// ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. void DXFImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile)); // Check whether we can read from the file if( file.get() == NULL) { throw DeadlyImportError( "Failed to open DXF file " + pFile + ""); } // read the contents of the file in a buffer std::vector<char> buffer2; TextFileToBuffer(file.get(),buffer2); buffer = &buffer2[0]; bRepeat = false; mDefaultLayer = NULL; // check whether this is a binaray DXF file - we can't read binary DXF files :-( if (!strncmp(AI_DXF_BINARY_IDENT,buffer,AI_DXF_BINARY_IDENT_LEN)) throw DeadlyImportError("DXF: Binary files are not supported at the moment"); // now get all lines of the file while (GetNextToken()) { if (2 == groupCode) { // ENTITIES and BLOCKS sections - skip the whole rest, no need to waste our time with them if (!::strcmp(cursor,"ENTITIES") || !::strcmp(cursor,"BLOCKS")) { if (!ParseEntities()) break; else bRepeat = true; } // other sections - skip them to make sure there will be no name conflicts else { while ( GetNextToken()) { if (!::strcmp(cursor,"ENDSEC")) break; } } } // print comment strings else if (999 == groupCode) { DefaultLogger::get()->info(std::string( cursor )); } else if (!groupCode && !::strcmp(cursor,"EOF")) break; } // find out how many valud layers we have for (std::vector<LayerInfo>::const_iterator it = mLayers.begin(),end = mLayers.end(); it != end;++it) { if (!(*it).vPositions.empty()) ++pScene->mNumMeshes; } if (!pScene->mNumMeshes) throw DeadlyImportError("DXF: this file contains no 3d data"); pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ]; unsigned int m = 0; for (std::vector<LayerInfo>::const_iterator it = mLayers.begin(),end = mLayers.end();it != end;++it) { if ((*it).vPositions.empty()) { continue; } // generate the output mesh aiMesh* pMesh = pScene->mMeshes[m++] = new aiMesh(); const std::vector<aiVector3D>& vPositions = (*it).vPositions; const std::vector<aiColor4D>& vColors = (*it).vColors; // check whether we need vertex colors here aiColor4D* clrOut = NULL; const aiColor4D* clr = NULL; for (std::vector<aiColor4D>::const_iterator it2 = (*it).vColors.begin(), end2 = (*it).vColors.end();it2 != end2; ++it2) { if ((*it2).r == (*it2).r) /* qnan? */ { clrOut = pMesh->mColors[0] = new aiColor4D[vPositions.size()]; for (unsigned int i = 0; i < vPositions.size();++i) clrOut[i] = aiColor4D(0.6f,0.6f,0.6f,1.0f); clr = &vColors[0]; break; } } pMesh->mNumFaces = (unsigned int)vPositions.size() / 4u; pMesh->mFaces = new aiFace[pMesh->mNumFaces]; aiVector3D* vpOut = pMesh->mVertices = new aiVector3D[vPositions.size()]; const aiVector3D* vp = &vPositions[0]; for (unsigned int i = 0; i < pMesh->mNumFaces;++i) { aiFace& face = pMesh->mFaces[i]; // check whether we need four, three or two indices here if (vp[1] == vp[2]) { face.mNumIndices = 2; } else if (vp[3] == vp[2]) { face.mNumIndices = 3; } else face.mNumIndices = 4; face.mIndices = new unsigned int[face.mNumIndices]; for (unsigned int a = 0; a < face.mNumIndices;++a) { *vpOut++ = vp[a]; if (clr) { if (is_not_qnan( clr[a].r )) { *clrOut = clr[a]; } ++clrOut; } face.mIndices[a] = pMesh->mNumVertices++; } vp += 4; } } // generate the output scene graph pScene->mRootNode = new aiNode(); pScene->mRootNode->mName.Set("<DXF_ROOT>"); if (1 == pScene->mNumMeshes) { pScene->mRootNode->mMeshes = new unsigned int[ pScene->mRootNode->mNumMeshes = 1 ]; pScene->mRootNode->mMeshes[0] = 0; } else { pScene->mRootNode->mChildren = new aiNode*[ pScene->mRootNode->mNumChildren = pScene->mNumMeshes ]; for (m = 0; m < pScene->mRootNode->mNumChildren;++m) { aiNode* p = pScene->mRootNode->mChildren[m] = new aiNode(); p->mName.length = ::strlen( mLayers[m].name ); strcpy(p->mName.data, mLayers[m].name); p->mMeshes = new unsigned int[p->mNumMeshes = 1]; p->mMeshes[0] = m; p->mParent = pScene->mRootNode; } } // generate a default material MaterialHelper* pcMat = new MaterialHelper(); aiString s; s.Set(AI_DEFAULT_MATERIAL_NAME); pcMat->AddProperty(&s, AI_MATKEY_NAME); aiColor4D clrDiffuse(0.6f,0.6f,0.6f,1.0f); pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE); clrDiffuse = aiColor4D(1.0f,1.0f,1.0f,1.0f); pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR); clrDiffuse = aiColor4D(0.05f,0.05f,0.05f,1.0f); pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT); pScene->mNumMaterials = 1; pScene->mMaterials = new aiMaterial*[1]; pScene->mMaterials[0] = pcMat; // flip winding order to be ccw FlipWindingOrderProcess flipper; flipper.Execute(pScene); // --- everything destructs automatically --- }
// ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. void UnrealImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { // For any of the 3 files being passed get the three correct paths // First of all, determine file extension std::string::size_type pos = pFile.find_last_of('.'); std::string extension = GetExtension(pFile); std::string d_path,a_path,uc_path; if (extension == "3d") { // jjjj_d.3d // jjjj_a.3d pos = pFile.find_last_of('_'); if (std::string::npos == pos) { throw DeadlyImportError("UNREAL: Unexpected naming scheme"); } extension = pFile.substr(0,pos); } else { extension = pFile.substr(0,pos); } // build proper paths d_path = extension+"_d.3d"; a_path = extension+"_a.3d"; uc_path = extension+".uc"; DefaultLogger::get()->debug("UNREAL: data file is " + d_path); DefaultLogger::get()->debug("UNREAL: aniv file is " + a_path); DefaultLogger::get()->debug("UNREAL: uc file is " + uc_path); // and open the files ... we can't live without them IOStream* p = pIOHandler->Open(d_path); if (!p) throw DeadlyImportError("UNREAL: Unable to open _d file"); StreamReaderLE d_reader(pIOHandler->Open(d_path)); const uint16_t numTris = d_reader.GetI2(); const uint16_t numVert = d_reader.GetI2(); d_reader.IncPtr(44); if (!numTris || numVert < 3) throw DeadlyImportError("UNREAL: Invalid number of vertices/triangles"); // maximum texture index unsigned int maxTexIdx = 0; // collect triangles std::vector<Unreal::Triangle> triangles(numTris); for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) { Unreal::Triangle& tri = *it; for (unsigned int i = 0; i < 3;++i) { tri.mVertex[i] = d_reader.GetI2(); if (tri.mVertex[i] >= numTris) { DefaultLogger::get()->warn("UNREAL: vertex index out of range"); tri.mVertex[i] = 0; } } tri.mType = d_reader.GetI1(); // handle mesh flagss? if (configHandleFlags) tri.mType = Unreal::MF_NORMAL_OS; else { // ignore MOD and MASKED for the moment, treat them as two-sided if (tri.mType == Unreal::MF_NORMAL_MOD_TS || tri.mType == Unreal::MF_NORMAL_MASKED_TS) tri.mType = Unreal::MF_NORMAL_TS; } d_reader.IncPtr(1); for (unsigned int i = 0; i < 3;++i) for (unsigned int i2 = 0; i2 < 2;++i2) tri.mTex[i][i2] = d_reader.GetI1(); tri.mTextureNum = d_reader.GetI1(); maxTexIdx = std::max(maxTexIdx,(unsigned int)tri.mTextureNum); d_reader.IncPtr(1); } p = pIOHandler->Open(a_path); if (!p) throw DeadlyImportError("UNREAL: Unable to open _a file"); StreamReaderLE a_reader(pIOHandler->Open(a_path)); // read number of frames const uint32_t numFrames = a_reader.GetI2(); if (configFrameID >= numFrames) throw DeadlyImportError("UNREAL: The requested frame does not exist"); uint32_t st = a_reader.GetI2(); if (st != numVert*4) throw DeadlyImportError("UNREAL: Unexpected aniv file length"); // skip to our frame a_reader.IncPtr(configFrameID *numVert*4); // collect vertices std::vector<aiVector3D> vertices(numVert); for (std::vector<aiVector3D>::iterator it = vertices.begin(), end = vertices.end(); it != end; ++it) { int32_t val = a_reader.GetI4(); Unreal::DecompressVertex(*it,val); } // list of textures. std::vector< std::pair<unsigned int, std::string> > textures; // allocate the output scene aiNode* nd = pScene->mRootNode = new aiNode(); nd->mName.Set("<UnrealRoot>"); // we can live without the uc file if necessary boost::scoped_ptr<IOStream> pb (pIOHandler->Open(uc_path)); if (pb.get()) { std::vector<char> _data; TextFileToBuffer(pb.get(),_data); const char* data = &_data[0]; std::vector< std::pair< std::string,std::string > > tempTextures; // do a quick search in the UC file for some known, usually texture-related, tags for (;*data;++data) { if (TokenMatchI(data,"#exec",5)) { SkipSpacesAndLineEnd(&data); // #exec TEXTURE IMPORT [...] NAME=jjjjj [...] FILE=jjjj.pcx [...] if (TokenMatchI(data,"TEXTURE",7)) { SkipSpacesAndLineEnd(&data); if (TokenMatchI(data,"IMPORT",6)) { tempTextures.push_back(std::pair< std::string,std::string >()); std::pair< std::string,std::string >& me = tempTextures.back(); for (;!IsLineEnd(*data);++data) { if (!::ASSIMP_strincmp(data,"NAME=",5)) { const char *d = data+=5; for (;!IsSpaceOrNewLine(*data);++data); me.first = std::string(d,(size_t)(data-d)); } else if (!::ASSIMP_strincmp(data,"FILE=",5)) { const char *d = data+=5; for (;!IsSpaceOrNewLine(*data);++data); me.second = std::string(d,(size_t)(data-d)); } } if (!me.first.length() || !me.second.length()) tempTextures.pop_back(); } } // #exec MESHMAP SETTEXTURE MESHMAP=box NUM=1 TEXTURE=Jtex1 // #exec MESHMAP SCALE MESHMAP=box X=0.1 Y=0.1 Z=0.2 else if (TokenMatchI(data,"MESHMAP",7)) { SkipSpacesAndLineEnd(&data); if (TokenMatchI(data,"SETTEXTURE",10)) { textures.push_back(std::pair<unsigned int, std::string>()); std::pair<unsigned int, std::string>& me = textures.back(); for (;!IsLineEnd(*data);++data) { if (!::ASSIMP_strincmp(data,"NUM=",4)) { data += 4; me.first = strtoul10(data,&data); } else if (!::ASSIMP_strincmp(data,"TEXTURE=",8)) { data += 8; const char *d = data; for (;!IsSpaceOrNewLine(*data);++data); me.second = std::string(d,(size_t)(data-d)); // try to find matching path names, doesn't care if we don't find them for (std::vector< std::pair< std::string,std::string > >::const_iterator it = tempTextures.begin(); it != tempTextures.end(); ++it) { if ((*it).first == me.second) { me.second = (*it).second; break; } } } } } else if (TokenMatchI(data,"SCALE",5)) { for (;!IsLineEnd(*data);++data) { if (data[0] == 'X' && data[1] == '=') { data = fast_atoreal_move<float>(data+2,(float&)nd->mTransformation.a1); } else if (data[0] == 'Y' && data[1] == '=') { data = fast_atoreal_move<float>(data+2,(float&)nd->mTransformation.b2); } else if (data[0] == 'Z' && data[1] == '=') { data = fast_atoreal_move<float>(data+2,(float&)nd->mTransformation.c3); } } } } } } } else { DefaultLogger::get()->error("Unable to open .uc file"); } std::vector<Unreal::TempMat> materials; materials.reserve(textures.size()*2+5); // find out how many output meshes and materials we'll have and build material indices for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) { Unreal::Triangle& tri = *it; Unreal::TempMat mat(tri); std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(),materials.end(),mat); if (nt == materials.end()) { // add material tri.matIndex = materials.size(); mat.numFaces = 1; materials.push_back(mat); ++pScene->mNumMeshes; } else { tri.matIndex = static_cast<unsigned int>(nt-materials.begin()); ++nt->numFaces; } } if (!pScene->mNumMeshes) { throw DeadlyImportError("UNREAL: Unable to find valid mesh data"); } // allocate meshes and bind them to the node graph pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]; pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = pScene->mNumMeshes]; nd->mNumMeshes = pScene->mNumMeshes; nd->mMeshes = new unsigned int[nd->mNumMeshes]; for (unsigned int i = 0; i < pScene->mNumMeshes;++i) { aiMesh* m = pScene->mMeshes[i] = new aiMesh(); m->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; const unsigned int num = materials[i].numFaces; m->mFaces = new aiFace [num]; m->mVertices = new aiVector3D [num*3]; m->mTextureCoords[0] = new aiVector3D [num*3]; nd->mMeshes[i] = i; // create materials, too aiMaterial* mat = new aiMaterial(); pScene->mMaterials[i] = mat; // all white by default - texture rulez aiColor3D color(1.f,1.f,1.f); aiString s; ::sprintf(s.data,"mat%u_tx%u_",i,materials[i].tex); // set the two-sided flag if (materials[i].type == Unreal::MF_NORMAL_TS) { const int twosided = 1; mat->AddProperty(&twosided,1,AI_MATKEY_TWOSIDED); ::strcat(s.data,"ts_"); } else ::strcat(s.data,"os_"); // make TRANS faces 90% opaque that RemRedundantMaterials won't catch us if (materials[i].type == Unreal::MF_NORMAL_TRANS_TS) { const float opac = 0.9f; mat->AddProperty(&opac,1,AI_MATKEY_OPACITY); ::strcat(s.data,"tran_"); } else ::strcat(s.data,"opaq_"); // a special name for the weapon attachment point if (materials[i].type == Unreal::MF_WEAPON_PLACEHOLDER) { s.length = ::sprintf(s.data,"$WeaponTag$"); color = aiColor3D(0.f,0.f,0.f); } // set color and name mat->AddProperty(&color,1,AI_MATKEY_COLOR_DIFFUSE); s.length = ::strlen(s.data); mat->AddProperty(&s,AI_MATKEY_NAME); // set texture, if any const unsigned int tex = materials[i].tex; for (std::vector< std::pair< unsigned int, std::string > >::const_iterator it = textures.begin();it != textures.end();++it) { if ((*it).first == tex) { s.Set((*it).second); mat->AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0)); break; } } } // fill them. for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) { Unreal::Triangle& tri = *it; Unreal::TempMat mat(tri); std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(),materials.end(),mat); aiMesh* mesh = pScene->mMeshes[nt-materials.begin()]; aiFace& f = mesh->mFaces[mesh->mNumFaces++]; f.mIndices = new unsigned int[f.mNumIndices = 3]; for (unsigned int i = 0; i < 3;++i,mesh->mNumVertices++) { f.mIndices[i] = mesh->mNumVertices; mesh->mVertices[mesh->mNumVertices] = vertices[ tri.mVertex[i] ]; mesh->mTextureCoords[0][mesh->mNumVertices] = aiVector3D( tri.mTex[i][0] / 255.f, 1.f - tri.mTex[i][1] / 255.f, 0.f); } } // convert to RH MakeLeftHandedProcess hero; hero.Execute(pScene); FlipWindingOrderProcess flipper; flipper.Execute(pScene); }
// ------------------------------------------------------------------------------------------------ void B3DImporter::ReadBB3D( aiScene *scene ){ _textures.clear(); _materials.size(); _vertices.clear(); _meshes.clear(); _nodes.clear(); _nodeAnims.clear(); _animations.clear(); string t=ReadChunk(); if ( t=="BB3D" ){ int version=ReadInt(); if (!DefaultLogger::isNullLogger()) { char dmp[128]; sprintf(dmp,"B3D file format version: %i",version); DefaultLogger::get()->info(dmp); } while ( ChunkSize() ){ string t=ReadChunk(); if ( t=="TEXS" ){ ReadTEXS(); }else if ( t=="BRUS" ){ ReadBRUS(); }else if ( t=="NODE" ){ ReadNODE( 0 ); } ExitChunk(); } } ExitChunk(); if ( !_nodes.size() ) Fail( "No nodes" ); if ( !_meshes.size() ) Fail( "No meshes" ); //Fix nodes/meshes/bones for (size_t i=0;i<_nodes.size();++i ){ aiNode *node=_nodes[i]; for ( size_t j=0;j<node->mNumMeshes;++j ){ aiMesh *mesh=_meshes[node->mMeshes[j]]; int n_tris=mesh->mNumFaces; int n_verts=mesh->mNumVertices=n_tris * 3; aiVector3D *mv=mesh->mVertices=new aiVector3D[ n_verts ],*mn=0,*mc=0; if ( _vflags & 1 ) mn=mesh->mNormals=new aiVector3D[ n_verts ]; if ( _tcsets ) mc=mesh->mTextureCoords[0]=new aiVector3D[ n_verts ]; aiFace *face=mesh->mFaces; vector< vector<aiVertexWeight> > vweights( _nodes.size() ); for ( int i=0;i<n_verts;i+=3 ){ for ( int j=0;j<3;++j ){ Vertex &v=_vertices[face->mIndices[j]]; *mv++=v.vertex; if ( mn ) *mn++=v.normal; if ( mc ) *mc++=v.texcoords; face->mIndices[j]=i+j; for ( int k=0;k<4;++k ){ if ( !v.weights[k] ) break; int bone=v.bones[k]; float weight=v.weights[k]; vweights[bone].push_back( aiVertexWeight(i+j,weight) ); } } ++face; } vector<aiBone*> bones; for (size_t i=0;i<vweights.size();++i ){ vector<aiVertexWeight> &weights=vweights[i]; if ( !weights.size() ) continue; aiBone *bone=new aiBone; bones.push_back( bone ); aiNode *bnode=_nodes[i]; bone->mName=bnode->mName; bone->mNumWeights=weights.size(); bone->mWeights=to_array( weights ); aiMatrix4x4 mat=bnode->mTransformation; while ( bnode->mParent ){ bnode=bnode->mParent; mat=bnode->mTransformation * mat; } bone->mOffsetMatrix=mat.Inverse(); } mesh->mNumBones=bones.size(); mesh->mBones=to_array( bones ); } } //nodes scene->mRootNode=_nodes[0]; //material if ( !_materials.size() ){ _materials.push_back( new MaterialHelper ); } scene->mNumMaterials=_materials.size(); scene->mMaterials=to_array( _materials ); //meshes scene->mNumMeshes=_meshes.size(); scene->mMeshes=to_array( _meshes ); //animations if ( _animations.size()==1 && _nodeAnims.size() ){ aiAnimation *anim=_animations.back(); anim->mNumChannels=_nodeAnims.size(); anim->mChannels=to_array( _nodeAnims ); scene->mNumAnimations=_animations.size(); scene->mAnimations=to_array( _animations ); } // convert to RH MakeLeftHandedProcess makeleft; makeleft.Execute( scene ); FlipWindingOrderProcess flip; flip.Execute( scene ); }
// ------------------------------------------------------------------------------------------------ // Read file into given scene data structure void LWSImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { io = pIOHandler; boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb")); // Check whether we can read from the file if( file.get() == NULL) { throw DeadlyImportError( "Failed to open LWS file " + pFile + "."); } // Allocate storage and copy the contents of the file to a memory buffer std::vector< char > mBuffer; TextFileToBuffer(file.get(),mBuffer); // Parse the file structure LWS::Element root; const char* dummy = &mBuffer[0]; root.Parse(dummy); // Construct a Batchimporter to read more files recursively BatchLoader batch(pIOHandler); // batch.SetBasePath(pFile); // Construct an array to receive the flat output graph std::list<LWS::NodeDesc> nodes; unsigned int cur_light = 0, cur_camera = 0, cur_object = 0; unsigned int num_light = 0, num_camera = 0, num_object = 0; // check magic identifier, 'LWSC' bool motion_file = false; std::list< LWS::Element >::const_iterator it = root.children.begin(); if ((*it).tokens[0] == "LWMO") motion_file = true; if ((*it).tokens[0] != "LWSC" && !motion_file) throw DeadlyImportError("LWS: Not a LightWave scene, magic tag LWSC not found"); // get file format version and print to log ++it; unsigned int version = strtoul10((*it).tokens[0].c_str()); DefaultLogger::get()->info("LWS file format version is " + (*it).tokens[0]); first = 0.; last = 60.; fps = 25.; /* seems to be a good default frame rate */ // Now read all elements in a very straghtforward manner for (; it != root.children.end(); ++it) { const char* c = (*it).tokens[1].c_str(); // 'FirstFrame': begin of animation slice if ((*it).tokens[0] == "FirstFrame") { if (150392. != first /* see SetupProperties() */) first = strtoul10(c,&c)-1.; /* we're zero-based */ } // 'LastFrame': end of animation slice else if ((*it).tokens[0] == "LastFrame") { if (150392. != last /* see SetupProperties() */) last = strtoul10(c,&c)-1.; /* we're zero-based */ } // 'FramesPerSecond': frames per second else if ((*it).tokens[0] == "FramesPerSecond") { fps = strtoul10(c,&c); } // 'LoadObjectLayer': load a layer of a specific LWO file else if ((*it).tokens[0] == "LoadObjectLayer") { // get layer index const int layer = strtoul10(c,&c); // setup the layer to be loaded BatchLoader::PropertyMap props; SetGenericProperty(props.ints,AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,layer); // add node to list LWS::NodeDesc d; d.type = LWS::NodeDesc::OBJECT; if (version >= 4) { // handle LWSC 4 explicit ID SkipSpaces(&c); d.number = strtoul16(c,&c) & AI_LWS_MASK; } else d.number = cur_object++; // and add the file to the import list SkipSpaces(&c); std::string path = FindLWOFile( c ); d.path = path; d.id = batch.AddLoadRequest(path,0,&props); nodes.push_back(d); num_object++; } // 'LoadObject': load a LWO file into the scenegraph else if ((*it).tokens[0] == "LoadObject") { // add node to list LWS::NodeDesc d; d.type = LWS::NodeDesc::OBJECT; if (version >= 4) { // handle LWSC 4 explicit ID d.number = strtoul16(c,&c) & AI_LWS_MASK; SkipSpaces(&c); } else d.number = cur_object++; std::string path = FindLWOFile( c ); d.id = batch.AddLoadRequest(path,0,NULL); d.path = path; nodes.push_back(d); num_object++; } // 'AddNullObject': add a dummy node to the hierarchy else if ((*it).tokens[0] == "AddNullObject") { // add node to list LWS::NodeDesc d; d.type = LWS::NodeDesc::OBJECT; if (version >= 4) { // handle LWSC 4 explicit ID d.number = strtoul16(c,&c) & AI_LWS_MASK; SkipSpaces(&c); } else d.number = cur_object++; d.name = c; nodes.push_back(d); num_object++; } // 'NumChannels': Number of envelope channels assigned to last layer else if ((*it).tokens[0] == "NumChannels") { // ignore for now } // 'Channel': preceedes any envelope description else if ((*it).tokens[0] == "Channel") { if (nodes.empty()) { if (motion_file) { // LightWave motion file. Add dummy node LWS::NodeDesc d; d.type = LWS::NodeDesc::OBJECT; d.name = c; d.number = cur_object++; nodes.push_back(d); } else DefaultLogger::get()->error("LWS: Unexpected keyword: \'Channel\'"); } // important: index of channel nodes.back().channels.push_back(LWO::Envelope()); LWO::Envelope& env = nodes.back().channels.back(); env.index = strtoul10(c); // currently we can just interpret the standard channels 0...9 // (hack) assume that index-i yields the binary channel type from LWO env.type = (LWO::EnvelopeType)(env.index+1); } // 'Envelope': a single animation channel else if ((*it).tokens[0] == "Envelope") { if (nodes.empty() || nodes.back().channels.empty()) DefaultLogger::get()->error("LWS: Unexpected keyword: \'Envelope\'"); else { ReadEnvelope((*it),nodes.back().channels.back()); } } // 'ObjectMotion': animation information for older lightwave formats else if (version < 3 && ((*it).tokens[0] == "ObjectMotion" || (*it).tokens[0] == "CameraMotion" || (*it).tokens[0] == "LightMotion")) { if (nodes.empty()) DefaultLogger::get()->error("LWS: Unexpected keyword: \'<Light|Object|Camera>Motion\'"); else { ReadEnvelope_Old(it,root.children.end(),nodes.back(),version); } } // 'Pre/PostBehavior': pre/post animation behaviour for LWSC 2 else if (version == 2 && (*it).tokens[0] == "Pre/PostBehavior") { if (nodes.empty()) DefaultLogger::get()->error("LWS: Unexpected keyword: \'Pre/PostBehavior'"); else { for (std::list<LWO::Envelope>::iterator it = nodes.back().channels.begin(); it != nodes.back().channels.end(); ++it) { // two ints per envelope LWO::Envelope& env = *it; env.pre = (LWO::PrePostBehaviour) strtoul10(c,&c); SkipSpaces(&c); env.post = (LWO::PrePostBehaviour) strtoul10(c,&c); SkipSpaces(&c); } } } // 'ParentItem': specifies the parent of the current element else if ((*it).tokens[0] == "ParentItem") { if (nodes.empty()) DefaultLogger::get()->error("LWS: Unexpected keyword: \'ParentItem\'"); else nodes.back().parent = strtoul16(c,&c); } // 'ParentObject': deprecated one for older formats else if (version < 3 && (*it).tokens[0] == "ParentObject") { if (nodes.empty()) DefaultLogger::get()->error("LWS: Unexpected keyword: \'ParentObject\'"); else { nodes.back().parent = strtoul10(c,&c) | (1u << 28u); } } // 'AddCamera': add a camera to the scenegraph else if ((*it).tokens[0] == "AddCamera") { // add node to list LWS::NodeDesc d; d.type = LWS::NodeDesc::CAMERA; if (version >= 4) { // handle LWSC 4 explicit ID d.number = strtoul16(c,&c) & AI_LWS_MASK; } else d.number = cur_camera++; nodes.push_back(d); num_camera++; } // 'CameraName': set name of currently active camera else if ((*it).tokens[0] == "CameraName") { if (nodes.empty() || nodes.back().type != LWS::NodeDesc::CAMERA) DefaultLogger::get()->error("LWS: Unexpected keyword: \'CameraName\'"); else nodes.back().name = c; } // 'AddLight': add a light to the scenegraph else if ((*it).tokens[0] == "AddLight") { // add node to list LWS::NodeDesc d; d.type = LWS::NodeDesc::LIGHT; if (version >= 4) { // handle LWSC 4 explicit ID d.number = strtoul16(c,&c) & AI_LWS_MASK; } else d.number = cur_light++; nodes.push_back(d); num_light++; } // 'LightName': set name of currently active light else if ((*it).tokens[0] == "LightName") { if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightName\'"); else nodes.back().name = c; } // 'LightIntensity': set intensity of currently active light else if ((*it).tokens[0] == "LightIntensity" || (*it).tokens[0] == "LgtIntensity" ) { if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightIntensity\'"); else fast_atoreal_move<float>(c, nodes.back().lightIntensity ); } // 'LightType': set type of currently active light else if ((*it).tokens[0] == "LightType") { if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightType\'"); else nodes.back().lightType = strtoul10(c); } // 'LightFalloffType': set falloff type of currently active light else if ((*it).tokens[0] == "LightFalloffType") { if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightFalloffType\'"); else nodes.back().lightFalloffType = strtoul10(c); } // 'LightConeAngle': set cone angle of currently active light else if ((*it).tokens[0] == "LightConeAngle") { if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightConeAngle\'"); else nodes.back().lightConeAngle = fast_atof(c); } // 'LightEdgeAngle': set area where we're smoothing from min to max intensity else if ((*it).tokens[0] == "LightEdgeAngle") { if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightEdgeAngle\'"); else nodes.back().lightEdgeAngle = fast_atof(c); } // 'LightColor': set color of currently active light else if ((*it).tokens[0] == "LightColor") { if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT) DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightColor\'"); else { c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.r ); SkipSpaces(&c); c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.g ); SkipSpaces(&c); c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.b ); } } // 'PivotPosition': position of local transformation origin else if ((*it).tokens[0] == "PivotPosition" || (*it).tokens[0] == "PivotPoint") { if (nodes.empty()) DefaultLogger::get()->error("LWS: Unexpected keyword: \'PivotPosition\'"); else { c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.x ); SkipSpaces(&c); c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.y ); SkipSpaces(&c); c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.z ); // Mark pivotPos as set nodes.back().isPivotSet = true; } } } // resolve parenting for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) { // check whether there is another node which calls us a parent for (std::list<LWS::NodeDesc>::iterator dit = nodes.begin(); dit != nodes.end(); ++dit) { if (dit != it && *it == (*dit).parent) { if ((*dit).parent_resolved) { // fixme: it's still possible to produce an overflow due to cross references .. DefaultLogger::get()->error("LWS: Found cross reference in scenegraph"); continue; } (*it).children.push_back(&*dit); (*dit).parent_resolved = &*it; } } } // find out how many nodes have no parent yet unsigned int no_parent = 0; for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) { if (!(*it).parent_resolved) ++ no_parent; } if (!no_parent) throw DeadlyImportError("LWS: Unable to find scene root node"); // Load all subsequent files batch.LoadAll(); // and build the final output graph by attaching the loaded external // files to ourselves. first build a master graph aiScene* master = new aiScene(); aiNode* nd = master->mRootNode = new aiNode(); // allocate storage for cameras&lights if (num_camera) { master->mCameras = new aiCamera*[master->mNumCameras = num_camera]; } aiCamera** cams = master->mCameras; if (num_light) { master->mLights = new aiLight*[master->mNumLights = num_light]; } aiLight** lights = master->mLights; std::vector<AttachmentInfo> attach; std::vector<aiNodeAnim*> anims; nd->mName.Set("<LWSRoot>"); nd->mChildren = new aiNode*[no_parent]; for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) { if (!(*it).parent_resolved) { aiNode* ro = nd->mChildren[ nd->mNumChildren++ ] = new aiNode(); ro->mParent = nd; // ... and build the scene graph. If we encounter object nodes, // add then to our attachment table. BuildGraph(ro,*it, attach, batch, cams, lights, anims); } } // create a master animation channel for us if (anims.size()) { master->mAnimations = new aiAnimation*[master->mNumAnimations = 1]; aiAnimation* anim = master->mAnimations[0] = new aiAnimation(); anim->mName.Set("LWSMasterAnim"); // LWS uses seconds as time units, but we convert to frames anim->mTicksPerSecond = fps; anim->mDuration = last-(first-1); /* fixme ... zero or one-based?*/ anim->mChannels = new aiNodeAnim*[anim->mNumChannels = anims.size()]; std::copy(anims.begin(),anims.end(),anim->mChannels); } // convert the master scene to RH MakeLeftHandedProcess monster_cheat; monster_cheat.Execute(master); // .. ccw FlipWindingOrderProcess flipper; flipper.Execute(master); // OK ... finally build the output graph SceneCombiner::MergeScenes(&pScene,master,attach, AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES | (!configSpeedFlag ? ( AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY | AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES) : 0)); // Check flags if (!pScene->mNumMeshes || !pScene->mNumMaterials) { pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE; if (pScene->mNumAnimations) { // construct skeleton mesh SkeletonMeshBuilder builder(pScene); } } }
// ------------------------------------------------------------------------------------------------ aiReturn Exporter::Export( const aiScene* pScene, const char* pFormatId, const char* pPath, unsigned int pPreprocessing, const ExportProperties* pProperties) { ASSIMP_BEGIN_EXCEPTION_REGION(); // when they create scenes from scratch, users will likely create them not in verbose // format. They will likely not be aware that there is a flag in the scene to indicate // this, however. To avoid surprises and bug reports, we check for duplicates in // meshes upfront. const bool is_verbose_format = !(pScene->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) || IsVerboseFormat(pScene); pimpl->mProgressHandler->UpdateFileWrite(0, 4); pimpl->mError = ""; for (size_t i = 0; i < pimpl->mExporters.size(); ++i) { const Exporter::ExportFormatEntry& exp = pimpl->mExporters[i]; if (!strcmp(exp.mDescription.id,pFormatId)) { try { // Always create a full copy of the scene. We might optimize this one day, // but for now it is the most pragmatic way. aiScene* scenecopy_tmp = nullptr; SceneCombiner::CopyScene(&scenecopy_tmp,pScene); pimpl->mProgressHandler->UpdateFileWrite(1, 4); std::unique_ptr<aiScene> scenecopy(scenecopy_tmp); const ScenePrivateData* const priv = ScenePriv(pScene); // steps that are not idempotent, i.e. we might need to run them again, usually to get back to the // original state before the step was applied first. When checking which steps we don't need // to run, those are excluded. const unsigned int nonIdempotentSteps = aiProcess_FlipWindingOrder | aiProcess_FlipUVs | aiProcess_MakeLeftHanded; // Erase all pp steps that were already applied to this scene const unsigned int pp = (exp.mEnforcePP | pPreprocessing) & ~(priv && !priv->mIsCopy ? (priv->mPPStepsApplied & ~nonIdempotentSteps) : 0u); // If no extra post-processing was specified, and we obtained this scene from an // Assimp importer, apply the reverse steps automatically. // TODO: either drop this, or document it. Otherwise it is just a bad surprise. //if (!pPreprocessing && priv) { // pp |= (nonIdempotentSteps & priv->mPPStepsApplied); //} // If the input scene is not in verbose format, but there is at least post-processing step that relies on it, // we need to run the MakeVerboseFormat step first. bool must_join_again = false; if (!is_verbose_format) { bool verbosify = false; for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) { BaseProcess* const p = pimpl->mPostProcessingSteps[a]; if (p->IsActive(pp) && p->RequireVerboseFormat()) { verbosify = true; break; } } if (verbosify || (exp.mEnforcePP & aiProcess_JoinIdenticalVertices)) { ASSIMP_LOG_DEBUG("export: Scene data not in verbose format, applying MakeVerboseFormat step first"); MakeVerboseFormatProcess proc; proc.Execute(scenecopy.get()); if(!(exp.mEnforcePP & aiProcess_JoinIdenticalVertices)) { must_join_again = true; } } } pimpl->mProgressHandler->UpdateFileWrite(2, 4); if (pp) { // the three 'conversion' steps need to be executed first because all other steps rely on the standard data layout { FlipWindingOrderProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } { FlipUVsProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } { MakeLeftHandedProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } bool exportPointCloud(false); if (nullptr != pProperties) { exportPointCloud = pProperties->GetPropertyBool(AI_CONFIG_EXPORT_POINT_CLOUDS); } // dispatch other processes for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) { BaseProcess* const p = pimpl->mPostProcessingSteps[a]; if (p->IsActive(pp) && !dynamic_cast<FlipUVsProcess*>(p) && !dynamic_cast<FlipWindingOrderProcess*>(p) && !dynamic_cast<MakeLeftHandedProcess*>(p)) { if (dynamic_cast<PretransformVertices*>(p) && exportPointCloud) { continue; } p->Execute(scenecopy.get()); } } ScenePrivateData* const privOut = ScenePriv(scenecopy.get()); ai_assert(nullptr != privOut); privOut->mPPStepsApplied |= pp; } pimpl->mProgressHandler->UpdateFileWrite(3, 4); if(must_join_again) { JoinVerticesProcess proc; proc.Execute(scenecopy.get()); } ExportProperties emptyProperties; // Never pass NULL ExportProperties so Exporters don't have to worry. exp.mExportFunction(pPath,pimpl->mIOSystem.get(),scenecopy.get(), pProperties ? pProperties : &emptyProperties); pimpl->mProgressHandler->UpdateFileWrite(4, 4); } catch (DeadlyExportError& err) { pimpl->mError = err.what(); return AI_FAILURE; } return AI_SUCCESS; } } pimpl->mError = std::string("Found no exporter to handle this file format: ") + pFormatId; ASSIMP_END_EXCEPTION_REGION(aiReturn); return AI_FAILURE; }
// ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. void COBImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { COB::Scene scene; std::unique_ptr<StreamReaderLE> stream(new StreamReaderLE( pIOHandler->Open(pFile,"rb")) ); // check header char head[32]; stream->CopyAndAdvance(head,32); if (strncmp(head,"Caligari ",9)) { ThrowException("Could not found magic id: `Caligari`"); } ASSIMP_LOG_INFO_F("File format tag: ",std::string(head+9,6)); if (head[16]!='L') { ThrowException("File is big-endian, which is not supported"); } // load data into intermediate structures if (head[15]=='A') { ReadAsciiFile(scene, stream.get()); } else { ReadBinaryFile(scene, stream.get()); } if(scene.nodes.empty()) { ThrowException("No nodes loaded"); } // sort faces by material indices for(std::shared_ptr< Node >& n : scene.nodes) { if (n->type == Node::TYPE_MESH) { Mesh& mesh = (Mesh&)(*n.get()); for(Face& f : mesh.faces) { mesh.temp_map[f.material].push_back(&f); } } } // count meshes for(std::shared_ptr< Node >& n : scene.nodes) { if (n->type == Node::TYPE_MESH) { Mesh& mesh = (Mesh&)(*n.get()); if (mesh.vertex_positions.size() && mesh.texture_coords.size()) { pScene->mNumMeshes += static_cast<unsigned int>(mesh.temp_map.size()); } } } pScene->mMeshes = new aiMesh*[pScene->mNumMeshes](); pScene->mMaterials = new aiMaterial*[pScene->mNumMeshes](); pScene->mNumMeshes = 0; // count lights and cameras for(std::shared_ptr< Node >& n : scene.nodes) { if (n->type == Node::TYPE_LIGHT) { ++pScene->mNumLights; } else if (n->type == Node::TYPE_CAMERA) { ++pScene->mNumCameras; } } if (pScene->mNumLights) { pScene->mLights = new aiLight*[pScene->mNumLights](); } if (pScene->mNumCameras) { pScene->mCameras = new aiCamera*[pScene->mNumCameras](); } pScene->mNumLights = pScene->mNumCameras = 0; // resolve parents by their IDs and build the output graph std::unique_ptr<Node> root(new Group()); for(size_t n = 0; n < scene.nodes.size(); ++n) { const Node& nn = *scene.nodes[n].get(); if(nn.parent_id==0) { root->temp_children.push_back(&nn); } for(size_t m = n; m < scene.nodes.size(); ++m) { const Node& mm = *scene.nodes[m].get(); if (mm.parent_id == nn.id) { nn.temp_children.push_back(&mm); } } } pScene->mRootNode = BuildNodes(*root.get(),scene,pScene); //flip normals after import FlipWindingOrderProcess flip; flip.Execute( pScene ); }
// ------------------------------------------------------------------------------------------------ aiReturn Exporter :: Export( const aiScene* pScene, const char* pFormatId, const char* pPath, unsigned int pPreprocessing ) { ASSIMP_BEGIN_EXCEPTION_REGION(); pimpl->mError = ""; for (size_t i = 0; i < pimpl->mExporters.size(); ++i) { const Exporter::ExportFormatEntry& exp = pimpl->mExporters[i]; if (!strcmp(exp.mDescription.id,pFormatId)) { try { // Always create a full copy of the scene. We might optimize this one day, // but for now it is the most pragmatic way. aiScene* scenecopy_tmp; SceneCombiner::CopyScene(&scenecopy_tmp,pScene); std::auto_ptr<aiScene> scenecopy(scenecopy_tmp); const ScenePrivateData* const priv = ScenePriv(pScene); // steps that are not idempotent, i.e. we might need to run them again, usually to get back to the // original state before the step was applied first. When checking which steps we don't need // to run, those are excluded. const unsigned int nonIdempotentSteps = aiProcess_FlipWindingOrder | aiProcess_FlipUVs | aiProcess_MakeLeftHanded; // Erase all pp steps that were already applied to this scene unsigned int pp = (exp.mEnforcePP | pPreprocessing) & ~(priv ? (priv->mPPStepsApplied & ~nonIdempotentSteps) : 0u); // If no extra postprocessing was specified, and we obtained this scene from an // Assimp importer, apply the reverse steps automatically. if (!pPreprocessing && priv) { pp |= (nonIdempotentSteps & priv->mPPStepsApplied); } // If the input scene is not in verbose format, but there is at least postprocessing step that relies on it, // we need to run the MakeVerboseFormat step first. if (scenecopy->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) { bool verbosify = false; for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) { BaseProcess* const p = pimpl->mPostProcessingSteps[a]; if (p->IsActive(pp) && p->RequireVerboseFormat()) { verbosify = true; break; } } if (verbosify || (exp.mEnforcePP & aiProcess_JoinIdenticalVertices)) { DefaultLogger::get()->debug("export: Scene data not in verbose format, applying MakeVerboseFormat step first"); MakeVerboseFormatProcess proc; proc.Execute(scenecopy.get()); } } if (pp) { // the three 'conversion' steps need to be executed first because all other steps rely on the standard data layout { FlipWindingOrderProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } { FlipUVsProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } { MakeLeftHandedProcess step; if (step.IsActive(pp)) { step.Execute(scenecopy.get()); } } // dispatch other processes for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) { BaseProcess* const p = pimpl->mPostProcessingSteps[a]; if (p->IsActive(pp) && !dynamic_cast<FlipUVsProcess*>(p) && !dynamic_cast<FlipWindingOrderProcess*>(p) && !dynamic_cast<MakeLeftHandedProcess*>(p)) { p->Execute(scenecopy.get()); } } ScenePrivateData* const privOut = ScenePriv(scenecopy.get()); ai_assert(privOut); privOut->mPPStepsApplied |= pp; } exp.mExportFunction(pPath,pimpl->mIOSystem.get(),scenecopy.get()); } catch (DeadlyExportError& err) { pimpl->mError = err.what(); return AI_FAILURE; } return AI_SUCCESS; } } pimpl->mError = std::string("Found no exporter to handle this file format: ") + pFormatId; ASSIMP_END_EXCEPTION_REGION(aiReturn); return AI_FAILURE; }
// ------------------------------------------------------------------------------------------------ // Constructs the return data structure out of the imported data. void XFileImporter::CreateDataRepresentationFromImport( aiScene* pScene, XFile::Scene* pData) { // Read the global materials first so that meshes referring to them can find them later ConvertMaterials( pScene, pData->mGlobalMaterials); // copy nodes, extracting meshes and materials on the way pScene->mRootNode = CreateNodes( pScene, NULL, pData->mRootNode); // extract animations CreateAnimations( pScene, pData); // read the global meshes that were stored outside of any node if( pData->mGlobalMeshes.size() > 0) { // create a root node to hold them if there isn't any, yet if( pScene->mRootNode == NULL) { pScene->mRootNode = new aiNode; pScene->mRootNode->mName.Set( "$dummy_node"); } // convert all global meshes and store them in the root node. // If there was one before, the global meshes now suddenly have its transformation matrix... // Don't know what to do there, I don't want to insert another node under the present root node // just to avoid this. CreateMeshes( pScene, pScene->mRootNode, pData->mGlobalMeshes); } if (!pScene->mRootNode) { throw DeadlyImportError( "No root node" ); } // Convert everything to OpenGL space... it's the same operation as the conversion back, so we can reuse the step directly MakeLeftHandedProcess convertProcess; convertProcess.Execute( pScene); FlipWindingOrderProcess flipper; flipper.Execute(pScene); // finally: create a dummy material if not material was imported if( pScene->mNumMaterials == 0) { pScene->mNumMaterials = 1; // create the Material aiMaterial* mat = new aiMaterial; int shadeMode = (int) aiShadingMode_Gouraud; mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL); // material colours int specExp = 1; aiColor3D clr = aiColor3D( 0, 0, 0); mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_EMISSIVE); mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_SPECULAR); clr = aiColor3D( 0.5f, 0.5f, 0.5f); mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_DIFFUSE); mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS); pScene->mMaterials = new aiMaterial*[1]; pScene->mMaterials[0] = mat; } }