Merge remote-tracking branch 'official/master' into contrib

This commit is contained in:
Léo Terziman
2015-12-08 15:25:13 +01:00
162 changed files with 18423 additions and 529 deletions

View File

@@ -138,7 +138,7 @@ struct Bone
}
//! Construction from an existing name
Bone( const std::string& name)
explicit Bone( const std::string& name)
: mName (name)
{}
@@ -216,7 +216,7 @@ struct BaseNode
enum Type {Light, Camera, Mesh, Dummy} mType;
//! Constructor. Creates a default name for the node
BaseNode(Type _mType)
explicit BaseNode(Type _mType)
: mType (_mType)
, mProcessed (false)
{

View File

@@ -110,7 +110,7 @@ static boost::mutex gLogStreamMutex;
class LogToCallbackRedirector : public LogStream
{
public:
LogToCallbackRedirector(const aiLogStream& s)
explicit LogToCallbackRedirector(const aiLogStream& s)
: stream (s) {
ai_assert(NULL != s.callback);
}

View File

@@ -59,13 +59,38 @@ ASSIMP_API size_t aiGetExportFormatCount(void)
// ------------------------------------------------------------------------------------------------
ASSIMP_API const aiExportFormatDesc* aiGetExportFormatDescription( size_t pIndex)
ASSIMP_API const aiExportFormatDesc* aiGetExportFormatDescription( size_t index)
{
// Note: this is valid as the index always pertains to a builtin exporter,
// Note: this is valid as the index always pertains to a built-in exporter,
// for which the returned structure is guaranteed to be of static storage duration.
return Exporter().GetExportFormatDescription(pIndex);
Exporter exporter;
const aiExportFormatDesc* orig( exporter.GetExportFormatDescription( index ) );
if (NULL == orig) {
return NULL;
}
aiExportFormatDesc *desc = new aiExportFormatDesc;
desc->description = new char[ strlen( orig->description ) + 1 ];
::strncpy( (char*) desc->description, orig->description, strlen( orig->description ) );
desc->fileExtension = new char[ strlen( orig->fileExtension ) + 1 ];
::strncpy( ( char* ) desc->fileExtension, orig->fileExtension, strlen( orig->fileExtension ) );
desc->id = new char[ strlen( orig->id ) + 1 ];
::strncpy( ( char* ) desc->id, orig->id, strlen( orig->id ) );
return desc;
}
// ------------------------------------------------------------------------------------------------
ASSIMP_API void aiReleaseExportFormatDescription( const aiExportFormatDesc *desc ) {
if (NULL == desc) {
return;
}
delete [] desc->description;
delete [] desc->fileExtension;
delete [] desc->id;
delete desc;
}
// ------------------------------------------------------------------------------------------------
ASSIMP_API void aiCopyScene(const aiScene* pIn, aiScene** pOut)

View File

@@ -83,7 +83,7 @@ class BVHLoader : public BaseImporter
std::vector<float> mChannelValues; // motion data values for that node. Of size NumChannels * NumFrames
Node() { }
Node( const aiNode* pNode) : mNode( pNode) { }
explicit Node( const aiNode* pNode) : mNode( pNode) { }
};
public:

View File

@@ -63,7 +63,7 @@ using namespace Assimp;
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
BaseImporter::BaseImporter()
: progress()
: m_progress()
{
// nothing to do here
}
@@ -79,8 +79,8 @@ BaseImporter::~BaseImporter()
// Imports the given file and returns the imported data.
aiScene* BaseImporter::ReadFile(const Importer* pImp, const std::string& pFile, IOSystem* pIOHandler)
{
progress = pImp->GetProgressHandler();
ai_assert(progress);
m_progress = pImp->GetProgressHandler();
ai_assert(m_progress);
// Gather configuration properties for this run
SetupProperties( pImp );
@@ -98,8 +98,8 @@ aiScene* BaseImporter::ReadFile(const Importer* pImp, const std::string& pFile,
} catch( const std::exception& err ) {
// extract error description
mErrorText = err.what();
DefaultLogger::get()->error(mErrorText);
m_ErrorText = err.what();
DefaultLogger::get()->error(m_ErrorText);
return NULL;
}
@@ -274,7 +274,7 @@ void BaseImporter::GetExtensionList(std::set<std::string>& extensions)
for (unsigned int i = 0; i < num; ++i) {
// also check against big endian versions of tokens with size 2,4
// that's just for convinience, the chance that we cause conflicts
// that's just for convenience, the chance that we cause conflicts
// is quite low and it can save some lines and prevent nasty bugs
if (2 == size) {
uint16_t rev = *magic_u16;

View File

@@ -70,7 +70,7 @@ class IOStream;
template <typename T>
struct ScopeGuard
{
ScopeGuard(T* obj) : obj(obj), mdismiss() {}
explicit ScopeGuard(T* obj) : obj(obj), mdismiss() {}
~ScopeGuard () throw() {
if (!mdismiss) {
delete obj;
@@ -181,7 +181,7 @@ public:
* string if there was no error.
*/
const std::string& GetErrorText() const {
return mErrorText;
return m_ErrorText;
}
// -------------------------------------------------------------------
@@ -359,13 +359,34 @@ public: // static utilities
IOStream* stream,
std::vector<char>& data);
// -------------------------------------------------------------------
/** Utility function to move a std::vector into a aiScene array
* @param vec The vector to be moved
* @param out The output pointer to the allocated array.
* @param numOut The output count of elements copied. */
template<typename T>
AI_FORCE_INLINE
static void CopyVector(
std::vector<T>& vec,
T*& out,
unsigned int& outLength)
{
outLength = vec.size();
if (outLength) {
out = new T[outLength];
std::swap_ranges(vec.begin(), vec.end(), out);
}
}
protected:
/** Error description in case there was one. */
std::string mErrorText;
std::string m_ErrorText;
/** Currently set progress handler */
ProgressHandler* progress;
ProgressHandler* m_progress;
};

View File

@@ -74,7 +74,7 @@ public:
template <typename T>
struct THeapData : public Base
{
THeapData(T* in)
explicit THeapData(T* in)
: data (in)
{}
@@ -89,7 +89,7 @@ public:
template <typename T>
struct TStaticData : public Base
{
TStaticData(T in)
explicit TStaticData(T in)
: data (in)
{}

View File

@@ -84,7 +84,12 @@ namespace Assimp {
template<typename T>
inline std::size_t Copy(uint8_t* data, T& field) {
#ifdef AI_BUILD_BIG_ENDIAN
T field_swapped=AI_BE(field);
std::memcpy(data, &field_swapped, sizeof(field)); return sizeof(field);
#else
std::memcpy(data, &AI_BE(field), sizeof(field)); return sizeof(field);
#endif
}
void Bitmap::WriteHeader(Header& header, IOStream* file) {

View File

@@ -57,7 +57,7 @@ class CIOStreamWrapper : public IOStream
friend class CIOSystemWrapper;
public:
CIOStreamWrapper(aiFile* pFile)
explicit CIOStreamWrapper(aiFile* pFile)
: mFile(pFile)
{}
@@ -110,7 +110,7 @@ private:
class CIOSystemWrapper : public IOSystem
{
public:
CIOSystemWrapper(aiFileIO* pFile)
explicit CIOSystemWrapper(aiFileIO* pFile)
: mFileSystem(pFile)
{}

View File

@@ -562,6 +562,19 @@ ADD_ASSIMP_IMPORTER(X
XFileExporter.cpp
)
ADD_ASSIMP_IMPORTER(GLTF
glTFAsset.h
glTFAsset.inl
glTFAssetWriter.h
glTFAssetWriter.inl
glTFImporter.cpp
glTFImporter.h
glTFExporter.h
glTFExporter.cpp
)
SET( Step_SRCS
StepExporter.h
StepExporter.cpp
@@ -632,15 +645,20 @@ SOURCE_GROUP( unzip FILES ${unzip_SRCS})
SET ( openddl_parser_SRCS
../contrib/openddlparser/code/OpenDDLParser.cpp
../contrib/openddlparser/code/DDLNode.cpp
../contrib/openddlparser/code/OpenDDLCommon.cpp
../contrib/openddlparser/code/OpenDDLExport.cpp
../contrib/openddlparser/code/Value.cpp
../contrib/openddlparser/include/openddlparser/OpenDDLParser.h
../contrib/openddlparser/include/openddlparser/OpenDDLParserUtils.h
../contrib/openddlparser/include/openddlparser/OpenDDLCommon.h
../contrib/openddlparser/include/openddlparser/OpenDDLExport.h
../contrib/openddlparser/include/openddlparser/DDLNode.h
../contrib/openddlparser/include/openddlparser/Value.h
)
SOURCE_GROUP( openddl_parser FILES ${openddl_parser_SRCS})
INCLUDE_DIRECTORIES( "../contrib/rapidjson/include" )
# VC2010 fixes
if(MSVC10)
option( VC10_STDINT_FIX "Fix for VC10 Compiler regarding pstdint.h redefinition errors" OFF )
@@ -766,7 +784,7 @@ INSTALL( TARGETS assimp
INSTALL( FILES ${PUBLIC_HEADERS} DESTINATION ${ASSIMP_INCLUDE_INSTALL_DIR}/assimp COMPONENT assimp-dev)
INSTALL( FILES ${COMPILER_HEADERS} DESTINATION ${ASSIMP_INCLUDE_INSTALL_DIR}/assimp/Compiler COMPONENT assimp-dev)
if (ASSIMP_ANDROID_JNIIOSYSTEM)
INSTALL(FILES ${HEADER_PATH}/../${ASSIMP_ANDROID_JNIIOSYSTEM_PATH}/AndroidJNIIOSystem.h
INSTALL(FILES ${HEADER_PATH}/${ASSIMP_ANDROID_JNIIOSYSTEM_PATH}/AndroidJNIIOSystem.h
DESTINATION ${ASSIMP_INCLUDE_INSTALL_DIR}
COMPONENT assimp-dev)
endif(ASSIMP_ANDROID_JNIIOSYSTEM)

View File

@@ -64,28 +64,47 @@ using namespace Assimp::Collada;
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
ColladaParser::ColladaParser( IOSystem* pIOHandler, const std::string& pFile)
: mFileName( pFile)
: mFileName( pFile )
, mReader( NULL )
, mDataLibrary()
, mAccessorLibrary()
, mMeshLibrary()
, mNodeLibrary()
, mImageLibrary()
, mEffectLibrary()
, mMaterialLibrary()
, mLightLibrary()
, mCameraLibrary()
, mControllerLibrary()
, mRootNode( NULL )
, mAnims()
, mUnitSize( 1.0f )
, mUpDirection( UP_Y )
, mFormat(FV_1_5_n ) // We assume the newest file format by default
{
mRootNode = NULL;
mUnitSize = 1.0f;
mUpDirection = UP_Y;
// validate io-handler instance
if ( NULL == pIOHandler ) {
throw DeadlyImportError("IOSystem is NULL." );
}
// We assume the newest file format by default
mFormat = FV_1_5_n;
// open the file
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
if( file.get() == NULL)
throw DeadlyImportError( "Failed to open file " + pFile + ".");
// open the file
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile ) );
if ( file.get() == NULL ) {
throw DeadlyImportError( "Failed to open file " + pFile + "." );
}
// generate a XML reader for it
boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper( new CIrrXML_IOStreamReader( file.get()));
boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper( new CIrrXML_IOStreamReader( file.get()));
mReader = irr::io::createIrrXMLReader( mIOWrapper.get());
if( !mReader)
ThrowException( "Collada: Unable to open file.");
if (!mReader) {
ThrowException("Collada: Unable to open file.");
}
// start reading
ReadContents();
// release file after import
//pIOHandler->Close( file.get() );
}
// ------------------------------------------------------------------------------------------------
@@ -1514,7 +1533,7 @@ void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam)
// don't care for remaining stuff
SkipElement( "surface");
}
else if( IsElement( "sampler2D"))
else if( IsElement( "sampler2D") && (FV_1_4_n == mFormat || FV_1_3_n == mFormat))
{
// surface ID is given inside <source> tags
TestOpening( "source");
@@ -1525,6 +1544,19 @@ void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam)
// don't care for remaining stuff
SkipElement( "sampler2D");
}
else if( IsElement( "sampler2D"))
{
// surface ID is given inside <instance_image> tags
TestOpening( "instance_image");
int attrURL = GetAttribute("url");
const char* url = mReader->getAttributeValue( attrURL);
if( url[0] != '#')
ThrowException( "Unsupported URL format in instance_image");
url++;
pParam.mType = Param_Sampler;
pParam.mReference = url;
SkipElement( "sampler2D");
} else
{
// ignore unknown element

View File

@@ -125,7 +125,7 @@ private:
// temporary structure to describe a mapping
struct MappingInfo
{
MappingInfo(aiTextureMapping _type)
explicit MappingInfo(aiTextureMapping _type)
: type (_type)
, axis (0.f,1.f,0.f)
, uv (0u)

View File

@@ -135,11 +135,11 @@ inline void MakeAbsolutePath (const char* in, char* _out)
{
ai_assert(in && _out);
char* ret;
#ifdef _WIN32
ret = ::_fullpath(_out, in,PATHLIMIT);
#if defined( _MSC_VER ) || defined( __MINGW32__ )
ret = ::_fullpath( _out, in, PATHLIMIT );
#else
// use realpath
ret = realpath(in, _out);
// use realpath
ret = realpath(in, _out);
#endif
if(!ret) {
// preserve the input path, maybe someone else is able to fix
@@ -167,8 +167,8 @@ bool DefaultIOSystem::ComparePaths (const char* one, const char* second) const
return !ASSIMP_stricmp(temp1,temp2);
}
std::string DefaultIOSystem::fileName(std::string path)
// ------------------------------------------------------------------------------------------------
std::string DefaultIOSystem::fileName( const std::string &path )
{
std::string ret = path;
std::size_t last = ret.find_last_of("\\/");
@@ -176,8 +176,8 @@ std::string DefaultIOSystem::fileName(std::string path)
return ret;
}
std::string DefaultIOSystem::completeBaseName(std::string path)
// ------------------------------------------------------------------------------------------------
std::string DefaultIOSystem::completeBaseName( const std::string &path )
{
std::string ret = fileName(path);
std::size_t pos = ret.find_last_of('.');
@@ -185,8 +185,8 @@ std::string DefaultIOSystem::completeBaseName(std::string path)
return ret;
}
std::string DefaultIOSystem::absolutePath(std::string path)
// ------------------------------------------------------------------------------------------------
std::string DefaultIOSystem::absolutePath( const std::string &path )
{
std::string ret = path;
std::size_t last = ret.find_last_of("\\/");
@@ -194,4 +194,6 @@ std::string DefaultIOSystem::absolutePath(std::string path)
return ret;
}
// ------------------------------------------------------------------------------------------------
#undef PATHLIMIT

View File

@@ -80,17 +80,17 @@ public:
/** @brief get the file name of a full filepath
* example: /tmp/archive.tar.gz -> archive.tar.gz
*/
static std::string fileName(std::string path);
static std::string fileName( const std::string &path );
/** @brief get the complete base name of a full filepath
* example: /tmp/archive.tar.gz -> archive.tar
*/
static std::string completeBaseName(std::string path);
static std::string completeBaseName( const std::string &path);
/** @brief get the path of a full filepath
* example: /tmp/archive.tar.gz -> /tmp/
*/
static std::string absolutePath(std::string path);
static std::string absolutePath( const std::string &path);
};
} //!ns Assimp

View File

@@ -87,6 +87,8 @@ void ExportSceneSTLBinary(const char*,IOSystem*, const aiScene*, const ExportPro
void ExportScenePly(const char*,IOSystem*, const aiScene*, const ExportProperties*);
void ExportScenePlyBinary(const char*, IOSystem*, const aiScene*, const ExportProperties*);
void ExportScene3DS(const char*, IOSystem*, const aiScene*, const ExportProperties*);
void ExportSceneGLTF(const char*, IOSystem*, const aiScene*, const ExportProperties*);
void ExportSceneGLB(const char*, IOSystem*, const aiScene*, const ExportProperties*);
void ExportSceneAssbin(const char*, IOSystem*, const aiScene*, const ExportProperties*);
void ExportSceneAssxml(const char*, IOSystem*, const aiScene*, const ExportProperties*);
@@ -135,6 +137,13 @@ Exporter::ExportFormatEntry gExporters[] =
aiProcess_Triangulate | aiProcess_SortByPType | aiProcess_JoinIdenticalVertices),
#endif
#ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER
Exporter::ExportFormatEntry( "gltf", "GL Transmission Format", "gltf", &ExportSceneGLTF,
aiProcess_JoinIdenticalVertices /*| aiProcess_SortByPType*/),
Exporter::ExportFormatEntry( "glb", "GL Transmission Format (binary)", "glb", &ExportSceneGLB,
aiProcess_JoinIdenticalVertices /*| aiProcess_SortByPType*/),
#endif
#ifndef ASSIMP_BUILD_NO_ASSBIN_EXPORTER
Exporter::ExportFormatEntry( "assbin", "Assimp Binary", "assbin" , &ExportSceneAssbin, 0),
#endif

View File

@@ -54,6 +54,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "FBXUtil.h"
#include "FBXProperties.h"
#include "FBXImporter.h"
#include "StringComparison.h"
#include "../include/assimp/scene.h"
#include <boost/foreach.hpp>
#include <boost/scoped_array.hpp>
@@ -148,6 +149,7 @@ public:
std::for_each(animations.begin(),animations.end(),Util::delete_fun<aiAnimation>());
std::for_each(lights.begin(),lights.end(),Util::delete_fun<aiLight>());
std::for_each(cameras.begin(),cameras.end(),Util::delete_fun<aiCamera>());
std::for_each(textures.begin(),textures.end(),Util::delete_fun<aiTexture>());
}
@@ -1449,6 +1451,36 @@ private:
return static_cast<unsigned int>(materials.size() - 1);
}
// ------------------------------------------------------------------------------------------------
// Video -> aiTexture
unsigned int ConvertVideo(const Video& video)
{
// generate empty output texture
aiTexture* out_tex = new aiTexture();
textures.push_back(out_tex);
// assuming the texture is compressed
out_tex->mWidth = static_cast<unsigned int>(video.ContentLength()); // total data size
out_tex->mHeight = 0; // fixed to 0
// steal the data from the Video to avoid an additional copy
out_tex->pcData = reinterpret_cast<aiTexel*>( const_cast<Video&>(video).RelinquishContent() );
// try to extract a hint from the file extension
const std::string& filename = video.FileName().empty() ? video.RelativeFilename() : video.FileName();
std::string ext = BaseImporter::GetExtension(filename);
if(ext == "jpeg") {
ext = "jpg";
}
if(ext.size() <= 3) {
memcpy(out_tex->achFormatHint, ext.c_str(), ext.size());
}
return static_cast<unsigned int>(textures.size() - 1);
}
// ------------------------------------------------------------------------------------------------
void TrySetTextureProperties(aiMaterial* out_mat, const TextureMap& textures,
@@ -1466,6 +1498,24 @@ private:
aiString path;
path.Set(tex->RelativeFilename());
const Video* media = tex->Media();
if(media != 0 && media->ContentLength() > 0) {
unsigned int index;
VideoMap::const_iterator it = textures_converted.find(media);
if(it != textures_converted.end()) {
index = (*it).second;
}
else {
index = ConvertVideo(*media);
textures_converted[media] = index;
}
// setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
path.data[0] = '*';
path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index);
}
out_mat->AddProperty(&path,_AI_MATKEY_TEXTURE_BASE,target,0);
aiUVTransform uvTrafo;
@@ -2496,8 +2546,9 @@ private:
// need to convert from TRS order to SRT?
if(reverse_order) {
aiVector3D def_scale, def_translate;
aiQuaternion def_rot;
aiVector3D def_scale = PropertyGet(props,"Lcl Scaling",aiVector3D(1.f,1.f,1.f));
aiVector3D def_translate = PropertyGet(props,"Lcl Translation",aiVector3D(0.f,0.f,0.f));
aiVector3D def_rot = PropertyGet(props,"Lcl Rotation",aiVector3D(0.f,0.f,0.f));
KeyFrameListList scaling;
KeyFrameListList translation;
@@ -2506,24 +2557,14 @@ private:
if(chain[TransformationComp_Scaling] != iter_end) {
scaling = GetKeyframeList((*chain[TransformationComp_Scaling]).second, start, stop);
}
else {
def_scale = PropertyGet(props,"Lcl Scaling",aiVector3D(1.f,1.f,1.f));
}
if(chain[TransformationComp_Translation] != iter_end) {
translation = GetKeyframeList((*chain[TransformationComp_Translation]).second, start, stop);
}
else {
def_translate = PropertyGet(props,"Lcl Translation",aiVector3D(0.f,0.f,0.f));
}
if(chain[TransformationComp_Rotation] != iter_end) {
rotation = GetKeyframeList((*chain[TransformationComp_Rotation]).second, start, stop);
}
else {
def_rot = EulerToQuaternion(PropertyGet(props,"Lcl Rotation",aiVector3D(0.f,0.f,0.f)),
target.RotationOrder());
}
KeyFrameListList joined;
joined.insert(joined.end(), scaling.begin(), scaling.end());
@@ -2740,7 +2781,7 @@ private:
// ------------------------------------------------------------------------------------------------
void InterpolateKeys(aiVectorKey* valOut,const KeyTimeList& keys, const KeyFrameListList& inputs,
const bool geom,
const aiVector3D& def_value,
double& max_time,
double& min_time)
@@ -2754,10 +2795,7 @@ private:
next_pos.resize(inputs.size(),0);
BOOST_FOREACH(KeyTimeList::value_type time, keys) {
float result[3] = {0.0f, 0.0f, 0.0f};
if(geom) {
result[0] = result[1] = result[2] = 1.0f;
}
float result[3] = {def_value.x, def_value.y, def_value.z};
for (size_t i = 0; i < count; ++i) {
const KeyFrameList& kfl = inputs[i];
@@ -2782,12 +2820,7 @@ private:
const double factor = timeB == timeA ? 0. : static_cast<double>((time - timeA) / (timeB - timeA));
const float interpValue = static_cast<float>(valueA + (valueB - valueA) * factor);
if(geom) {
result[kfl.get<2>()] *= interpValue;
}
else {
result[kfl.get<2>()] += interpValue;
}
result[kfl.get<2>()] = interpValue;
}
// magic value to convert fbx times to seconds
@@ -2807,7 +2840,7 @@ private:
// ------------------------------------------------------------------------------------------------
void InterpolateKeys(aiQuatKey* valOut,const KeyTimeList& keys, const KeyFrameListList& inputs,
const bool geom,
const aiVector3D& def_value,
double& maxTime,
double& minTime,
Model::RotOrder order)
@@ -2816,7 +2849,7 @@ private:
ai_assert(valOut);
boost::scoped_array<aiVectorKey> temp(new aiVectorKey[keys.size()]);
InterpolateKeys(temp.get(),keys,inputs,geom,maxTime, minTime);
InterpolateKeys(temp.get(), keys, inputs, def_value, maxTime, minTime);
aiMatrix4x4 m;
@@ -2858,20 +2891,20 @@ private:
Model::RotOrder order,
const aiVector3D& def_scale,
const aiVector3D& def_translate,
const aiQuaternion& def_rotation)
const aiVector3D& def_rotation)
{
if (rotation.size()) {
InterpolateKeys(out_quat, times, rotation, false, maxTime, minTime, order);
InterpolateKeys(out_quat, times, rotation, def_rotation, maxTime, minTime, order);
}
else {
for (size_t i = 0; i < times.size(); ++i) {
out_quat[i].mTime = CONVERT_FBX_TIME(times[i]) * anim_fps;
out_quat[i].mValue = def_rotation;
out_quat[i].mValue = EulerToQuaternion(def_rotation, order);
}
}
if (scaling.size()) {
InterpolateKeys(out_scale, times, scaling, true, maxTime, minTime);
InterpolateKeys(out_scale, times, scaling, def_scale, maxTime, minTime);
}
else {
for (size_t i = 0; i < times.size(); ++i) {
@@ -2881,7 +2914,7 @@ private:
}
if (translation.size()) {
InterpolateKeys(out_translation, times, translation, false, maxTime, minTime);
InterpolateKeys(out_translation, times, translation, def_translate, maxTime, minTime);
}
else {
for (size_t i = 0; i < times.size(); ++i) {
@@ -2935,7 +2968,7 @@ private:
na->mNumScalingKeys = static_cast<unsigned int>(keys.size());
na->mScalingKeys = new aiVectorKey[keys.size()];
if (keys.size() > 0)
InterpolateKeys(na->mScalingKeys, keys, inputs, true, maxTime, minTime);
InterpolateKeys(na->mScalingKeys, keys, inputs, aiVector3D(1.0f, 1.0f, 1.0f), maxTime, minTime);
}
@@ -2955,7 +2988,7 @@ private:
na->mNumPositionKeys = static_cast<unsigned int>(keys.size());
na->mPositionKeys = new aiVectorKey[keys.size()];
if (keys.size() > 0)
InterpolateKeys(na->mPositionKeys, keys, inputs, false, maxTime, minTime);
InterpolateKeys(na->mPositionKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime);
}
@@ -2976,7 +3009,7 @@ private:
na->mNumRotationKeys = static_cast<unsigned int>(keys.size());
na->mRotationKeys = new aiQuatKey[keys.size()];
if (keys.size() > 0)
InterpolateKeys(na->mRotationKeys, keys, inputs, false, maxTime, minTime, order);
InterpolateKeys(na->mRotationKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime, order);
}
@@ -3024,6 +3057,13 @@ private:
std::swap_ranges(cameras.begin(),cameras.end(),out->mCameras);
}
if(textures.size()) {
out->mTextures = new aiTexture*[textures.size()]();
out->mNumTextures = static_cast<unsigned int>(textures.size());
std::swap_ranges(textures.begin(),textures.end(),out->mTextures);
}
}
@@ -3037,10 +3077,14 @@ private:
std::vector<aiAnimation*> animations;
std::vector<aiLight*> lights;
std::vector<aiCamera*> cameras;
std::vector<aiTexture*> textures;
typedef std::map<const Material*, unsigned int> MaterialMap;
MaterialMap materials_converted;
typedef std::map<const Video*, unsigned int> VideoMap;
VideoMap textures_converted;
typedef std::map<const Geometry*, std::vector<unsigned int> > MeshMap;
MeshMap meshes_converted;

View File

@@ -180,6 +180,9 @@ const Object* LazyObject::Get(bool dieOnError)
else if (!strncmp(obtype,"LayeredTexture",length)) {
object.reset(new LayeredTexture(id,element,doc,name));
}
else if (!strncmp(obtype,"Video",length)) {
object.reset(new Video(id,element,doc,name));
}
else if (!strncmp(obtype,"AnimationStack",length)) {
object.reset(new AnimationStack(id,element,name,doc));
}
@@ -483,6 +486,11 @@ void Document::ReadConnections()
for(ElementMap::const_iterator it = conns.first; it != conns.second; ++it) {
const Element& el = *(*it).second;
const std::string& type = ParseTokenAsString(GetRequiredToken(el,0));
// PP = property-property connection, ignored for now
// (tokens: "PP", ID1, "Property1", ID2, "Property2")
if(type == "PP") continue;
const uint64_t src = ParseTokenAsID(GetRequiredToken(el,1));
const uint64_t dest = ParseTokenAsID(GetRequiredToken(el,2));

View File

@@ -73,6 +73,8 @@ namespace FBX {
class Material;
class Geometry;
class Video;
class AnimationCurve;
class AnimationCurveNode;
class AnimationLayer;
@@ -571,6 +573,10 @@ public:
return crop;
}
const Video* Media() const {
return media;
}
private:
aiVector2D uvTrans;
@@ -583,6 +589,8 @@ private:
boost::shared_ptr<const PropertyTable> props;
unsigned int crop[4];
const Video* media;
};
/** DOM class for layered FBX textures */
@@ -654,6 +662,59 @@ typedef std::fbx_unordered_map<std::string, const Texture*> TextureMap;
typedef std::fbx_unordered_map<std::string, const LayeredTexture*> LayeredTextureMap;
/** DOM class for generic FBX videos */
class Video : public Object
{
public:
Video(uint64_t id, const Element& element, const Document& doc, const std::string& name);
~Video();
public:
const std::string& Type() const {
return type;
}
const std::string& FileName() const {
return fileName;
}
const std::string& RelativeFilename() const {
return relativeFileName;
}
const PropertyTable& Props() const {
ai_assert(props.get());
return *props.get();
}
const uint8_t* Content() const {
ai_assert(content);
return content;
}
const uint32_t ContentLength() const {
return contentLength;
}
uint8_t* RelinquishContent() {
uint8_t* ptr = content;
content = 0;
return ptr;
}
private:
std::string type;
std::string relativeFileName;
std::string fileName;
boost::shared_ptr<const PropertyTable> props;
uint32_t contentLength;
uint8_t* content;
};
/** DOM class for generic FBX materials */
class Material : public Object
{

View File

@@ -55,6 +55,7 @@ struct ImportSettings
, readAllLayers(true)
, readAllMaterials(false)
, readMaterials(true)
, readTextures(true)
, readCameras(true)
, readLights(true)
, readAnimations(true)
@@ -92,6 +93,9 @@ struct ImportSettings
* material. The default value is true.*/
bool readMaterials;
/** import embedded textures? Default value is true.*/
bool readTextures;
/** import cameras? Default value is true.*/
bool readCameras;

View File

@@ -126,6 +126,7 @@ void FBXImporter::SetupProperties(const Importer* pImp)
settings.readAllLayers = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_READ_ALL_GEOMETRY_LAYERS, true);
settings.readAllMaterials = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_READ_ALL_MATERIALS, false);
settings.readMaterials = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_READ_MATERIALS, true);
settings.readTextures = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_READ_TEXTURES, true);
settings.readCameras = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_READ_CAMERAS, true);
settings.readLights = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_READ_LIGHTS, true);
settings.readAnimations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_READ_ANIMATIONS, true);

View File

@@ -50,6 +50,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "FBXImportSettings.h"
#include "FBXDocumentUtil.h"
#include "FBXProperties.h"
#include "ByteSwapper.h"
#include <boost/foreach.hpp>
namespace Assimp {
@@ -147,6 +148,7 @@ Material::~Material()
Texture::Texture(uint64_t id, const Element& element, const Document& doc, const std::string& name)
: Object(id,element,name)
, uvScaling(1.0f,1.0f)
, media(0)
{
const Scope& sc = GetRequiredScope(element);
@@ -199,6 +201,23 @@ Texture::Texture(uint64_t id, const Element& element, const Document& doc, const
}
props = GetPropertyTable(doc,"Texture.FbxFileTexture",element,sc);
// resolve video links
if(doc.Settings().readTextures) {
const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID());
BOOST_FOREACH(const Connection* con, conns) {
const Object* const ob = con->SourceObject();
if(!ob) {
DOMWarning("failed to read source object for texture link, ignoring",&element);
continue;
}
const Video* const video = dynamic_cast<const Video*>(ob);
if(video) {
media = video;
}
}
}
}
@@ -253,6 +272,68 @@ void LayeredTexture::fillTexture(const Document& doc)
}
}
// ------------------------------------------------------------------------------------------------
Video::Video(uint64_t id, const Element& element, const Document& doc, const std::string& name)
: Object(id,element,name)
, contentLength(0)
, content(0)
{
const Scope& sc = GetRequiredScope(element);
const Element* const Type = sc["Type"];
const Element* const FileName = sc["FileName"];
const Element* const RelativeFilename = sc["RelativeFilename"];
const Element* const Content = sc["Content"];
if(Type) {
type = ParseTokenAsString(GetRequiredToken(*Type,0));
}
if(FileName) {
fileName = ParseTokenAsString(GetRequiredToken(*FileName,0));
}
if(RelativeFilename) {
relativeFileName = ParseTokenAsString(GetRequiredToken(*RelativeFilename,0));
}
if(Content) {
const Token& token = GetRequiredToken(*Content, 0);
const char* data = token.begin();
if(!token.IsBinary()) {
DOMWarning("video content is not binary data, ignoring", &element);
}
else if(static_cast<size_t>(token.end() - data) < 5) {
DOMError("binary data array is too short, need five (5) bytes for type signature and element count", &element);
}
else if(*data != 'R') {
DOMWarning("video content is not raw binary data, ignoring", &element);
}
else {
// read number of elements
uint32_t len = 0;
::memcpy(&len, data + 1, sizeof(len));
AI_SWAP4(len);
contentLength = len;
content = new uint8_t[len];
::memcpy(content, data + 5, len);
}
}
props = GetPropertyTable(doc,"Video.FbxVideo",element,sc);
}
Video::~Video()
{
if(content) {
delete[] content;
}
}
} //!FBX
} //!Assimp

View File

@@ -87,7 +87,7 @@ class TypedProperty : public Property
{
public:
TypedProperty(const T& value)
explicit TypedProperty(const T& value)
: value(value)
{
}

View File

@@ -113,7 +113,7 @@ private:
} type;
Animator(AT t = UNKNOWN)
explicit Animator(AT t = UNKNOWN)
: type (t)
, speed (0.001f)
, direction (0.f,1.f,0.f)
@@ -163,7 +163,7 @@ private:
ANIMMESH
} type;
Node(ET t)
explicit Node(ET t)
: type (t)
, scaling (1.f,1.f,1.f) // assume uniform scaling by default
, parent()

View File

@@ -491,7 +491,7 @@ const aiScene* Importer::ReadFileFromMemory( const void* pBuffer,
pHint = "";
}
if (!pBuffer || !pLength || strlen(pHint) > 100) {
if (!pBuffer || !pLength || strlen(pHint) > MaxLenHint ) {
pimpl->mErrorString = "Invalid parameters passed to ReadFileFromMemory()";
return NULL;
}
@@ -503,7 +503,8 @@ const aiScene* Importer::ReadFileFromMemory( const void* pBuffer,
SetIOHandler(new MemoryIOSystem((const uint8_t*)pBuffer,pLength));
// read the file and recover the previous IOSystem
char fbuff[128];
static const size_t BufferSize(Importer::MaxLenHint + 28);
char fbuff[ BufferSize ];
sprintf(fbuff,"%s.%s",AI_MEMORYIO_MAGIC_FILENAME,pHint);
ReadFile(fbuff,pFlags);

View File

@@ -167,7 +167,7 @@ public:
// -------------------------------------------------------------------
/** Construct a batch loader from a given IO system to be used
* to acess external files */
BatchLoader(IOSystem* pIO);
explicit BatchLoader(IOSystem* pIO);
~BatchLoader();

View File

@@ -170,7 +170,9 @@ corresponding preprocessor flag to selectively disable formats.
#ifndef ASSIMP_BUILD_NO_ASSBIN_IMPORTER
# include "AssbinLoader.h"
#endif
#ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
# include "glTFImporter.h"
#endif
#ifndef ASSIMP_BUILD_NO_C4D_IMPORTER
# include "C4DImporter.h"
#endif
@@ -305,8 +307,10 @@ void GetImporterInstanceList(std::vector< BaseImporter* >& out)
#if ( !defined ASSIMP_BUILD_NO_ASSBIN_IMPORTER )
out.push_back( new AssbinImporter() );
#endif
#ifndef ASSIMP_BUILD_NO_C4D_IMPORTER
#if ( !defined ASSIMP_BUILD_NO_GLTF_IMPORTER )
out.push_back( new glTFImporter() );
#endif
#if ( !defined ASSIMP_BUILD_NO_C4D_IMPORTER )
out.push_back( new C4DImporter() );
#endif
}

View File

@@ -269,7 +269,7 @@ struct Face : public aiFace
{}
//! Construction from given type
Face(uint32_t _type)
explicit Face(uint32_t _type)
: surfaceIndex (0)
, smoothGroup (0)
, type (_type)
@@ -305,7 +305,7 @@ struct Face : public aiFace
*/
struct VMapEntry
{
VMapEntry(unsigned int _dims)
explicit VMapEntry(unsigned int _dims)
: dims(_dims)
{}

View File

@@ -285,9 +285,6 @@ void MD5Importer::AttachChilds_Mesh(int iParentID,aiNode* piParent, BoneList& bo
aiQuaternion quat;
MD5::ConvertQuaternion ( bones[i].mRotationQuat, quat );
// FIX to get to Assimp's quaternion conventions
quat.w *= -1.f;
bones[i].mTransform = aiMatrix4x4 ( quat.GetMatrix());
bones[i].mTransform.a4 = bones[i].mPositionXYZ.x;
bones[i].mTransform.b4 = bones[i].mPositionXYZ.y;
@@ -656,9 +653,6 @@ void MD5Importer::LoadMD5AnimFile ()
MD5::ConvertQuaternion(vTemp, qKey->mValue);
qKey->mTime = vKey->mTime = dTime;
// we need this to get to Assimp quaternion conventions
qKey->mValue.w *= -1.f;
}
}

View File

@@ -262,6 +262,9 @@ inline void ConvertQuaternion (const aiVector3D& in, aiQuaternion& out) {
if (t < 0.0f)
out.w = 0.0f;
else out.w = std::sqrt (t);
// Assimp convention.
out.w *= -1.f;
}
// ---------------------------------------------------------------------------
@@ -277,7 +280,7 @@ public:
*
* @param mSections List of file sections (output of MD5Parser)
*/
MD5MeshParser(SectionList& mSections);
explicit MD5MeshParser(SectionList& mSections);
//! List of all meshes
MeshList mMeshes;
@@ -302,7 +305,7 @@ public:
*
* @param mSections List of file sections (output of MD5Parser)
*/
MD5AnimParser(SectionList& mSections);
explicit MD5AnimParser(SectionList& mSections);
//! Output frame rate
@@ -334,7 +337,7 @@ public:
*
* @param mSections List of file sections (output of MD5Parser)
*/
MD5CameraParser(SectionList& mSections);
explicit MD5CameraParser(SectionList& mSections);
//! Output frame rate

View File

@@ -138,9 +138,15 @@ void OFFImporter::InternReadFile( const std::string& pFile,
throw DeadlyImportError("OFF: There are no valid faces");
}
pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes = 1 ];
aiMesh* mesh = pScene->mMeshes[0] = new aiMesh();
aiFace* faces = mesh->mFaces = new aiFace [mesh->mNumFaces = numFaces];
pScene->mNumMeshes = 1;
pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ];
aiMesh* mesh = new aiMesh();
pScene->mMeshes[0] = mesh;
mesh->mNumFaces = numFaces;
aiFace* faces = new aiFace [mesh->mNumFaces];
mesh->mFaces = faces;
std::vector<aiVector3D> tempPositions(numVertices);
@@ -171,7 +177,8 @@ void OFFImporter::InternReadFile( const std::string& pFile,
break;
}
sz = line;SkipSpaces(&sz);
if(!(faces->mNumIndices = strtoul10(sz,&sz)) || faces->mNumIndices > 9)
faces->mNumIndices = strtoul10(sz,&sz);
if(!(faces->mNumIndices) || faces->mNumIndices > 9)
{
DefaultLogger::get()->error("OFF: Faces with zero indices aren't allowed");
--mesh->mNumFaces;
@@ -185,43 +192,54 @@ void OFFImporter::InternReadFile( const std::string& pFile,
throw DeadlyImportError("OFF: There are no valid faces");
// allocate storage for the output vertices
aiVector3D* verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
std::vector<aiVector3D> verts;
verts.reserve(mesh->mNumVertices);
// second: now parse all face indices
buffer = old;faces = mesh->mFaces;
buffer = old;
faces = mesh->mFaces;
for (unsigned int i = 0, p = 0; i< mesh->mNumFaces;)
{
if(!GetNextLine(buffer,line))break;
unsigned int idx;
sz = line;SkipSpaces(&sz);
if(!(idx = strtoul10(sz,&sz)) || idx > 9)
idx = strtoul10(sz,&sz);
if(!(idx) || idx > 9)
continue;
faces->mIndices = new unsigned int [faces->mNumIndices];
for (unsigned int m = 0; m < faces->mNumIndices;++m)
{
SkipSpaces(&sz);
if ((idx = strtoul10(sz,&sz)) >= numVertices)
idx = strtoul10(sz,&sz);
if ((idx) >= numVertices)
{
DefaultLogger::get()->error("OFF: Vertex index is out of range");
idx = numVertices-1;
}
faces->mIndices[m] = p++;
*verts++ = tempPositions[idx];
verts.push_back(tempPositions[idx]);
}
++i;
++faces;
}
if (mesh->mNumVertices != verts.size()) {
throw DeadlyImportError("OFF: Vertex count mismatch");
}
mesh->mVertices = new aiVector3D[verts.size()];
memcpy(mesh->mVertices, &verts[0], verts.size() * sizeof(aiVector3D));
// generate the output node graph
pScene->mRootNode = new aiNode();
pScene->mRootNode->mName.Set("<OFFRoot>");
pScene->mRootNode->mMeshes = new unsigned int [pScene->mRootNode->mNumMeshes = 1];
pScene->mRootNode->mNumMeshes = 1;
pScene->mRootNode->mMeshes = new unsigned int [pScene->mRootNode->mNumMeshes];
pScene->mRootNode->mMeshes[0] = 0;
// generate a default material
pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = 1];
pScene->mNumMaterials = 1;
pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
aiMaterial* pcMat = new aiMaterial();
aiColor4D clr(0.6f,0.6f,0.6f,1.0f);

View File

@@ -156,6 +156,7 @@ struct Material
aiString textureEmissive;
aiString textureBump;
aiString textureNormal;
aiString textureReflection[6];
aiString textureSpecularity;
aiString textureOpacity;
aiString textureDisp;
@@ -167,6 +168,13 @@ struct Material
TextureEmissiveType,
TextureBumpType,
TextureNormalType,
TextureReflectionSphereType,
TextureReflectionCubeTopType,
TextureReflectionCubeBottomType,
TextureReflectionCubeFrontType,
TextureReflectionCubeBackType,
TextureReflectionCubeLeftType,
TextureReflectionCubeRightType,
TextureSpecularityType,
TextureOpacityType,
TextureDispType,
@@ -234,7 +242,7 @@ struct Mesh {
bool m_hasNormals;
/// Constructor
Mesh( const std::string &name )
explicit Mesh( const std::string &name )
: m_name( name )
, m_pMaterial(NULL)
, m_uiNumIndices(0)

View File

@@ -138,7 +138,7 @@ void ObjFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene,
if ( pos != std::string::npos ) {
modelName = pFile.substr(pos+1, pFile.size() - pos - 1);
folderName = pFile.substr( 0, pos );
if ( folderName.empty() ) {
if ( !folderName.empty() ) {
pIOHandler->PushDirectory( folderName );
}
} else {
@@ -636,6 +636,22 @@ void ObjFileImporter::createMaterials(const ObjFile::Model* pModel, aiScene* pSc
}
}
if( 0 != pCurrentMaterial->textureReflection[0].length )
{
ObjFile::Material::TextureType type = 0 != pCurrentMaterial->textureReflection[1].length ?
ObjFile::Material::TextureReflectionCubeTopType :
ObjFile::Material::TextureReflectionSphereType;
unsigned count = type == ObjFile::Material::TextureReflectionSphereType ? 1 : 6;
for( unsigned i = 0; i < count; i++ )
mat->AddProperty(&pCurrentMaterial->textureReflection[i], AI_MATKEY_TEXTURE_REFLECTION(i));
if(pCurrentMaterial->clamp[type])
//TODO addTextureMappingModeProperty should accept an index to handle clamp option for each
//texture of a cubemap
addTextureMappingModeProperty(mat, aiTextureType_REFLECTION);
}
if ( 0 != pCurrentMaterial->textureDisp.length )
{
mat->AddProperty( &pCurrentMaterial->textureDisp, AI_MATKEY_TEXTURE_DISPLACEMENT(0) );

View File

@@ -64,6 +64,7 @@ static const std::string BumpTexture1 = "map_bump";
static const std::string BumpTexture2 = "map_Bump";
static const std::string BumpTexture3 = "bump";
static const std::string NormalTexture = "map_Kn";
static const std::string ReflectionTexture = "refl";
static const std::string DisplacementTexture = "disp";
static const std::string SpecularityTexture = "map_ns";
@@ -200,6 +201,7 @@ void ObjFileMtlImporter::load()
case 'm': // Texture
case 'b': // quick'n'dirty - for 'bump' sections
case 'r': // quick'n'dirty - for 'refl' sections
{
getTexture();
m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
@@ -332,6 +334,9 @@ void ObjFileMtlImporter::getTexture() {
// Normal map
out = & m_pModel->m_pCurrentMaterial->textureNormal;
clampIndex = ObjFile::Material::TextureNormalType;
} else if(!ASSIMP_strincmp( pPtr, ReflectionTexture.c_str(), ReflectionTexture.size() ) ) {
// Reflection texture(s)
//Do nothing here
} else if (!ASSIMP_strincmp( pPtr, DisplacementTexture.c_str(), DisplacementTexture.size() ) ) {
// Displacement texture
out = &m_pModel->m_pCurrentMaterial->textureDisp;
@@ -346,7 +351,7 @@ void ObjFileMtlImporter::getTexture() {
}
bool clamp = false;
getTextureOption(clamp);
getTextureOption(clamp, clampIndex, out);
m_pModel->m_pCurrentMaterial->clamp[clampIndex] = clamp;
std::string texture;
@@ -369,7 +374,7 @@ void ObjFileMtlImporter::getTexture() {
* Because aiMaterial supports clamp option, so we also want to return it
* /////////////////////////////////////////////////////////////////////////////
*/
void ObjFileMtlImporter::getTextureOption(bool &clamp)
void ObjFileMtlImporter::getTextureOption(bool &clamp, int &clampIndex, aiString *&out)
{
m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
@@ -392,13 +397,55 @@ void ObjFileMtlImporter::getTextureOption(bool &clamp)
skipToken = 2;
}
else if ( !ASSIMP_strincmp(pPtr, BlendUOption.c_str(), BlendUOption.size())
else if( !ASSIMP_strincmp( pPtr, TypeOption.c_str(), TypeOption.size() ) )
{
DataArrayIt it = getNextToken<DataArrayIt>( m_DataIt, m_DataItEnd );
char value[ 12 ];
CopyNextWord( it, m_DataItEnd, value, sizeof( value ) / sizeof( *value ) );
if( !ASSIMP_strincmp( value, "cube_top", 8 ) )
{
clampIndex = ObjFile::Material::TextureReflectionCubeTopType;
out = &m_pModel->m_pCurrentMaterial->textureReflection[0];
}
else if( !ASSIMP_strincmp( value, "cube_bottom", 11 ) )
{
clampIndex = ObjFile::Material::TextureReflectionCubeBottomType;
out = &m_pModel->m_pCurrentMaterial->textureReflection[1];
}
else if( !ASSIMP_strincmp( value, "cube_front", 10 ) )
{
clampIndex = ObjFile::Material::TextureReflectionCubeFrontType;
out = &m_pModel->m_pCurrentMaterial->textureReflection[2];
}
else if( !ASSIMP_strincmp( value, "cube_back", 9 ) )
{
clampIndex = ObjFile::Material::TextureReflectionCubeBackType;
out = &m_pModel->m_pCurrentMaterial->textureReflection[3];
}
else if( !ASSIMP_strincmp( value, "cube_left", 9 ) )
{
clampIndex = ObjFile::Material::TextureReflectionCubeLeftType;
out = &m_pModel->m_pCurrentMaterial->textureReflection[4];
}
else if( !ASSIMP_strincmp( value, "cube_right", 10 ) )
{
clampIndex = ObjFile::Material::TextureReflectionCubeRightType;
out = &m_pModel->m_pCurrentMaterial->textureReflection[5];
}
else if( !ASSIMP_strincmp( value, "sphere", 6 ) )
{
clampIndex = ObjFile::Material::TextureReflectionSphereType;
out = &m_pModel->m_pCurrentMaterial->textureReflection[0];
}
skipToken = 2;
}
else if (!ASSIMP_strincmp(pPtr, BlendUOption.c_str(), BlendUOption.size())
|| !ASSIMP_strincmp(pPtr, BlendVOption.c_str(), BlendVOption.size())
|| !ASSIMP_strincmp(pPtr, BoostOption.c_str(), BoostOption.size())
|| !ASSIMP_strincmp(pPtr, ResolutionOption.c_str(), ResolutionOption.size())
|| !ASSIMP_strincmp(pPtr, BumpOption.c_str(), BumpOption.size())
|| !ASSIMP_strincmp(pPtr, ChannelOption.c_str(), ChannelOption.size())
|| !ASSIMP_strincmp(pPtr, TypeOption.c_str(), TypeOption.size()) )
|| !ASSIMP_strincmp(pPtr, ChannelOption.c_str(), ChannelOption.size()))
{
skipToken = 2;
}

View File

@@ -43,6 +43,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
struct aiColor3D;
struct aiString;
namespace Assimp {
@@ -89,7 +90,7 @@ private:
void createMaterial();
/// Get texture name from loaded data.
void getTexture();
void getTextureOption(bool &clamp);
void getTextureOption(bool &clamp, int &clampIndex, aiString *&out);
private:
//! Absolute pathname

View File

@@ -414,7 +414,7 @@ void ObjFileParser::getFace(aiPrimitiveType type)
if ( pIndices->empty() ) {
DefaultLogger::get()->error("Obj: Ignoring empty face");
// skip line and clean up
// skip line and clean up
m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
delete pNormalID;
delete pTexID;
@@ -539,7 +539,10 @@ void ObjFileParser::getMaterialLib()
const std::string strMatName(pStart, &(*m_DataIt));
std::string absName;
if ( m_pIO->StackSize() > 0 ) {
const std::string &path = m_pIO->CurrentDirectory();
std::string path = m_pIO->CurrentDirectory();
if ( '/' != *path.rbegin() ) {
path += '/';
}
absName = path + strMatName;
} else {
absName = strMatName;

View File

@@ -381,8 +381,8 @@ typedef std::vector<VertexAnimationTrack> VertexAnimationTrackList;
class Animation
{
public:
Animation(Skeleton *parent);
Animation(Mesh *parent);
explicit Animation(Skeleton *parent);
explicit Animation(Mesh *parent);
/// Returns the associated vertex data for a track in this animation.
/** @note Only valid to call when parent Mesh is set. */

View File

@@ -69,7 +69,7 @@ public:
static bool ImportSkeleton(Assimp::IOSystem *pIOHandler, Mesh *mesh);
private:
OgreXmlSerializer(XmlReader *reader) :
explicit OgreXmlSerializer(XmlReader *reader) :
m_reader(reader)
{
}

View File

@@ -801,6 +801,19 @@ void OpenGEXImporter::handleColorNode( ODDLParser::DDLNode *node, aiScene *pScen
}
}
//------------------------------------------------------------------------------------------------
bool isSpecialRootDir(aiString &texName) {
if (texName.length < 2) {
return false;
}
if (texName.data[0] = '/' || texName.data[1] == '/') {
return true;
}
return false;
}
//------------------------------------------------------------------------------------------------
void OpenGEXImporter::handleTextureNode( ODDLParser::DDLNode *node, aiScene *pScene ) {
if( NULL == node ) {

View File

@@ -857,7 +857,7 @@ bool PLY::PropertyInstance::ParseValueBinary(
case EDT_UShort:
{
int16_t i = *((uint16_t*)pCur);
uint16_t i = *((uint16_t*)pCur);
// Swap endianess
if (p_bBE)ByteSwap::Swap(&i);

View File

@@ -325,7 +325,7 @@ void Q3BSPFileImporter::CreateNodes( const Q3BSP::Q3BSPModel *pModel, aiScene* p
matIdx++;
}
pScene->mNumMeshes = MeshArray.size();
pScene->mNumMeshes = static_cast<unsigned int>( MeshArray.size() );
if ( pScene->mNumMeshes > 0 )
{
pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ];

View File

@@ -90,7 +90,7 @@ class ZipFile : public IOStream {
public:
ZipFile(size_t size);
explicit ZipFile(size_t size);
~ZipFile();

View File

@@ -103,7 +103,7 @@ private:
struct Face
{
Face(unsigned int s)
explicit Face(unsigned int s)
: indices (s)
, uvindices (s)
, mat (0)

View File

@@ -88,7 +88,7 @@ private:
struct MeshInformation
{
MeshInformation(const std::string& _name)
explicit MeshInformation(const std::string& _name)
: name(_name)
{
vertices.reserve(100);
@@ -103,7 +103,7 @@ private:
struct GroupInformation
{
GroupInformation(const std::string& _name)
explicit GroupInformation(const std::string& _name)
: name(_name)
{
meshes.reserve(10);

View File

@@ -66,7 +66,7 @@ public:
/** Construction from a given face array, handling smoothing groups
* properly
*/
SGSpatialSort(const std::vector<aiVector3D>& vPositions);
explicit SGSpatialSort(const std::vector<aiVector3D>& vPositions);
// -------------------------------------------------------------------
/** Add a vertex to the spatial sort

View File

@@ -74,7 +74,7 @@ static const aiImporterDesc desc = {
// 1) 80 byte header
// 2) 4 byte face count
// 3) 50 bytes per face
bool IsBinarySTL(const char* buffer, unsigned int fileSize) {
static bool IsBinarySTL(const char* buffer, unsigned int fileSize) {
if( fileSize < 84 ) {
return false;
}
@@ -88,7 +88,7 @@ bool IsBinarySTL(const char* buffer, unsigned int fileSize) {
// An ascii STL buffer will begin with "solid NAME", where NAME is optional.
// Note: The "solid NAME" check is necessary, but not sufficient, to determine
// if the buffer is ASCII; a binary header could also begin with "solid NAME".
bool IsAsciiSTL(const char* buffer, unsigned int fileSize) {
static bool IsAsciiSTL(const char* buffer, unsigned int fileSize) {
if (IsBinarySTL(buffer, fileSize))
return false;

View File

@@ -166,7 +166,7 @@ struct SceneHelper
id[0] = 0;
}
SceneHelper (aiScene* _scene)
explicit SceneHelper (aiScene* _scene)
: scene (_scene)
, idlen (0)
{

View File

@@ -16,7 +16,7 @@ public:
/** @brief Construction from an existing std::ostream
* @param _ostream Output stream to be used
*/
StdOStreamLogStream(std::ostream& _ostream);
explicit StdOStreamLogStream(std::ostream& _ostream);
/** @brief Destructor */
~StdOStreamLogStream();

View File

@@ -97,7 +97,7 @@ public:
// being bound to const ref& function parameters. Copying streams is not permitted, though.
// This workaround avoids this by manually specifying a copy ctor.
#if !defined(__GNUC__) || !defined(__APPLE__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
basic_formatter(const basic_formatter& other) {
explicit basic_formatter(const basic_formatter& other) {
underlying << (string)other;
}
#endif

View File

@@ -87,7 +87,7 @@ struct TempMat {
, numFaces (0)
{}
TempMat(const Triangle& in)
explicit TempMat(const Triangle& in)
: type ((Unreal::MeshFlags)in.mType)
, tex (in.mTextureNum)
, numFaces (0)

View File

@@ -6,7 +6,7 @@
#include "ScenePrivate.h"
static const unsigned int MajorVersion = 3;
static const unsigned int MinorVersion = 1;
static const unsigned int MinorVersion = 2;
// --------------------------------------------------------------------------------
// Legal information string - dont't remove this.

View File

@@ -129,7 +129,7 @@ struct Mesh
std::vector<Bone> mBones;
Mesh(const std::string &pName = "") { mName = pName; mNumTextures = 0; mNumColorSets = 0; }
explicit Mesh(const std::string &pName = "") { mName = pName; mNumTextures = 0; mNumColorSets = 0; }
};
/** Helper structure to represent a XFile frame */
@@ -142,7 +142,7 @@ struct Node
std::vector<Mesh*> mMeshes;
Node() { mParent = NULL; }
Node( Node* pParent) { mParent = pParent; }
explicit Node( Node* pParent) { mParent = pParent; }
~Node()
{
for( unsigned int a = 0; a < mChildren.size(); a++)

View File

@@ -68,7 +68,7 @@ public:
/** Constructor. Creates a data structure out of the XFile given in the memory block.
* @param pBuffer Null-terminated memory buffer containing the XFile
*/
XFileParser( const std::vector<char>& pBuffer);
explicit XFileParser( const std::vector<char>& pBuffer);
/** Destructor. Destroys all imported data along with it */
~XFileParser();

945
code/glTFAsset.h Normal file
View File

@@ -0,0 +1,945 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2015, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file glTFAsset.h
* Declares a glTF class to handle gltf/glb files
*
* glTF Extensions Support:
* KHR_binary_glTF: full
* KHR_materials_common: full
*/
#ifndef glTFAsset_H_INC
#define glTFAsset_H_INC
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#define RAPIDJSON_HAS_STDSTRING 1
#include <rapidjson/rapidjson.h>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#ifdef ASSIMP_API
# include "boost/shared_ptr.hpp"
# include "DefaultIOSystem.h"
# include "ByteSwapper.h"
#else
# include <memory>
# define AI_SWAP4(p)
# define ai_assert
#endif
#if _MSC_VER > 1500 || (defined __GNUC___)
# define ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
# else
# define gltf_unordered_map map
#endif
#ifdef ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
# include <unordered_map>
# if _MSC_VER > 1600
# define gltf_unordered_map unordered_map
# else
# define gltf_unordered_map tr1::unordered_map
# endif
#endif
namespace glTF
{
#ifdef ASSIMP_API
using Assimp::IOStream;
using Assimp::IOSystem;
using boost::shared_ptr;
#else
using std::shared_ptr;
typedef std::runtime_error DeadlyImportError;
typedef std::runtime_error DeadlyExportError;
enum aiOrigin { aiOrigin_SET = 0, aiOrigin_CUR = 1, aiOrigin_END = 2 };
class IOSystem;
class IOStream
{
FILE* f;
public:
IOStream(FILE* file) : f(file) {}
~IOStream() { fclose(f); f = 0; }
size_t Read(void* b, size_t sz, size_t n) { return fread(b, sz, n, f); }
size_t Write(const void* b, size_t sz, size_t n) { return fwrite(b, sz, n, f); }
int Seek(size_t off, aiOrigin orig) { return fseek(f, off, int(orig)); }
size_t Tell() const { return ftell(f); }
size_t FileSize() {
long p = Tell(), len = (Seek(0, aiOrigin_END), Tell());
return size_t((Seek(p, aiOrigin_SET), len));
}
};
#endif
using rapidjson::Value;
using rapidjson::Document;
class Asset;
class AssetWriter;
struct BufferView; // here due to cross-reference
struct Texture;
struct Light;
// Vec/matrix types, as raw float arrays
typedef float (vec3)[3];
typedef float (vec4)[4];
typedef float (mat4)[16];
namespace Util
{
void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out);
size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out);
inline size_t DecodeBase64(const char* in, uint8_t*& out)
{
return DecodeBase64(in, strlen(in), out);
}
struct DataURI
{
const char* mediaType;
const char* charset;
bool base64;
const char* data;
size_t dataLength;
};
//! Check if a uri is a data URI
inline bool ParseDataURI(const char* uri, size_t uriLen, DataURI& out);
}
//! Magic number for GLB files
#define AI_GLB_MAGIC_NUMBER "glTF"
#ifdef ASSIMP_API
#include "./../include/assimp/Compiler/pushpack1.h"
#endif
//! For the KHR_binary_glTF extension (binary .glb file)
//! 20-byte header (+ the JSON + a "body" data section)
struct GLB_Header
{
uint8_t magic[4]; //!< Magic number: "glTF"
uint32_t version; //!< Version number (always 1 as of the last update)
uint32_t length; //!< Total length of the Binary glTF, including header, scene, and body, in bytes
uint32_t sceneLength; //!< Length, in bytes, of the glTF scene
uint32_t sceneFormat; //!< Specifies the format of the glTF scene (see the SceneFormat enum)
} PACK_STRUCT;
#ifdef ASSIMP_API
#include "./../include/assimp/Compiler/poppack1.h"
#endif
//! Values for the GLB_Header::sceneFormat field
enum SceneFormat
{
SceneFormat_JSON = 0
};
//! Values for the mesh primitive modes
enum PrimitiveMode
{
PrimitiveMode_POINTS = 0,
PrimitiveMode_LINES = 1,
PrimitiveMode_LINE_LOOP = 2,
PrimitiveMode_LINE_STRIP = 3,
PrimitiveMode_TRIANGLES = 4,
PrimitiveMode_TRIANGLE_STRIP = 5,
PrimitiveMode_TRIANGLE_FAN = 6
};
//! Values for the Accessor::componentType field
enum ComponentType
{
ComponentType_BYTE = 5120,
ComponentType_UNSIGNED_BYTE = 5121,
ComponentType_SHORT = 5122,
ComponentType_UNSIGNED_SHORT = 5123,
ComponentType_FLOAT = 5126
};
inline size_t ComponentTypeSize(ComponentType t)
{
switch (t) {
case ComponentType_SHORT:
case ComponentType_UNSIGNED_SHORT:
return 2;
case ComponentType_FLOAT:
return 4;
//case Accessor::ComponentType_BYTE:
//case Accessor::ComponentType_UNSIGNED_BYTE:
default:
return 1;
}
}
//! Values for the BufferView::target field
enum BufferViewTarget
{
BufferViewTarget_ARRAY_BUFFER = 34962,
BufferViewTarget_ELEMENT_ARRAY_BUFFER = 34963
};
//! Values for the Texture::format and Texture::internalFormat fields
enum TextureFormat
{
TextureFormat_ALPHA = 6406,
TextureFormat_RGB = 6407,
TextureFormat_RGBA = 6408,
TextureFormat_LUMINANCE = 6409,
TextureFormat_LUMINANCE_ALPHA = 6410
};
//! Values for the Texture::target field
enum TextureTarget
{
TextureTarget_TEXTURE_2D = 3553
};
//! Values for the Texture::type field
enum TextureType
{
TextureType_UNSIGNED_BYTE = 5121,
TextureType_UNSIGNED_SHORT_5_6_5 = 33635,
TextureType_UNSIGNED_SHORT_4_4_4_4 = 32819,
TextureType_UNSIGNED_SHORT_5_5_5_1 = 32820
};
//! Values for the Accessor::type field (helper class)
class AttribType
{
public:
enum Value
{ SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4 };
private:
static const size_t NUM_VALUES = static_cast<size_t>(MAT4)+1;
struct Info
{ const char* name; unsigned int numComponents; };
template<int N> struct data
{ static const Info infos[NUM_VALUES]; };
public:
inline static Value FromString(const char* str)
{
for (size_t i = 0; i < NUM_VALUES; ++i) {
if (strcmp(data<0>::infos[i].name, str) == 0) {
return static_cast<Value>(i);
}
}
return SCALAR;
}
inline static const char* ToString(Value type)
{
return data<0>::infos[static_cast<size_t>(type)].name;
}
inline static unsigned int GetNumComponents(Value type)
{
return data<0>::infos[static_cast<size_t>(type)].numComponents;
}
};
// must match the order of the AttribTypeTraits::Value enum!
template<int N> const AttribType::Info
AttribType::data<N>::infos[AttribType::NUM_VALUES] = {
{ "SCALAR", 1 }, { "VEC2", 2 }, { "VEC3", 3 }, { "VEC4", 4 }, { "MAT2", 4 }, { "MAT3", 9 }, { "MAT4", 16 }
};
//! A reference to one top-level object, which is valid
//! until the Asset instance is destroyed
template<class T>
class Ref
{
std::vector<T*>* vector;
int index;
public:
Ref() : vector(0), index(0) {}
Ref(std::vector<T*>& vec, int idx) : vector(&vec), index(idx) {}
inline size_t GetIndex() const
{ return index; }
operator bool() const
{ return vector != 0; }
T* operator->()
{ return (*vector)[index]; }
T& operator*()
{ return *((*vector)[index]); }
};
//! Helper struct to represent values that might not be present
template<class T>
struct Nullable
{
T value;
bool isPresent;
Nullable() : isPresent(false) {}
Nullable(T& val) : value(val), isPresent(true) {}
};
//! Base classe for all glTF top-level objects
struct Object
{
std::string id; //!< The globally unique ID used to reference this object
std::string name; //!< The user-defined name of this object
//! Objects marked as special are not exported (used to emulate the binary body buffer)
virtual bool IsSpecial() const
{ return false; }
virtual ~Object() {}
};
//
// Classes for each glTF top-level object type
//
//! A typed view into a BufferView. A BufferView contains raw binary data.
//! An accessor provides a typed view into a BufferView or a subset of a BufferView
// !similar to how WebGL's vertexAttribPointer() defines an attribute in a buffer.
struct Accessor : public Object
{
Ref<BufferView> bufferView; //!< The ID of the bufferView. (required)
unsigned int byteOffset; //!< The offset relative to the start of the bufferView in bytes. (required)
unsigned int byteStride; //!< The stride, in bytes, between attributes referenced by this accessor. (default: 0)
ComponentType componentType; //!< The datatype of components in the attribute. (required)
unsigned int count; //!< The number of attributes referenced by this accessor. (required)
AttribType::Value type; //!< Specifies if the attribute is a scalar, vector, or matrix. (required)
//std::vector<float> max; //!< Maximum value of each component in this attribute.
//std::vector<float> min; //!< Minimum value of each component in this attribute.
unsigned int GetNumComponents();
unsigned int GetBytesPerComponent();
unsigned int GetElementSize();
inline uint8_t* GetPointer();
template<class T>
void ExtractData(T*& outData);
void WriteData(size_t count, const void* src_buffer, size_t src_stride);
//! Helper class to iterate the data
class Indexer
{
friend struct Accessor;
Accessor& accessor;
uint8_t* data;
size_t elemSize, stride;
Indexer(Accessor& acc);
public:
//! Accesses the i-th value as defined by the accessor
template<class T>
T GetValue(int i);
//! Accesses the i-th value as defined by the accessor
inline unsigned int GetUInt(int i)
{
return GetValue<unsigned int>(i);
}
};
inline Indexer GetIndexer()
{
return Indexer(*this);
}
Accessor() {}
void Read(Value& obj, Asset& r);
};
struct Animation : public Object
{
struct Channel
{
};
struct Target
{
};
struct Sampler
{
};
};
//! A buffer points to binary geometry, animation, or skins.
struct Buffer : public Object
{
public:
enum Type
{
Type_arraybuffer,
Type_text
};
//std::string uri; //!< The uri of the buffer. Can be a filepath, a data uri, etc. (required)
size_t byteLength; //!< The length of the buffer in bytes. (default: 0)
//std::string type; //!< XMLHttpRequest responseType (default: "arraybuffer")
Type type;
private:
shared_ptr<uint8_t> mData; //!< Pointer to the data
bool mIsSpecial; //!< Set to true for special cases (e.g. the body buffer)
public:
Buffer();
void Read(Value& obj, Asset& r);
void LoadFromStream(IOStream& stream, size_t length = 0, size_t baseOffset = 0);
size_t AppendData(uint8_t* data, size_t length);
void Grow(size_t amount);
uint8_t* GetPointer()
{ return mData.get(); }
void MarkAsSpecial()
{ mIsSpecial = true; }
bool IsSpecial() const
{ return mIsSpecial; }
};
//! A view into a buffer generally representing a subset of the buffer.
struct BufferView : public Object
{
Ref<Buffer> buffer; //! The ID of the buffer. (required)
size_t byteOffset; //! The offset into the buffer in bytes. (required)
size_t byteLength; //! The length of the bufferView in bytes. (default: 0)
BufferViewTarget target; //! The target that the WebGL buffer should be bound to.
BufferView() {}
void Read(Value& obj, Asset& r);
};
struct Camera : public Object
{
enum Type
{
Perspective,
Orthographic
};
Type type;
union
{
struct {
float aspectRatio; //!<The floating - point aspect ratio of the field of view. (0 = undefined = use the canvas one)
float yfov; //!<The floating - point vertical field of view in radians. (required)
float zfar; //!<The floating - point distance to the far clipping plane. (required)
float znear; //!< The floating - point distance to the near clipping plane. (required)
} perspective;
struct {
float xmag; //! The floating-point horizontal magnification of the view. (required)
float ymag; //! The floating-point vertical magnification of the view. (required)
float zfar; //! The floating-point distance to the far clipping plane. (required)
float znear; //! The floating-point distance to the near clipping plane. (required)
} ortographic;
};
Camera() {}
void Read(Value& obj, Asset& r);
};
//! Image data used to create a texture.
struct Image : public Object
{
std::string uri; //! The uri of the image, that can be a file path, a data URI, etc.. (required)
Ref<BufferView> bufferView;
std::string mimeType;
int width, height;
private:
uint8_t* mData;
size_t mDataLength;
public:
Image();
void Read(Value& obj, Asset& r);
inline bool HasData() const
{ return mDataLength > 0; }
inline size_t GetDataLength() const
{ return mDataLength; }
inline const uint8_t* GetData() const
{ return mData; }
inline uint8_t* StealData();
inline void SetData(uint8_t* data, size_t length, Asset& r);
};
//! Holds a material property that can be a texture or a color
struct TexProperty
{
Ref<Texture> texture;
vec4 color;
};
//! The material appearance of a primitive.
struct Material : public Object
{
//Ref<Sampler> source; //!< The ID of the technique.
//std::gltf_unordered_map<std::string, std::string> values; //!< A dictionary object of parameter values.
//! Techniques defined by KHR_materials_common
enum Technique
{
Technique_undefined = 0,
Technique_BLINN,
Technique_PHONG,
Technique_LAMBERT,
Technique_CONSTANT
};
TexProperty ambient;
TexProperty diffuse;
TexProperty specular;
TexProperty emission;
bool doubleSided;
bool transparent;
float transparency;
float shininess;
Technique technique;
Material() { SetDefaults(); }
void Read(Value& obj, Asset& r);
void SetDefaults();
};
//! A set of primitives to be rendered. A node can contain one or more meshes. A node's transform places the mesh in the scene.
struct Mesh : public Object
{
typedef std::vector< Ref<Accessor> > AccessorList;
struct Primitive
{
PrimitiveMode mode;
struct Attributes {
AccessorList position, normal, texcoord, color, joint, jointmatrix, weight;
} attributes;
Ref<Accessor> indices;
Ref<Material> material;
};
std::vector<Primitive> primitives;
Mesh() {}
void Read(Value& obj, Asset& r);
};
struct Node : public Object
{
std::vector< Ref<Node> > children;
std::vector< Ref<Mesh> > meshes;
Nullable<mat4> matrix;
Nullable<vec3> translation;
Nullable<vec4> rotation;
Nullable<vec3> scale;
Ref<Camera> camera;
Ref<Light> light;
Node() {}
void Read(Value& obj, Asset& r);
};
struct Program : public Object
{
Program() {}
void Read(Value& obj, Asset& r);
};
struct Sampler : public Object
{
Sampler() {}
void Read(Value& obj, Asset& r);
};
struct Scene : public Object
{
std::vector< Ref<Node> > nodes;
Scene() {}
void Read(Value& obj, Asset& r);
};
struct Shader : public Object
{
Shader() {}
void Read(Value& obj, Asset& r);
};
struct Skin : public Object
{
Skin() {}
void Read(Value& obj, Asset& r);
};
struct Technique : public Object
{
struct Parameters
{
};
struct States
{
};
struct Functions
{
};
Technique() {}
void Read(Value& obj, Asset& r);
};
//! A texture and its sampler.
struct Texture : public Object
{
//Ref<Sampler> source; //!< The ID of the sampler used by this texture. (required)
Ref<Image> source; //!< The ID of the image used by this texture. (required)
//TextureFormat format; //!< The texture's format. (default: TextureFormat_RGBA)
//TextureFormat internalFormat; //!< The texture's internal format. (default: TextureFormat_RGBA)
//TextureTarget target; //!< The target that the WebGL texture should be bound to. (default: TextureTarget_TEXTURE_2D)
//TextureType type; //!< Texel datatype. (default: TextureType_UNSIGNED_BYTE)
Texture() {}
void Read(Value& obj, Asset& r);
};
//! A light (from KHR_materials_common extension)
struct Light : public Object
{
enum Type
{
Type_undefined,
Type_ambient,
Type_directional,
Type_point,
Type_spot
};
Type type;
vec4 color;
float distance;
float constantAttenuation;
float linearAttenuation;
float quadraticAttenuation;
float falloffAngle;
float falloffExponent;
Light() {}
void Read(Value& obj, Asset& r);
void SetDefaults();
};
//! Base class for LazyDict that acts as an interface
class LazyDictBase
{
public:
virtual ~LazyDictBase() {}
virtual void AttachToDocument(Document& doc) = 0;
virtual void DetachFromDocument() = 0;
virtual void WriteObjects(AssetWriter& writer) = 0;
};
//! (Stub class that is specialized in glTFAssetWriter.h)
template<class T>
struct LazyDictWriter
{
static void Write(T& d, AssetWriter& w) {}
};
//! Manages lazy loading of the glTF top-level objects, and keeps a reference to them by ID
//! It is the owner the loaded objects, so when it is destroyed it also deletes them
template<class T>
class LazyDict : public LazyDictBase
{
friend class Asset;
friend class AssetWriter;
typedef typename std::gltf_unordered_map< std::string, size_t > Dict;
std::vector<T*> mObjs; //! The read objects
Dict mObjsById; //! The read objects accesible by id
const char* mDictId; //! ID of the dictionary object
const char* mExtId; //! ID of the extension defining the dictionary
Value* mDict; //! JSON dictionary object
Asset& mAsset; //! The asset instance
void AttachToDocument(Document& doc);
void DetachFromDocument();
void WriteObjects(AssetWriter& writer)
{ LazyDictWriter< LazyDict >::Write(*this, writer); }
Ref<T> Add(T* obj);
public:
LazyDict(Asset& asset, const char* dictId, const char* extId = 0);
~LazyDict();
Ref<T> Get(const char* id);
Ref<T> Get(size_t i);
Ref<T> Create(const char* id);
Ref<T> Create(const std::string& id)
{ return Create(id.c_str()); }
inline size_t Size() const
{ return mObjs.size(); }
inline T& operator[](size_t i)
{ return *mObjs[i]; }
};
struct AssetMetadata
{
std::string copyright; //!< A copyright message suitable for display to credit the content creator.
std::string generator; //!< Tool that generated this glTF model.Useful for debugging.
bool premultipliedAlpha; //!< Specifies if the shaders were generated with premultiplied alpha. (default: false)
struct {
std::string api; //!< Specifies the target rendering API (default: "WebGL")
std::string version; //!< Specifies the target rendering API (default: "1.0.3")
} profile; //!< Specifies the target rendering API and version, e.g., WebGL 1.0.3. (default: {})
int version; //!< The glTF format version (should be 1)
void Read(Document& doc);
};
//
// glTF Asset class
//
//! Root object for a glTF asset
class Asset
{
typedef std::gltf_unordered_map<std::string, int> IdMap;
template<class T>
friend class LazyDict;
friend struct Buffer; // To access OpenFile
friend class AssetWriter;
private:
IOSystem* mIOSystem;
std::string mCurrentAssetDir;
size_t mSceneLength;
size_t mBodyOffset, mBodyLength;
std::vector<LazyDictBase*> mDicts;
IdMap mUsedIds;
Ref<Buffer> mBodyBuffer;
Asset(Asset&);
Asset& operator=(const Asset&);
public:
//! Keeps info about the enabled extensions
struct Extensions
{
bool KHR_binary_glTF;
bool KHR_materials_common;
} extensionsUsed;
AssetMetadata asset;
// Dictionaries for each type of object
LazyDict<Accessor> accessors;
LazyDict<Animation> animations;
LazyDict<Buffer> buffers;
LazyDict<BufferView> bufferViews;
LazyDict<Camera> cameras;
LazyDict<Image> images;
LazyDict<Material> materials;
LazyDict<Mesh> meshes;
LazyDict<Node> nodes;
//LazyDict<Program> programs;
//LazyDict<Sampler> samplers;
LazyDict<Scene> scenes;
//LazyDict<Shader> shaders;
//LazyDict<Skin> skins;
//LazyDict<Technique> techniques;
LazyDict<Texture> textures;
LazyDict<Light> lights; // KHR_materials_common ext
Ref<Scene> scene;
public:
Asset(IOSystem* io = 0)
: mIOSystem(io)
, accessors (*this, "accessors")
, animations (*this, "animations")
, buffers (*this, "buffers")
, bufferViews (*this, "bufferViews")
, cameras (*this, "cameras")
, images (*this, "images")
, materials (*this, "materials")
, meshes (*this, "meshes")
, nodes (*this, "nodes")
//, programs (*this, "programs")
//, samplers (*this, "samplers")
, scenes (*this, "scenes")
//, shaders (*this, "shaders")
//, skins (*this, "skins")
//, techniques (*this, "techniques")
, textures (*this, "textures")
, lights (*this, "lights", "KHR_materials_common")
{
memset(&extensionsUsed, 0, sizeof(extensionsUsed));
memset(&asset, 0, sizeof(asset));
}
//! Main function
void Load(const std::string& file, bool isBinary = false);
//! Enables the "KHR_binary_glTF" extension on the asset
void SetAsBinary();
//! Search for an available name, starting from the given strings
std::string FindUniqueID(const std::string& str, const char* suffix);
Ref<Buffer> GetBodyBuffer()
{ return mBodyBuffer; }
private:
void ReadBinaryHeader(IOStream& stream);
void ReadExtensionsUsed(Document& doc);
IOStream* OpenFile(std::string path, const char* mode, bool absolute = false);
};
}
// Include the implementation of the methods
#include "glTFAsset.inl"
#endif

1215
code/glTFAsset.inl Normal file

File diff suppressed because it is too large Load Diff

89
code/glTFAssetWriter.h Normal file
View File

@@ -0,0 +1,89 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2015, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file glTFWriter.h
* Declares a class to write gltf/glb files
*
* glTF Extensions Support:
* KHR_binary_glTF: full
* KHR_materials_common: full
*/
#ifndef glTFAssetWriter_H_INC
#define glTFAssetWriter_H_INC
#include "glTFAsset.h"
namespace glTF
{
using rapidjson::MemoryPoolAllocator;
class AssetWriter
{
template<class T>
friend struct LazyDictWriter;
private:
void WriteBinaryData(IOStream* outfile, size_t sceneLength);
void WriteMetadata();
void WriteExtensionsUsed();
template<class T>
void WriteObjects(LazyDict<T>& d);
public:
Document mDoc;
Asset& mAsset;
MemoryPoolAllocator<>& mAl;
AssetWriter(Asset& asset);
void WriteFile(const char* path);
};
}
// Include the implementation of the methods
#include "glTFAssetWriter.inl"
#endif

497
code/glTFAssetWriter.inl Normal file
View File

@@ -0,0 +1,497 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2015, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <rapidjson/prettywriter.h>
namespace glTF {
using rapidjson::StringBuffer;
using rapidjson::PrettyWriter;
using rapidjson::Writer;
using rapidjson::StringRef;
using rapidjson::StringRef;
namespace {
template<size_t N>
inline Value& MakeValue(Value& val, float(&r)[N], MemoryPoolAllocator<>& al) {
val.SetArray();
val.Reserve(N, al);
for (int i = 0; i < N; ++i) {
val.PushBack(r[i], al);
}
return val;
};
template<class T>
inline void AddRefsVector(Value& obj, const char* fieldId, std::vector< Ref<T> >& v, MemoryPoolAllocator<>& al) {
if (v.empty()) return;
Value lst;
lst.SetArray();
lst.Reserve(v.size(), al);
for (size_t i = 0; i < v.size(); ++i) {
lst.PushBack(StringRef(v[i]->id), al);
}
obj.AddMember(StringRef(fieldId), lst, al);
};
}
inline void Write(Value& obj, Accessor& a, AssetWriter& w)
{
obj.AddMember("bufferView", Value(a.bufferView->id, w.mAl).Move(), w.mAl);
obj.AddMember("byteOffset", a.byteOffset, w.mAl);
obj.AddMember("byteStride", a.byteStride, w.mAl);
obj.AddMember("componentType", int(a.componentType), w.mAl);
obj.AddMember("count", a.count, w.mAl);
obj.AddMember("type", StringRef(AttribType::ToString(a.type)), w.mAl);
}
inline void Write(Value& obj, Animation& a, AssetWriter& w)
{
}
inline void Write(Value& obj, Buffer& b, AssetWriter& w)
{
std::string dataURI = "data:application/octet-stream;base64,";
Util::EncodeBase64(b.GetPointer(), b.byteLength, dataURI);
const char* type;
switch (b.type) {
case Buffer::Type_text:
type = "text"; break;
default:
type = "arraybuffer";
}
obj.AddMember("byteLength", b.byteLength, w.mAl);
obj.AddMember("type", StringRef(type), w.mAl);
obj.AddMember("uri", Value(dataURI, w.mAl).Move(), w.mAl);
}
inline void Write(Value& obj, BufferView& bv, AssetWriter& w)
{
obj.AddMember("buffer", Value(bv.buffer->id, w.mAl).Move(), w.mAl);
obj.AddMember("byteOffset", bv.byteOffset, w.mAl);
obj.AddMember("byteLength", bv.byteLength, w.mAl);
obj.AddMember("target", int(bv.target), w.mAl);
}
inline void Write(Value& obj, Camera& c, AssetWriter& w)
{
}
inline void Write(Value& obj, Image& img, AssetWriter& w)
{
std::string uri;
if (w.mAsset.extensionsUsed.KHR_binary_glTF && img.bufferView) {
Value exts, ext;
exts.SetObject();
ext.SetObject();
ext.AddMember("bufferView", StringRef(img.bufferView->id), w.mAl);
if (!img.mimeType.empty())
ext.AddMember("mimeType", StringRef(img.mimeType), w.mAl);
exts.AddMember("KHR_binary_glTF", ext, w.mAl);
obj.AddMember("extensions", exts, w.mAl);
return;
}
else if (img.HasData()) {
uri = "data:" + (img.mimeType.empty() ? "application/octet-stream" : img.mimeType);
uri += ";base64,";
Util::EncodeBase64(img.GetData(), img.GetDataLength(), uri);
}
else {
uri = img.uri;
}
obj.AddMember("uri", Value(uri, w.mAl).Move(), w.mAl);
}
namespace {
inline void WriteColorOrTex(Value& obj, TexProperty& prop, const char* propName, MemoryPoolAllocator<>& al)
{
if (prop.texture)
obj.AddMember(StringRef(propName), Value(prop.texture->id, al).Move(), al);
else {
Value col;
obj.AddMember(StringRef(propName), MakeValue(col, prop.color, al), al);
}
}
}
inline void Write(Value& obj, Material& m, AssetWriter& w)
{
Value v;
v.SetObject();
{
WriteColorOrTex(v, m.ambient, "ambient", w.mAl);
WriteColorOrTex(v, m.diffuse, "diffuse", w.mAl);
WriteColorOrTex(v, m.specular, "specular", w.mAl);
WriteColorOrTex(v, m.emission, "emission", w.mAl);
v.AddMember("shininess", m.shininess, w.mAl);
}
obj.AddMember("values", v, w.mAl);
}
namespace {
inline void WriteAttrs(AssetWriter& w, Value& attrs, Mesh::AccessorList& lst,
const char* semantic, bool forceNumber = false)
{
if (lst.empty()) return;
if (lst.size() == 1 && !forceNumber) {
attrs.AddMember(StringRef(semantic), Value(lst[0]->id, w.mAl).Move(), w.mAl);
}
else {
for (size_t i = 0; i < lst.size(); ++i) {
char buffer[32];
sprintf(buffer, "%s_%d", semantic, int(i));
attrs.AddMember(Value(buffer, w.mAl).Move(), Value(lst[i]->id, w.mAl).Move(), w.mAl);
}
}
}
}
inline void Write(Value& obj, Mesh& m, AssetWriter& w)
{
Value primitives;
primitives.SetArray();
primitives.Reserve(m.primitives.size(), w.mAl);
for (size_t i = 0; i < m.primitives.size(); ++i) {
Mesh::Primitive& p = m.primitives[i];
Value prim;
prim.SetObject();
{
prim.AddMember("mode", Value(int(p.mode)).Move(), w.mAl);
if (p.material)
prim.AddMember("material", p.material->id, w.mAl);
if (p.indices)
prim.AddMember("indices", Value(p.indices->id, w.mAl).Move(), w.mAl);
Value attrs;
attrs.SetObject();
{
WriteAttrs(w, attrs, p.attributes.position, "POSITION");
WriteAttrs(w, attrs, p.attributes.normal, "NORMAL");
WriteAttrs(w, attrs, p.attributes.texcoord, "TEXCOORD", true);
WriteAttrs(w, attrs, p.attributes.color, "COLOR");
WriteAttrs(w, attrs, p.attributes.joint, "JOINT");
WriteAttrs(w, attrs, p.attributes.jointmatrix, "JOINTMATRIX");
WriteAttrs(w, attrs, p.attributes.weight, "WEIGHT");
}
prim.AddMember("attributes", attrs, w.mAl);
}
primitives.PushBack(prim, w.mAl);
}
obj.AddMember("primitives", primitives, w.mAl);
}
inline void Write(Value& obj, Node& n, AssetWriter& w)
{
if (n.matrix.isPresent) {
Value val;
obj.AddMember("matrix", MakeValue(val, n.matrix.value, w.mAl).Move(), w.mAl);
}
if (n.translation.isPresent) {
Value val;
obj.AddMember("translation", MakeValue(val, n.translation.value, w.mAl).Move(), w.mAl);
}
if (n.scale.isPresent) {
Value val;
obj.AddMember("scale", MakeValue(val, n.scale.value, w.mAl).Move(), w.mAl);
}
if (n.rotation.isPresent) {
Value val;
obj.AddMember("rotation", MakeValue(val, n.rotation.value, w.mAl).Move(), w.mAl);
}
AddRefsVector(obj, "children", n.children, w.mAl);
AddRefsVector(obj, "meshes", n.meshes, w.mAl);
}
inline void Write(Value& obj, Program& b, AssetWriter& w)
{
}
inline void Write(Value& obj, Sampler& b, AssetWriter& w)
{
}
inline void Write(Value& scene, Scene& s, AssetWriter& w)
{
AddRefsVector(scene, "nodes", s.nodes, w.mAl);
}
inline void Write(Value& obj, Shader& b, AssetWriter& w)
{
}
inline void Write(Value& obj, Skin& b, AssetWriter& w)
{
}
inline void Write(Value& obj, Technique& b, AssetWriter& w)
{
}
inline void Write(Value& obj, Texture& tex, AssetWriter& w)
{
if (tex.source) {
obj.AddMember("source", Value(tex.source->id, w.mAl).Move(), w.mAl);
}
}
inline void Write(Value& obj, Light& b, AssetWriter& w)
{
}
AssetWriter::AssetWriter(Asset& a)
: mDoc()
, mAsset(a)
, mAl(mDoc.GetAllocator())
{
mDoc.SetObject();
WriteMetadata();
WriteExtensionsUsed();
// Dump the contents of the dictionaries
for (size_t i = 0; i < a.mDicts.size(); ++i) {
a.mDicts[i]->WriteObjects(*this);
}
// Add the target scene field
if (mAsset.scene) {
mDoc.AddMember("scene", StringRef(mAsset.scene->id), mAl);
}
}
void AssetWriter::WriteFile(const char* path)
{
bool isBinary = mAsset.extensionsUsed.KHR_binary_glTF;
boost::scoped_ptr<IOStream> outfile
(mAsset.OpenFile(path, isBinary ? "wb" : "wt", true));
if (outfile == 0) {
throw DeadlyExportError("Could not open output file: " + std::string(path));
}
if (isBinary) {
// we will write the header later, skip its size
outfile->Seek(sizeof(GLB_Header), aiOrigin_SET);
}
StringBuffer docBuffer;
bool pretty = true;
if (!isBinary && pretty) {
PrettyWriter<StringBuffer> writer(docBuffer);
mDoc.Accept(writer);
}
else {
Writer<StringBuffer> writer(docBuffer);
mDoc.Accept(writer);
}
if (outfile->Write(docBuffer.GetString(), docBuffer.GetSize(), 1) != 1) {
throw DeadlyExportError("Failed to write scene data!");
}
if (isBinary) {
WriteBinaryData(outfile.get(), docBuffer.GetSize());
}
}
void AssetWriter::WriteBinaryData(IOStream* outfile, size_t sceneLength)
{
//
// write the body data
//
size_t bodyLength = 0;
if (Ref<Buffer> b = mAsset.GetBodyBuffer()) {
bodyLength = b->byteLength;
if (bodyLength > 0) {
size_t bodyOffset = sizeof(GLB_Header) + sceneLength;
bodyOffset = (bodyOffset + 3) & ~3; // Round up to next multiple of 4
outfile->Seek(bodyOffset, aiOrigin_SET);
if (outfile->Write(b->GetPointer(), b->byteLength, 1) != 1) {
throw DeadlyExportError("Failed to write body data!");
}
}
}
//
// write the header
//
GLB_Header header;
memcpy(header.magic, AI_GLB_MAGIC_NUMBER, sizeof(header.magic));
header.version = 1;
AI_SWAP4(header.version);
header.length = sizeof(header) + sceneLength + bodyLength;
AI_SWAP4(header.length);
header.sceneLength = sceneLength;
AI_SWAP4(header.sceneLength);
header.sceneFormat = SceneFormat_JSON;
AI_SWAP4(header.sceneFormat);
outfile->Seek(0, aiOrigin_SET);
if (outfile->Write(&header, 1, sizeof(header)) != sizeof(header)) {
throw DeadlyExportError("Failed to write the header!");
}
}
void AssetWriter::WriteMetadata()
{
Value asset;
asset.SetObject();
{
asset.AddMember("version", mAsset.asset.version, mAl);
asset.AddMember("generator", Value(mAsset.asset.generator, mAl).Move(), mAl);
}
mDoc.AddMember("asset", asset, mAl);
}
void AssetWriter::WriteExtensionsUsed()
{
Value exts;
exts.SetArray();
{
if (false)
exts.PushBack(StringRef("KHR_binary_glTF"), mAl);
if (false)
exts.PushBack(StringRef("KHR_materials_common"), mAl);
}
if (!exts.Empty())
mDoc.AddMember("extensionsUsed", exts, mAl);
}
template<class T>
void AssetWriter::WriteObjects(LazyDict<T>& d)
{
if (d.mObjs.empty()) return;
Value* container = &mDoc;
if (d.mExtId) {
Value* exts = FindObject(mDoc, "extensions");
if (!exts) {
mDoc.AddMember("extensions", Value().SetObject().Move(), mDoc.GetAllocator());
exts = FindObject(mDoc, "extensions");
}
if (!(container = FindObject(*exts, d.mExtId))) {
exts->AddMember(StringRef(d.mExtId), Value().SetObject().Move(), mDoc.GetAllocator());
container = FindObject(*exts, d.mExtId);
}
}
Value* dict;
if (!(dict = FindObject(*container, d.mDictId))) {
container->AddMember(StringRef(d.mDictId), Value().SetObject().Move(), mDoc.GetAllocator());
dict = FindObject(*container, d.mDictId);
}
for (size_t i = 0; i < d.mObjs.size(); ++i) {
if (d.mObjs[i]->IsSpecial()) continue;
Value obj;
obj.SetObject();
if (!d.mObjs[i]->name.empty()) {
obj.AddMember("name", StringRef(d.mObjs[i]->name.c_str()), mAl);
}
Write(obj, *d.mObjs[i], *this);
dict->AddMember(StringRef(d.mObjs[i]->id), obj, mAl);
}
}
template<class T>
struct LazyDictWriter< LazyDict<T> >
{
static void Write(LazyDict<T>& d, AssetWriter& w)
{
w.WriteObjects(d);
}
};
}

367
code/glTFExporter.cpp Normal file
View File

@@ -0,0 +1,367 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2015, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#ifndef ASSIMP_BUILD_NO_EXPORT
#ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER
#include "glTFExporter.h"
#include "Exceptional.h"
#include "StringComparison.h"
#include "ByteSwapper.h"
#include <assimp/version.h>
#include <assimp/IOSystem.hpp>
#include <assimp/Exporter.hpp>
#include <assimp/material.h>
#include <assimp/scene.h>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include "glTFAssetWriter.h"
using namespace rapidjson;
using namespace Assimp;
using namespace glTF;
namespace Assimp {
// ------------------------------------------------------------------------------------------------
// Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
void ExportSceneGLTF(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
{
// invoke the exporter
glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, false);
}
// ------------------------------------------------------------------------------------------------
// Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
void ExportSceneGLB(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
{
// invoke the exporter
glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, true);
}
} // end of namespace Assimp
glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
const ExportProperties* pProperties, bool isBinary)
: mFilename(filename)
, mIOSystem(pIOSystem)
, mScene(pScene)
, mProperties(pProperties)
{
boost::scoped_ptr<Asset> asset(new glTF::Asset(pIOSystem));
mAsset = asset.get();
if (isBinary) {
asset->SetAsBinary();
}
ExportMetadata();
//for (unsigned int i = 0; i < pScene->mNumAnimations; ++i) {}
//for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {}
//for (unsigned int i = 0; i < pScene->mNumLights; ++i) {}
ExportMaterials();
ExportMeshes();
//for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {}
if (mScene->mRootNode) {
ExportNode(mScene->mRootNode);
}
ExportScene();
glTF::AssetWriter writer(*mAsset);
writer.WriteFile(filename);
}
static void CopyValue(const aiMatrix4x4& v, glTF::mat4& o)
{
o[ 0] = v.a1; o[ 1] = v.b1; o[ 2] = v.c1; o[ 3] = v.d1;
o[ 4] = v.a2; o[ 5] = v.b2; o[ 6] = v.c2; o[ 7] = v.d2;
o[ 8] = v.a3; o[ 9] = v.b3; o[10] = v.c3; o[11] = v.d3;
o[12] = v.a4; o[13] = v.b4; o[14] = v.c4; o[15] = v.d4;
}
inline Ref<Accessor> ExportData(Asset& a, std::string& meshName, Ref<Buffer>& buffer,
unsigned int count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, bool isIndices = false)
{
if (!count || !data) return Ref<Accessor>();
unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
unsigned int bytesPerComp = ComponentTypeSize(compType);
size_t offset = buffer->byteLength;
size_t length = count * numCompsOut * bytesPerComp;
buffer->Grow(length);
// bufferView
Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
bv->buffer = buffer;
bv->byteOffset = 0;
bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
bv->target = isIndices ? BufferViewTarget_ELEMENT_ARRAY_BUFFER : BufferViewTarget_ARRAY_BUFFER;
// accessor
Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
acc->bufferView = bv;
acc->byteOffset = offset;
acc->byteStride = 0;
acc->componentType = compType;
acc->count = count;
acc->type = typeOut;
// copy the data
acc->WriteData(count, data, numCompsIn*bytesPerComp);
return acc;
}
namespace {
void GetMatScalar(const aiMaterial* mat, float& val, const char* propName, int type, int idx) {
if (mat->Get(propName, type, idx, val) == AI_SUCCESS) {}
}
}
void glTFExporter::GetMatColorOrTex(const aiMaterial* mat, glTF::TexProperty& prop, const char* propName, int type, int idx, aiTextureType tt)
{
aiString tex;
aiColor4D col;
if (mat->GetTextureCount(tt) > 0) {
if (mat->Get(AI_MATKEY_TEXTURE(tt, 0), tex) == AI_SUCCESS) {
std::string path = tex.C_Str();
if (path.size() > 0) {
if (path[0] != '*') {
std::map<std::string, size_t>::iterator it = mTexturesByPath.find(path);
if (it != mTexturesByPath.end()) {
prop.texture = mAsset->textures.Get(it->second);
}
}
if (!prop.texture) {
std::string texId = mAsset->FindUniqueID("", "texture");
prop.texture = mAsset->textures.Create(texId);
mTexturesByPath[path] = prop.texture.GetIndex();
std::string imgId = mAsset->FindUniqueID("", "image");
prop.texture->source = mAsset->images.Create(imgId);
if (path[0] == '*') { // embedded
aiTexture* tex = mScene->mTextures[atoi(&path[1])];
uint8_t* data = reinterpret_cast<uint8_t*>(tex->pcData);
prop.texture->source->SetData(data, tex->mWidth, *mAsset);
if (tex->achFormatHint[0]) {
std::string mimeType = "image/";
mimeType += (memcmp(tex->achFormatHint, "jpg", 3) == 0) ? "jpeg" : tex->achFormatHint;
prop.texture->source->mimeType = mimeType;
}
}
else {
prop.texture->source->uri = path;
}
}
}
}
}
if (mat->Get(propName, type, idx, col) == AI_SUCCESS) {
prop.color[0] = col.r; prop.color[1] = col.g; prop.color[2] = col.b; prop.color[3] = col.a;
}
}
void glTFExporter::ExportMaterials()
{
aiString aiName;
for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
const aiMaterial* mat = mScene->mMaterials[i];
std::string name;
if (mat->Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
name = aiName.C_Str();
}
name = mAsset->FindUniqueID(name, "material");
Ref<Material> m = mAsset->materials.Create(name);
GetMatColorOrTex(mat, m->ambient, AI_MATKEY_COLOR_AMBIENT, aiTextureType_AMBIENT);
GetMatColorOrTex(mat, m->diffuse, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_DIFFUSE);
GetMatColorOrTex(mat, m->specular, AI_MATKEY_COLOR_SPECULAR, aiTextureType_SPECULAR);
GetMatColorOrTex(mat, m->emission, AI_MATKEY_COLOR_EMISSIVE, aiTextureType_EMISSIVE);
GetMatScalar(mat, m->shininess, AI_MATKEY_SHININESS);
}
}
void glTFExporter::ExportMeshes()
{
for (unsigned int i = 0; i < mScene->mNumMeshes; ++i) {
const aiMesh* aim = mScene->mMeshes[i];
std::string meshId = mAsset->FindUniqueID(aim->mName.C_Str(), "mesh");
Ref<Mesh> m = mAsset->meshes.Create(meshId);
m->primitives.resize(1);
Mesh::Primitive& p = m->primitives.back();
p.material = mAsset->materials.Get(aim->mMaterialIndex);
std::string bufferId = mAsset->FindUniqueID(meshId, "buffer");
Ref<Buffer> b = mAsset->GetBodyBuffer();
if (!b) {
b = mAsset->buffers.Create(bufferId);
}
Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
if (v) p.attributes.position.push_back(v);
Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
if (n) p.attributes.normal.push_back(n);
for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
if (aim->mNumUVComponents[i] > 0) {
AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i], AttribType::VEC3, type, ComponentType_FLOAT, true);
if (tc) p.attributes.texcoord.push_back(tc);
}
}
if (aim->mNumFaces > 0) {
unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
std::vector<uint16_t> indices;
indices.resize(aim->mNumFaces * nIndicesPerFace);
for (size_t i = 0; i < aim->mNumFaces; ++i) {
for (size_t j = 0; j < nIndicesPerFace; ++j) {
indices[i*nIndicesPerFace + j] = uint16_t(aim->mFaces[i].mIndices[j]);
}
}
p.indices = ExportData(*mAsset, meshId, b, indices.size(), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_SHORT);
}
switch (aim->mPrimitiveTypes) {
case aiPrimitiveType_POLYGON:
p.mode = PrimitiveMode_TRIANGLES; break; // TODO implement this
case aiPrimitiveType_LINE:
p.mode = PrimitiveMode_LINES; break;
case aiPrimitiveType_POINT:
p.mode = PrimitiveMode_POINTS; break;
default: // aiPrimitiveType_TRIANGLE
p.mode = PrimitiveMode_TRIANGLES;
}
}
}
size_t glTFExporter::ExportNode(const aiNode* n)
{
Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
if (!n->mTransformation.IsIdentity()) {
node->matrix.isPresent = true;
CopyValue(n->mTransformation, node->matrix.value);
}
for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
}
for (unsigned int i = 0; i < n->mNumChildren; ++i) {
size_t idx = ExportNode(n->mChildren[i]);
node->children.push_back(mAsset->nodes.Get(idx));
}
return node.GetIndex();
}
void glTFExporter::ExportScene()
{
const char* sceneName = "defaultScene";
Ref<Scene> scene = mAsset->scenes.Create(sceneName);
// root node will be the first one exported (idx 0)
if (mAsset->nodes.Size() > 0) {
scene->nodes.push_back(mAsset->nodes.Get(size_t(0)));
}
// set as the default scene
mAsset->scene = scene;
}
void glTFExporter::ExportMetadata()
{
glTF::AssetMetadata& asset = mAsset->asset;
asset.version = 1;
char buffer[256];
sprintf(buffer, "Open Asset Import Library (assimp v%d.%d.%d)",
aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
asset.generator = buffer;
}
#endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
#endif // ASSIMP_BUILD_NO_EXPORT

108
code/glTFExporter.h Normal file
View File

@@ -0,0 +1,108 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2015, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file GltfExporter.h
* Declares the exporter class to write a scene to a gltf/glb file
*/
#ifndef AI_GLTFEXPORTER_H_INC
#define AI_GLTFEXPORTER_H_INC
#include <assimp/types.h>
#include <assimp/material.h>
#include <sstream>
#include <vector>
#include <map>
#include "boost/scoped_ptr.hpp"
struct aiScene;
struct aiNode;
struct aiMaterial;
namespace glTF
{
class Asset;
struct TexProperty;
}
namespace Assimp
{
class IOSystem;
class IOStream;
class ExportProperties;
// ------------------------------------------------------------------------------------------------
/** Helper class to export a given scene to an glTF file. */
// ------------------------------------------------------------------------------------------------
class glTFExporter
{
public:
/// Constructor for a specific scene to export
glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
const ExportProperties* pProperties, bool binary);
private:
const char* mFilename;
IOSystem* mIOSystem;
const aiScene* mScene;
const ExportProperties* mProperties;
std::map<std::string, size_t> mTexturesByPath;
glTF::Asset* mAsset;
std::vector<unsigned char> mBodyData;
void WriteBinaryData(IOStream* outfile, std::size_t sceneLength);
void GetMatColorOrTex(const aiMaterial* mat, glTF::TexProperty& prop, const char* propName, int type, int idx, aiTextureType tt);
void ExportMetadata();
void ExportMaterials();
void ExportMeshes();
size_t ExportNode(const aiNode* node);
void ExportScene();
};
}
#endif

629
code/glTFImporter.cpp Normal file
View File

@@ -0,0 +1,629 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2015, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
#include "glTFImporter.h"
#include "StringComparison.h"
#include "boost/scoped_ptr.hpp"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/ai_assert.h>
#include <assimp/DefaultLogger.hpp>
#include <boost/shared_ptr.hpp>
#include "glTFAsset.h"
using namespace Assimp;
using namespace glTF;
//
// glTFImporter
//
static const aiImporterDesc desc = {
"glTF Importer",
"",
"",
"",
aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour
| aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
0,
0,
0,
0,
"gltf glb"
};
glTFImporter::glTFImporter()
: BaseImporter()
{
}
glTFImporter::~glTFImporter()
{
}
const aiImporterDesc* glTFImporter::GetInfo() const
{
return &desc;
}
bool glTFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
{
const std::string& extension = GetExtension(pFile);
if (extension == "gltf" || extension == "glb")
return true;
if ((checkSig || !extension.length()) && pIOHandler) {
char buffer[4];
boost::scoped_ptr<IOStream> pStream(pIOHandler->Open(pFile));
if (pStream && pStream->Read(buffer, sizeof(buffer), 1) == 1) {
if (memcmp(buffer, AI_GLB_MAGIC_NUMBER, sizeof(buffer)) == 0) {
return true; // Has GLB header
}
else if (memcmp(buffer, "{\r\n ", sizeof(buffer)) == 0
|| memcmp(buffer, "{\n ", sizeof(buffer)) == 0) {
// seems a JSON file, and we're the only format that can read them
return true;
}
}
}
return false;
}
//static void CopyValue(const glTF::vec3& v, aiColor3D& out)
//{
// out.r = v[0]; out.g = v[1]; out.b = v[2];
//}
static void CopyValue(const glTF::vec4& v, aiColor4D& out)
{
out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = v[3];
}
static void CopyValue(const glTF::vec4& v, aiColor3D& out)
{
out.r = v[0]; out.g = v[1]; out.b = v[2];
}
static void CopyValue(const glTF::vec3& v, aiVector3D& out)
{
out.x = v[0]; out.y = v[1]; out.z = v[2];
}
static void CopyValue(const glTF::vec4& v, aiQuaternion& out)
{
out.x = v[0]; out.y = v[1]; out.z = v[2]; out.w = v[3];
}
static void CopyValue(const glTF::mat4& v, aiMatrix4x4& o)
{
o.a1 = v[ 0]; o.b1 = v[ 1]; o.c1 = v[ 2]; o.d1 = v[ 3];
o.a2 = v[ 4]; o.b2 = v[ 5]; o.c2 = v[ 6]; o.d2 = v[ 7];
o.a3 = v[ 8]; o.b3 = v[ 9]; o.c3 = v[10]; o.d3 = v[11];
o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15];
}
inline void SetMaterialColorProperty(std::vector<int>& embeddedTexIdxs, Asset& r, glTF::TexProperty prop, aiMaterial* mat,
aiTextureType texType, const char* pKey, unsigned int type, unsigned int idx)
{
if (prop.texture) {
if (prop.texture->source) {
aiString uri(prop.texture->source->uri);
int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
if (texIdx != -1) { // embedded
// setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
uri.data[0] = '*';
uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
}
mat->AddProperty(&uri, _AI_MATKEY_TEXTURE_BASE, texType, 0);
}
}
else {
aiColor4D col;
CopyValue(prop.color, col);
if (col.r != 1.f || col.g != 1.f || col.b != 1.f || col.a != 1.f) {
mat->AddProperty(&col, 1, pKey, type, idx);
}
}
}
void glTFImporter::ImportMaterials(glTF::Asset& r)
{
mScene->mNumMaterials = r.materials.Size();
mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials];
for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
aiMaterial* aimat = mScene->mMaterials[i] = new aiMaterial();
Material& mat = r.materials[i];
/*if (!mat.name.empty())*/ {
aiString str(mat.id /*mat.name*/);
aimat->AddProperty(&str, AI_MATKEY_NAME);
}
SetMaterialColorProperty(embeddedTexIdxs, r, mat.diffuse, aimat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE);
SetMaterialColorProperty(embeddedTexIdxs, r, mat.specular, aimat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
SetMaterialColorProperty(embeddedTexIdxs, r, mat.ambient, aimat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT);
if (mat.shininess > 0.f) {
aimat->AddProperty(&mat.shininess, 1, AI_MATKEY_SHININESS);
}
}
if (mScene->mNumMaterials == 0) {
mScene->mNumMaterials = 1;
mScene->mMaterials = new aiMaterial*[1];
mScene->mMaterials[0] = new aiMaterial();
}
}
inline void SetFace(aiFace& face, int a)
{
face.mNumIndices = 1;
face.mIndices = new unsigned int[1];
face.mIndices[0] = a;
}
inline void SetFace(aiFace& face, int a, int b)
{
face.mNumIndices = 2;
face.mIndices = new unsigned int[2];
face.mIndices[0] = a;
face.mIndices[1] = b;
}
inline void SetFace(aiFace& face, int a, int b, int c)
{
face.mNumIndices = 3;
face.mIndices = new unsigned int[3];
face.mIndices[0] = a;
face.mIndices[1] = b;
face.mIndices[2] = c;
}
void glTFImporter::ImportMeshes(glTF::Asset& r)
{
std::vector<aiMesh*> meshes;
unsigned int k = 0;
for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
Mesh& mesh = r.meshes[m];
meshOffsets.push_back(k);
k += mesh.primitives.size();
for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
Mesh::Primitive& prim = mesh.primitives[p];
aiMesh* aim = new aiMesh();
meshes.push_back(aim);
aim->mName = mesh.id;
if (mesh.primitives.size() > 1) {
size_t& len = aim->mName.length;
aim->mName.data[len] = '-';
len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, MAXLEN - len - 1, p);
}
switch (prim.mode) {
case PrimitiveMode_POINTS:
aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
break;
case PrimitiveMode_LINES:
case PrimitiveMode_LINE_LOOP:
case PrimitiveMode_LINE_STRIP:
aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
break;
case PrimitiveMode_TRIANGLES:
case PrimitiveMode_TRIANGLE_STRIP:
case PrimitiveMode_TRIANGLE_FAN:
aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
break;
}
Mesh::Primitive::Attributes& attr = prim.attributes;
if (attr.position.size() > 0 && attr.position[0]) {
aim->mNumVertices = attr.position[0]->count;
attr.position[0]->ExtractData(aim->mVertices);
}
if (attr.normal.size() > 0 && attr.normal[0]) {
attr.normal[0]->ExtractData(aim->mNormals);
}
for (size_t tc = 0; tc < attr.texcoord.size() && tc <= AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
}
if (prim.indices) {
aiFace* faces = 0;
size_t nFaces = 0;
unsigned int count = prim.indices->count;
Accessor::Indexer data = prim.indices->GetIndexer();
switch (prim.mode) {
case PrimitiveMode_POINTS: {
nFaces = count;
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; ++i) {
SetFace(faces[i], data.GetUInt(i));
}
break;
}
case PrimitiveMode_LINES: {
nFaces = count / 2;
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; i += 2) {
SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
}
break;
}
case PrimitiveMode_LINE_LOOP:
case PrimitiveMode_LINE_STRIP: {
nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
faces = new aiFace[nFaces];
SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
for (unsigned int i = 2; i < count; ++i) {
SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
}
if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
}
break;
}
case PrimitiveMode_TRIANGLES: {
nFaces = count / 3;
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; i += 3) {
SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
}
break;
}
case PrimitiveMode_TRIANGLE_STRIP: {
nFaces = count - 2;
faces = new aiFace[nFaces];
SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
for (unsigned int i = 3; i < count; ++i) {
SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], data.GetUInt(i));
}
break;
}
case PrimitiveMode_TRIANGLE_FAN:
nFaces = count - 2;
faces = new aiFace[nFaces];
SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
for (unsigned int i = 3; i < count; ++i) {
SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i));
}
break;
}
if (faces) {
aim->mFaces = faces;
aim->mNumFaces = nFaces;
}
}
if (prim.material) {
aim->mMaterialIndex = prim.material.GetIndex();
}
}
}
meshOffsets.push_back(k);
CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
}
void glTFImporter::ImportCameras(glTF::Asset& r)
{
if (!r.cameras.Size()) return;
mScene->mNumCameras = r.cameras.Size();
mScene->mCameras = new aiCamera*[r.cameras.Size()];
for (size_t i = 0; i < r.cameras.Size(); ++i) {
Camera& cam = r.cameras[i];
aiCamera* aicam = mScene->mCameras[i] = new aiCamera();
if (cam.type == Camera::Perspective) {
aicam->mAspect = cam.perspective.aspectRatio;
aicam->mHorizontalFOV = cam.perspective.yfov * aicam->mAspect;
aicam->mClipPlaneFar = cam.perspective.zfar;
aicam->mClipPlaneNear = cam.perspective.znear;
}
else {
// assimp does not support orthographic cameras
}
}
}
void glTFImporter::ImportLights(glTF::Asset& r)
{
if (!r.lights.Size()) return;
mScene->mNumLights = r.lights.Size();
mScene->mLights = new aiLight*[r.lights.Size()];
for (size_t i = 0; i < r.lights.Size(); ++i) {
Light& l = r.lights[i];
aiLight* ail = mScene->mLights[i] = new aiLight();
switch (l.type) {
case Light::Type_directional:
ail->mType = aiLightSource_DIRECTIONAL; break;
case Light::Type_spot:
ail->mType = aiLightSource_SPOT; break;
case Light::Type_ambient:
ail->mType = aiLightSource_AMBIENT; break;
default: // Light::Type_point
ail->mType = aiLightSource_POINT; break;
}
CopyValue(l.color, ail->mColorAmbient);
CopyValue(l.color, ail->mColorDiffuse);
CopyValue(l.color, ail->mColorSpecular);
ail->mAngleOuterCone = l.falloffAngle;
ail->mAngleInnerCone = l.falloffExponent; // TODO fix this, it does not look right at all
ail->mAttenuationConstant = l.constantAttenuation;
ail->mAttenuationLinear = l.linearAttenuation;
ail->mAttenuationQuadratic = l.quadraticAttenuation;
}
}
aiNode* ImportNode(aiScene* pScene, glTF::Asset& r, std::vector<unsigned int>& meshOffsets, glTF::Ref<glTF::Node>& ptr)
{
Node& node = *ptr;
aiNode* ainode = new aiNode(node.id);
if (!node.children.empty()) {
ainode->mNumChildren = node.children.size();
ainode->mChildren = new aiNode*[ainode->mNumChildren];
for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
aiNode* child = ImportNode(pScene, r, meshOffsets, node.children[i]);
child->mParent = ainode;
ainode->mChildren[i] = child;
}
}
aiMatrix4x4 matrix = ainode->mTransformation;
if (node.matrix.isPresent) {
CopyValue(node.matrix.value, matrix);
}
else {
if (node.translation.isPresent) {
aiVector3D trans;
CopyValue(node.translation.value, trans);
aiMatrix4x4 t;
aiMatrix4x4::Translation(trans, t);
matrix = t * matrix;
}
if (node.scale.isPresent) {
aiVector3D scal(1.f);
CopyValue(node.scale.value, scal);
aiMatrix4x4 s;
aiMatrix4x4::Scaling(scal, s);
matrix = s * matrix;
}
if (node.rotation.isPresent) {
aiQuaternion rot;
CopyValue(node.rotation.value, rot);
matrix = aiMatrix4x4(rot.GetMatrix()) * matrix;
}
}
if (!node.meshes.empty()) {
int count = 0;
for (size_t i = 0; i < node.meshes.size(); ++i) {
int idx = node.meshes[i].GetIndex();
count += meshOffsets[idx + 1] - meshOffsets[idx];
}
ainode->mNumMeshes = count;
ainode->mMeshes = new unsigned int[count];
int k = 0;
for (size_t i = 0; i < node.meshes.size(); ++i) {
int idx = node.meshes[i].GetIndex();
for (size_t j = meshOffsets[idx]; j < meshOffsets[idx + 1]; ++j, ++k) {
ainode->mMeshes[k] = j;
}
}
}
if (node.camera) {
pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
}
if (node.light) {
pScene->mLights[node.light.GetIndex()]->mName = ainode->mName;
}
return ainode;
}
void glTFImporter::ImportNodes(glTF::Asset& r)
{
if (!r.scene) return;
std::vector< Ref<Node> > rootNodes = r.scene->nodes;
// The root nodes
unsigned int numRootNodes = rootNodes.size();
if (numRootNodes == 1) { // a single root node: use it
mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
}
else if (numRootNodes > 1) { // more than one root node: create a fake root
aiNode* root = new aiNode("ROOT");
root->mChildren = new aiNode*[numRootNodes];
for (unsigned int i = 0; i < numRootNodes; ++i) {
aiNode* node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
node->mParent = root;
root->mChildren[root->mNumChildren++] = node;
}
mScene->mRootNode = root;
}
//if (!mScene->mRootNode) {
// mScene->mRootNode = new aiNode("EMPTY");
//}
}
void glTFImporter::ImportEmbeddedTextures(glTF::Asset& r)
{
embeddedTexIdxs.resize(r.images.Size(), -1);
int numEmbeddedTexs = 0;
for (size_t i = 0; i < r.images.Size(); ++i) {
if (r.images[i].HasData())
numEmbeddedTexs += 1;
}
if (numEmbeddedTexs == 0)
return;
mScene->mTextures = new aiTexture*[numEmbeddedTexs];
// Add the embedded textures
for (size_t i = 0; i < r.images.Size(); ++i) {
Image img = r.images[i];
if (!img.HasData()) continue;
int idx = mScene->mNumTextures++;
embeddedTexIdxs[i] = idx;
aiTexture* tex = mScene->mTextures[idx] = new aiTexture();
size_t length = img.GetDataLength();
void* data = img.StealData();
tex->mWidth = static_cast<unsigned int>(length);
tex->mHeight = 0;
tex->pcData = reinterpret_cast<aiTexel*>(data);
if (!img.mimeType.empty()) {
const char* ext = strchr(img.mimeType.c_str(), '/') + 1;
if (ext) {
if (strcmp(ext, "jpeg") == 0) ext = "jpg";
size_t len = strlen(ext);
if (len <= 3) {
strcpy(tex->achFormatHint, ext);
}
}
}
}
}
void glTFImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) {
this->mScene = pScene;
// read the asset file
glTF::Asset asset(pIOHandler);
asset.Load(pFile, GetExtension(pFile) == "glb");
//
// Copy the data out
//
ImportEmbeddedTextures(asset);
ImportMaterials(asset);
ImportMeshes(asset);
ImportCameras(asset);
ImportLights(asset);
ImportNodes(asset);
// TODO: it does not split the loaded vertices, should it?
pScene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
if (pScene->mNumMeshes == 0) {
pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
}
}
#endif // ASSIMP_BUILD_NO_GLTF_IMPORTER

90
code/glTFImporter.h Normal file
View File

@@ -0,0 +1,90 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2015, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#ifndef AI_GLTFIMPORTER_H_INC
#define AI_GLTFIMPORTER_H_INC
#include "BaseImporter.h"
#include "DefaultIOSystem.h"
struct aiNode;
namespace glTF
{
class Asset;
}
namespace Assimp {
/**
* Load the glTF format.
* https://github.com/KhronosGroup/glTF/tree/master/specification
*/
class glTFImporter : public BaseImporter{
public:
glTFImporter();
virtual ~glTFImporter();
virtual bool CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig ) const;
protected:
virtual const aiImporterDesc* GetInfo() const;
virtual void InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler );
private:
std::vector<unsigned int> meshOffsets;
std::vector<int> embeddedTexIdxs;
aiScene* mScene;
void ImportEmbeddedTextures(glTF::Asset& a);
void ImportMaterials(glTF::Asset& a);
void ImportMeshes(glTF::Asset& a);
void ImportCameras(glTF::Asset& a);
void ImportLights(glTF::Asset& a);
void ImportNodes(glTF::Asset& a);
};
} // Namespace assimp
#endif // AI_GLTFIMPORTER_H_INC

View File

@@ -76,7 +76,7 @@ public:
// ----------------------------------------------------------------------------------
//! Construction from an existing IOStream
CIrrXML_IOStreamReader(IOStream* _stream)
explicit CIrrXML_IOStreamReader(IOStream* _stream)
: stream (_stream)
, t (0)
{