LWOLoader.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the LWO importer class */
  35. #include "AssimpPCH.h"
  36. // internal headers
  37. #include "LWOLoader.h"
  38. #include "MaterialSystem.h"
  39. #include "StringComparison.h"
  40. #include "SGSpatialSort.h"
  41. #include "ByteSwap.h"
  42. #include "ProcessHelper.h"
  43. using namespace Assimp;
  44. // ------------------------------------------------------------------------------------------------
  45. // Constructor to be privately used by Importer
  46. LWOImporter::LWOImporter()
  47. {
  48. }
  49. // ------------------------------------------------------------------------------------------------
  50. // Destructor, private as well
  51. LWOImporter::~LWOImporter()
  52. {
  53. }
  54. // ------------------------------------------------------------------------------------------------
  55. // Returns whether the class can handle the format of the given file.
  56. bool LWOImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  57. {
  58. // simple check of file extension is enough for the moment
  59. std::string::size_type pos = pFile.find_last_of('.');
  60. // no file extension - can't read
  61. if( pos == std::string::npos)return false;
  62. std::string extension = pFile.substr( pos);
  63. if (extension.length() < 4)return false;
  64. if (extension[0] != '.')return false;
  65. if (extension[1] != 'l' && extension[1] != 'L')return false;
  66. if (extension[2] != 'w' && extension[2] != 'W')return false;
  67. if (extension[3] != 'o' && extension[3] != 'O')return false;
  68. return true;
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Setup configuration properties
  72. void LWOImporter::SetupProperties(const Importer* pImp)
  73. {
  74. configSpeedFlag = ( 0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0) ? true : false);
  75. configLayerIndex = pImp->GetPropertyInteger (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,0xffffffff);
  76. configLayerName = pImp->GetPropertyString (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,"");
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Imports the given file into the given scene structure.
  80. void LWOImporter::InternReadFile( const std::string& pFile,
  81. aiScene* pScene,
  82. IOSystem* pIOHandler)
  83. {
  84. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  85. // Check whether we can read from the file
  86. if( file.get() == NULL)
  87. throw new ImportErrorException( "Failed to open LWO file " + pFile + ".");
  88. if((this->fileSize = (unsigned int)file->FileSize()) < 12)
  89. throw new ImportErrorException("LWO: The file is too small to contain the IFF header");
  90. // allocate storage and copy the contents of the file to a memory buffer
  91. std::vector< uint8_t > mBuffer(fileSize);
  92. file->Read( &mBuffer[0], 1, fileSize);
  93. this->pScene = pScene;
  94. // determine the type of the file
  95. uint32_t fileType;
  96. const char* sz = IFF::ReadHeader(&mBuffer[0],fileType);
  97. if (sz)throw new ImportErrorException(sz);
  98. mFileBuffer = &mBuffer[0] + 12;
  99. fileSize -= 12;
  100. // create temporary storage on the stack but store pointers to it in the class
  101. // instance. Therefore everything will be destructed properly if an exception
  102. // is thrown and we needn't take care of that.
  103. LayerList _mLayers;
  104. mLayers = &_mLayers;
  105. TagList _mTags;
  106. mTags = &_mTags;
  107. TagMappingTable _mMapping;
  108. mMapping = &_mMapping;
  109. SurfaceList _mSurfaces;
  110. mSurfaces = &_mSurfaces;
  111. // allocate a default layer
  112. mLayers->push_back(Layer());
  113. mCurLayer = &mLayers->back();
  114. mCurLayer->mName = "<LWODefault>";
  115. // old lightwave file format (prior to v6)
  116. if (AI_LWO_FOURCC_LWOB == fileType)
  117. {
  118. mIsLWO2 = false;
  119. this->LoadLWOBFile();
  120. }
  121. // new lightwave format
  122. else if (AI_LWO_FOURCC_LWO2 == fileType)
  123. {
  124. mIsLWO2 = true;
  125. this->LoadLWO2File();
  126. }
  127. // we don't know this format
  128. else
  129. {
  130. char szBuff[5];
  131. szBuff[0] = (char)(fileType >> 24u);
  132. szBuff[1] = (char)(fileType >> 16u);
  133. szBuff[2] = (char)(fileType >> 8u);
  134. szBuff[3] = (char)(fileType);
  135. throw new ImportErrorException(std::string("Unknown LWO sub format: ") + szBuff);
  136. }
  137. // now, as we have loaded all data, we can resolve cross-referenced tags and clips
  138. ResolveTags();
  139. ResolveClips();
  140. // now process all layers and build meshes and nodes
  141. std::vector<aiMesh*> apcMeshes;
  142. std::vector<aiNode*> apcNodes;
  143. apcNodes.reserve(mLayers->size());
  144. apcMeshes.reserve(mLayers->size()*std::min(((unsigned int)mSurfaces->size()/2u), 1u));
  145. unsigned int iDefaultSurface = 0xffffffff; // index of the default surface
  146. for (LayerList::iterator lit = mLayers->begin(), lend = mLayers->end();
  147. lit != lend;++lit)
  148. {
  149. LWO::Layer& layer = *lit;
  150. // I don't know whether there could be dummy layers, but it would be possible
  151. const unsigned int meshStart = (unsigned int)apcMeshes.size();
  152. if (!layer.mFaces.empty() && !layer.mTempPoints.empty())
  153. {
  154. // now sort all faces by the surfaces assigned to them
  155. typedef std::vector<unsigned int> SortedRep;
  156. std::vector<SortedRep> pSorted(mSurfaces->size()+1);
  157. unsigned int i = 0;
  158. for (FaceList::iterator it = layer.mFaces.begin(), end = layer.mFaces.end();
  159. it != end;++it,++i)
  160. {
  161. unsigned int idx = (*it).surfaceIndex;
  162. if (idx >= mTags->size())
  163. {
  164. DefaultLogger::get()->warn("LWO: Invalid face surface index");
  165. idx = 0xffffffff;
  166. }
  167. if(0xffffffff == idx || 0xffffffff == (idx = _mMapping[idx]))
  168. {
  169. if (0xffffffff == iDefaultSurface)
  170. {
  171. iDefaultSurface = (unsigned int)mSurfaces->size();
  172. mSurfaces->push_back(LWO::Surface());
  173. LWO::Surface& surf = mSurfaces->back();
  174. surf.mColor.r = surf.mColor.g = surf.mColor.b = 0.6f;
  175. }
  176. idx = iDefaultSurface;
  177. }
  178. pSorted[idx].push_back(i);
  179. }
  180. if (0xffffffff == iDefaultSurface)pSorted.erase(pSorted.end()-1);
  181. // now generate output meshes
  182. for (unsigned int p = 0; p < mSurfaces->size();++p)
  183. if (!pSorted[p].empty())pScene->mNumMeshes++;
  184. if (!pScene->mNumMeshes)
  185. throw new ImportErrorException("LWO: There are no meshes");
  186. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  187. for (unsigned int p = 0,i = 0;i < mSurfaces->size();++i)
  188. {
  189. SortedRep& sorted = pSorted[i];
  190. if (sorted.empty())continue;
  191. // generate the mesh
  192. aiMesh* mesh = new aiMesh();
  193. apcMeshes.push_back(mesh);
  194. mesh->mNumFaces = (unsigned int)sorted.size();
  195. // count the number of vertices
  196. SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  197. for (;it != end;++it)
  198. {
  199. mesh->mNumVertices += layer.mFaces[*it].mNumIndices;
  200. }
  201. aiVector3D* pv = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  202. aiFace* pf = mesh->mFaces = new aiFace[mesh->mNumFaces];
  203. mesh->mMaterialIndex = i;
  204. // find out which vertex color channels and which texture coordinate
  205. // channels are really required by the material attached to this mesh
  206. unsigned int vUVChannelIndices[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  207. unsigned int vVColorIndices[AI_MAX_NUMBER_OF_COLOR_SETS];
  208. #if _DEBUG
  209. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  210. vUVChannelIndices[mui] = 0xffffffff;
  211. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui )
  212. vVColorIndices[mui] = 0xffffffff;
  213. #endif
  214. FindUVChannels(_mSurfaces[i],layer,vUVChannelIndices);
  215. FindVCChannels(_mSurfaces[i],layer,vVColorIndices);
  216. // allocate storage for UV and CV channels
  217. aiVector3D* pvUV[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  218. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  219. {
  220. if (0xffffffff == vUVChannelIndices[mui])break;
  221. pvUV[mui] = mesh->mTextureCoords[mui] = new aiVector3D[mesh->mNumVertices];
  222. // LightWave doesn't support more than 2 UV components
  223. mesh->mNumUVComponents[0] = 2;
  224. }
  225. aiColor4D* pvVC[AI_MAX_NUMBER_OF_COLOR_SETS];
  226. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui)
  227. {
  228. if (0xffffffff == vVColorIndices[mui])break;
  229. pvVC[mui] = mesh->mColors[mui] = new aiColor4D[mesh->mNumVertices];
  230. }
  231. // we would not need this extra array, but the code is much cleaner if we use it
  232. // FIX: we can use the referrer ID array here. invalidate its contents
  233. // before we resize it to avoid a unnecessary memcpy
  234. std::vector<unsigned int>& smoothingGroups = layer.mPointReferrers;
  235. smoothingGroups.erase (smoothingGroups.begin(),smoothingGroups.end());
  236. smoothingGroups.resize(mesh->mNumFaces,0);
  237. // now convert all faces
  238. unsigned int vert = 0;
  239. std::vector<unsigned int>::iterator outIt = smoothingGroups.begin();
  240. for (it = sorted.begin(); it != end;++it,++outIt)
  241. {
  242. const LWO::Face& face = layer.mFaces[*it];
  243. *outIt = face.smoothGroup;
  244. // copy all vertices
  245. for (unsigned int q = 0; q < face.mNumIndices;++q)
  246. {
  247. register unsigned int idx = face.mIndices[q];
  248. *pv = layer.mTempPoints[idx] + layer.mPivot;
  249. pv->z *= -1.0f; // DX to OGL
  250. pv++;
  251. // process UV coordinates
  252. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_TEXTURECOORDS;++w)
  253. {
  254. if (0xffffffff == vUVChannelIndices[w])break;
  255. aiVector3D*& pp = pvUV[w];
  256. const aiVector2D& src = ((aiVector2D*)&layer.mUVChannels[vUVChannelIndices[w]].rawData[0])[idx];
  257. pp->x = src.x;
  258. pp->y = 1.f-src.y; // DX to OGL
  259. pp++;
  260. }
  261. // process vertex colors
  262. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_COLOR_SETS;++w)
  263. {
  264. if (0xffffffff == vVColorIndices[w])break;
  265. *(pvVC[w])++ = ((aiColor4D*)&layer.mVColorChannels[vVColorIndices[w]].rawData[0])[idx];
  266. }
  267. #if 0
  268. // process vertex weights - not yet supported
  269. for (unsigned int w = 0; w < layer.mWeightChannels.size();++w)
  270. {
  271. }
  272. #endif
  273. face.mIndices[q] = vert + (face.mNumIndices-q-1);
  274. }
  275. vert += face.mNumIndices;
  276. pf->mIndices = face.mIndices;
  277. pf->mNumIndices = face.mNumIndices;
  278. unsigned int** p = (unsigned int**)&face.mIndices;*p = NULL; // make sure it won't be deleted
  279. pf++;
  280. }
  281. // compute normal vectors for the mesh - we can't use our GenSmoothNormal-Step here
  282. // since it wouldn't handle smoothing groups correctly
  283. ComputeNormals(mesh,smoothingGroups,_mSurfaces[i]);
  284. ++p;
  285. }
  286. }
  287. // generate nodes to render the mesh. Store the parent index
  288. // in the mParent member of the nodes
  289. aiNode* pcNode = new aiNode();
  290. apcNodes.push_back(pcNode);
  291. pcNode->mName.Set(layer.mName);
  292. pcNode->mParent = (aiNode*)(uintptr_t)(layer.mParent);
  293. pcNode->mNumMeshes = (unsigned int)apcMeshes.size() - meshStart;
  294. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  295. for (unsigned int p = 0; p < pcNode->mNumMeshes;++p)
  296. pcNode->mMeshes[p] = p + meshStart;
  297. }
  298. // the RemoveRedundantMaterials step will clean this up later
  299. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = (unsigned int)mSurfaces->size()];
  300. for (unsigned int mat = 0; mat < pScene->mNumMaterials;++mat)
  301. {
  302. MaterialHelper* pcMat = new MaterialHelper();
  303. pScene->mMaterials[mat] = pcMat;
  304. ConvertMaterial((*mSurfaces)[mat],pcMat);
  305. }
  306. // copy the meshes to the output structure
  307. if (apcMeshes.size()) // shouldn't occur, just to be sure we don't crash
  308. {
  309. pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes = (unsigned int)apcMeshes.size() ];
  310. ::memcpy(pScene->mMeshes,&apcMeshes[0],pScene->mNumMeshes*sizeof(void*));
  311. }
  312. // generate the final node graph
  313. GenerateNodeGraph(apcNodes);
  314. }
  315. // ------------------------------------------------------------------------------------------------
  316. void LWOImporter::ComputeNormals(aiMesh* mesh, const std::vector<unsigned int>& smoothingGroups,
  317. const LWO::Surface& surface)
  318. {
  319. // allocate output storage
  320. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  321. // First generate per-face normals
  322. aiVector3D* out;
  323. std::vector<aiVector3D> faceNormals;
  324. if (!surface.mMaximumSmoothAngle)
  325. out = mesh->mNormals;
  326. else
  327. {
  328. faceNormals.resize(mesh->mNumVertices);
  329. out = &faceNormals[0];
  330. }
  331. aiFace* begin = mesh->mFaces, *const end = mesh->mFaces+mesh->mNumFaces;
  332. for (; begin != end; ++begin)
  333. {
  334. aiFace& face = *begin;
  335. // LWO doc: "the normal is defined as the cross product of the first and last edges"
  336. aiVector3D* pV1 = mesh->mVertices + face.mIndices[0];
  337. aiVector3D* pV2 = mesh->mVertices + face.mIndices[1];
  338. aiVector3D* pV3 = mesh->mVertices + face.mIndices[face.mNumIndices-1];
  339. aiVector3D vNor = ((*pV2 - *pV1) ^ (*pV3 - *pV1)).Normalize();
  340. for (unsigned int i = 0; i < face.mNumIndices;++i)
  341. out[face.mIndices[i]] = vNor;
  342. }
  343. if (!surface.mMaximumSmoothAngle)return;
  344. const float posEpsilon = ComputePositionEpsilon(mesh);
  345. // now generate the spatial sort tree
  346. SGSpatialSort sSort;
  347. std::vector<unsigned int>::const_iterator it = smoothingGroups.begin();
  348. for( begin = mesh->mFaces; begin != end; ++begin, ++it)
  349. {
  350. aiFace& face = *begin;
  351. for (unsigned int i = 0; i < face.mNumIndices;++i)
  352. {
  353. register unsigned int tt = face.mIndices[i];
  354. sSort.Add(mesh->mVertices[tt],tt,*it);
  355. }
  356. }
  357. // sort everything - this takes O(nlogn) time
  358. sSort.Prepare();
  359. std::vector<unsigned int> poResult;
  360. poResult.reserve(20);
  361. // generate vertex normals. We have O(logn) for the binary lookup, which we need
  362. // for n elements, thus the EXPECTED complexity is O(nlogn)
  363. if (surface.mMaximumSmoothAngle < 3.f && !configSpeedFlag)
  364. {
  365. const float fLimit = cos(surface.mMaximumSmoothAngle);
  366. for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it)
  367. {
  368. register unsigned int sg = *it;
  369. aiFace& face = *begin;
  370. unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
  371. for (; beginIdx != endIdx; ++beginIdx)
  372. {
  373. register unsigned int idx = *beginIdx;
  374. sSort.FindPositions(mesh->mVertices[idx],sg,posEpsilon,poResult,true);
  375. std::vector<unsigned int>::const_iterator a, end = poResult.end();
  376. aiVector3D vNormals;
  377. for (a = poResult.begin();a != end;++a)
  378. {
  379. const aiVector3D& v = faceNormals[*a];
  380. if (v * faceNormals[idx] < fLimit)continue;
  381. vNormals += v;
  382. }
  383. vNormals.Normalize();
  384. mesh->mNormals[idx] = vNormals;
  385. }
  386. }
  387. }
  388. else // faster code path in case there is no smooth angle
  389. {
  390. std::vector<bool> vertexDone(mesh->mNumVertices,false);
  391. for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it)
  392. {
  393. register unsigned int sg = *it;
  394. aiFace& face = *begin;
  395. unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
  396. for (; beginIdx != endIdx; ++beginIdx)
  397. {
  398. register unsigned int idx = *beginIdx;
  399. if (vertexDone[idx])continue;
  400. sSort.FindPositions(mesh->mVertices[idx],sg,posEpsilon,poResult,true);
  401. std::vector<unsigned int>::const_iterator a, end = poResult.end();
  402. aiVector3D vNormals;
  403. for (a = poResult.begin();a != end;++a)
  404. {
  405. const aiVector3D& v = faceNormals[*a];
  406. vNormals += v;
  407. }
  408. vNormals.Normalize();
  409. for (a = poResult.begin();a != end;++a)
  410. {
  411. mesh->mNormals[*a] = vNormals;
  412. vertexDone[*a] = true;
  413. }
  414. }
  415. }
  416. }
  417. }
  418. // ------------------------------------------------------------------------------------------------
  419. void LWOImporter::AddChildren(aiNode* node, uintptr_t parent, std::vector<aiNode*>& apcNodes)
  420. {
  421. for (uintptr_t i = 0; i < (uintptr_t)apcNodes.size();++i)
  422. {
  423. if (i == parent)continue;
  424. if (apcNodes[i] && (uintptr_t)apcNodes[i]->mParent == parent)++node->mNumChildren;
  425. }
  426. if (node->mNumChildren)
  427. {
  428. node->mChildren = new aiNode* [ node->mNumChildren ];
  429. for (uintptr_t i = 0, p = 0; i < (uintptr_t)apcNodes.size();++i)
  430. {
  431. if (i == parent)continue;
  432. if (apcNodes[i] && parent == (uintptr_t)(apcNodes[i]->mParent))
  433. {
  434. node->mChildren[p++] = apcNodes[i];
  435. apcNodes[i]->mParent = node;
  436. // recursively add more children
  437. AddChildren(apcNodes[i],i,apcNodes);
  438. apcNodes[i] = NULL;
  439. }
  440. }
  441. }
  442. }
  443. // ------------------------------------------------------------------------------------------------
  444. void LWOImporter::GenerateNodeGraph(std::vector<aiNode*>& apcNodes)
  445. {
  446. // now generate the final nodegraph - generate a root node
  447. pScene->mRootNode = new aiNode();
  448. pScene->mRootNode->mName.Set("<LWORoot>");
  449. AddChildren(pScene->mRootNode,0,apcNodes);
  450. unsigned int extra = 0;
  451. for (unsigned int i = 0; i < apcNodes.size();++i)
  452. if (apcNodes[i] && apcNodes[i]->mNumMeshes)++extra;
  453. if (extra)
  454. {
  455. // we need to add extra nodes to the root
  456. const unsigned int newSize = extra + pScene->mRootNode->mNumChildren;
  457. aiNode** const apcNewNodes = new aiNode*[newSize];
  458. if((extra = pScene->mRootNode->mNumChildren))
  459. ::memcpy(apcNewNodes,pScene->mRootNode->mChildren,extra*sizeof(void*));
  460. aiNode** cc = apcNewNodes+extra;
  461. for (unsigned int i = 0; i < apcNodes.size();++i)
  462. {
  463. if (apcNodes[i] && apcNodes[i]->mNumMeshes)
  464. {
  465. *cc++ = apcNodes[i];
  466. apcNodes[i]->mParent = pScene->mRootNode;
  467. // recursively add more children
  468. AddChildren(apcNodes[i],i,apcNodes);
  469. apcNodes[i] = NULL;
  470. }
  471. }
  472. delete[] pScene->mRootNode->mChildren;
  473. pScene->mRootNode->mChildren = apcNewNodes;
  474. pScene->mRootNode->mNumChildren = newSize;
  475. }
  476. if (!pScene->mRootNode->mNumChildren)throw new ImportErrorException("LWO: Unable to build a valid node graph");
  477. // remove a single root node
  478. // TODO: implement directly in the above loop, no need to deallocate here
  479. if (1 == pScene->mRootNode->mNumChildren)
  480. {
  481. aiNode* pc = pScene->mRootNode->mChildren[0];
  482. pc->mParent = pScene->mRootNode->mChildren[0] = NULL;
  483. delete pScene->mRootNode;
  484. pScene->mRootNode = pc;
  485. }
  486. }
  487. // ------------------------------------------------------------------------------------------------
  488. void LWOImporter::ResolveTags()
  489. {
  490. // --- this function is used for both LWO2 and LWOB
  491. mMapping->resize(mTags->size(),0xffffffff);
  492. for (unsigned int a = 0; a < mTags->size();++a)
  493. {
  494. for (unsigned int i = 0; i < mSurfaces->size();++i)
  495. {
  496. const std::string& c = (*mTags)[a];
  497. const std::string& d = (*mSurfaces)[i].mName;
  498. if (!ASSIMP_stricmp(c,d))
  499. {
  500. (*mMapping)[a] = i;
  501. break;
  502. }
  503. }
  504. }
  505. }
  506. // ------------------------------------------------------------------------------------------------
  507. void LWOImporter::ResolveClips()
  508. {
  509. for( unsigned int i = 0; i < mClips.size();++i)
  510. {
  511. Clip& clip = mClips[i];
  512. if (Clip::REF == clip.type)
  513. {
  514. if (clip.clipRef >= mClips.size())
  515. {
  516. DefaultLogger::get()->error("LWO2: Clip referrer index is out of range");
  517. clip.clipRef = 0;
  518. }
  519. Clip& dest = mClips[clip.clipRef];
  520. if (Clip::REF == dest.type)
  521. {
  522. DefaultLogger::get()->error("LWO2: Clip references another clip reference");
  523. clip.type = Clip::UNSUPPORTED;
  524. }
  525. else
  526. {
  527. clip.path = dest.path;
  528. clip.type = dest.type;
  529. }
  530. }
  531. }
  532. }
  533. // ------------------------------------------------------------------------------------------------
  534. void LWOImporter::AdjustTexturePath(std::string& out)
  535. {
  536. // --- this function is used for both LWO2 and LWOB
  537. if (!mIsLWO2 && ::strstr(out.c_str(), "(sequence)"))
  538. {
  539. // remove the (sequence) and append 000
  540. DefaultLogger::get()->info("LWOB: Sequence of animated texture found. It will be ignored");
  541. out = out.substr(0,out.length()-10) + "000";
  542. }
  543. // format: drive:path/file - we need to insert a slash after the drive
  544. std::string::size_type n = out.find_first_of(':');
  545. if (std::string::npos != n)
  546. {
  547. out.insert(n+1,"/");
  548. }
  549. }
  550. // ------------------------------------------------------------------------------------------------
  551. void LWOImporter::LoadLWOTags(unsigned int size)
  552. {
  553. // --- this function is used for both LWO2 and LWOB
  554. const char* szCur = (const char*)mFileBuffer, *szLast = szCur;
  555. const char* const szEnd = szLast+size;
  556. while (szCur < szEnd)
  557. {
  558. if (!(*szCur))
  559. {
  560. const unsigned int len = (unsigned int)(szCur-szLast);
  561. mTags->push_back(std::string(szLast,len));
  562. szCur += len & 1;
  563. szLast = szCur;
  564. }
  565. szCur++;
  566. }
  567. }
  568. // ------------------------------------------------------------------------------------------------
  569. void LWOImporter::LoadLWOPoints(unsigned int length)
  570. {
  571. // --- this function is used for both LWO2 and LWOB but for
  572. // LWO2 we need to allocate 25% more storage - it could be we'll
  573. // need to duplicate some points later.
  574. register unsigned int regularSize = (unsigned int)mCurLayer->mTempPoints.size() + length / 12;
  575. if (mIsLWO2)
  576. {
  577. mCurLayer->mTempPoints.reserve ( regularSize + (regularSize>>2u) );
  578. mCurLayer->mTempPoints.resize ( regularSize );
  579. // initialize all point referrers with the default values
  580. mCurLayer->mPointReferrers.reserve ( regularSize + (regularSize>>2u) );
  581. mCurLayer->mPointReferrers.resize ( regularSize, 0xffffffff );
  582. }
  583. else mCurLayer->mTempPoints.resize( regularSize );
  584. // perform endianess conversions
  585. #ifndef AI_BUILD_BIG_ENDIAN
  586. for (unsigned int i = 0; i < length>>2;++i)
  587. ByteSwap::Swap4( mFileBuffer + (i << 2));
  588. #endif
  589. ::memcpy(&mCurLayer->mTempPoints[0],mFileBuffer,length);
  590. }
  591. // ------------------------------------------------------------------------------------------------
  592. void LWOImporter::LoadLWO2Polygons(unsigned int length)
  593. {
  594. LE_NCONST uint16_t* const end = (LE_NCONST uint16_t*)(mFileBuffer+length);
  595. uint32_t type = GetU4();
  596. if (type != AI_LWO_FACE)
  597. {
  598. DefaultLogger::get()->warn("LWO2: Only POLS.FACE chunks are supported.");
  599. return;
  600. }
  601. // first find out how many faces and vertices we'll finally need
  602. uint16_t* cursor = (uint16_t*)mFileBuffer;
  603. unsigned int iNumFaces = 0,iNumVertices = 0;
  604. CountVertsAndFacesLWO2(iNumVertices,iNumFaces,cursor,end);
  605. // allocate the output array and copy face indices
  606. if (iNumFaces)
  607. {
  608. cursor = (uint16_t*)mFileBuffer;
  609. mCurLayer->mFaces.resize(iNumFaces);
  610. FaceList::iterator it = mCurLayer->mFaces.begin();
  611. CopyFaceIndicesLWO2(it,cursor,end);
  612. }
  613. }
  614. // ------------------------------------------------------------------------------------------------
  615. void LWOImporter::CountVertsAndFacesLWO2(unsigned int& verts, unsigned int& faces,
  616. uint16_t*& cursor, const uint16_t* const end, unsigned int max)
  617. {
  618. while (cursor < end && max--)
  619. {
  620. AI_LSWAP2P(cursor);
  621. uint16_t numIndices = *cursor++;
  622. numIndices &= 0x03FF;
  623. verts += numIndices;++faces;
  624. for(uint16_t i = 0; i < numIndices; i++)
  625. ReadVSizedIntLWO2((uint8_t*&)cursor);
  626. }
  627. }
  628. // ------------------------------------------------------------------------------------------------
  629. void LWOImporter::CopyFaceIndicesLWO2(FaceList::iterator& it,
  630. uint16_t*& cursor,
  631. const uint16_t* const end)
  632. {
  633. while (cursor < end)
  634. {
  635. LWO::Face& face = *it;++it;
  636. if((face.mNumIndices = (*cursor++) & 0x03FF)) // swapping has already been done
  637. {
  638. face.mIndices = new unsigned int[face.mNumIndices];
  639. for(unsigned int i = 0; i < face.mNumIndices; i++)
  640. {
  641. face.mIndices[i] = ReadVSizedIntLWO2((uint8_t*&)cursor) + mCurLayer->mPointIDXOfs;
  642. if(face.mIndices[i] > mCurLayer->mTempPoints.size())
  643. {
  644. DefaultLogger::get()->warn("LWO2: face index is out of range");
  645. face.mIndices[i] = (unsigned int)mCurLayer->mTempPoints.size()-1;
  646. }
  647. }
  648. }
  649. else DefaultLogger::get()->warn("LWO2: face has 0 indices");
  650. }
  651. }
  652. // ------------------------------------------------------------------------------------------------
  653. void LWOImporter::LoadLWO2PolygonTags(unsigned int length)
  654. {
  655. LE_NCONST uint8_t* const end = mFileBuffer+length;
  656. AI_LWO_VALIDATE_CHUNK_LENGTH(length,PTAG,4);
  657. uint32_t type = GetU4();
  658. if (type != AI_LWO_SURF && type != AI_LWO_SMGP)
  659. return;
  660. while (mFileBuffer < end)
  661. {
  662. unsigned int i = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  663. unsigned int j = GetU2();
  664. if (i >= mCurLayer->mFaces.size())
  665. {
  666. DefaultLogger::get()->warn("LWO2: face index in PTAG is out of range");
  667. continue;
  668. }
  669. switch (type)
  670. {
  671. case AI_LWO_SURF:
  672. mCurLayer->mFaces[i].surfaceIndex = j;
  673. break;
  674. case AI_LWO_SMGP:
  675. mCurLayer->mFaces[i].smoothGroup = j;
  676. break;
  677. };
  678. }
  679. }
  680. // ------------------------------------------------------------------------------------------------
  681. template <class T>
  682. VMapEntry* FindEntry(std::vector< T >& list,const std::string& name, bool perPoly)
  683. {
  684. for (typename std::vector< T >::iterator it = list.begin(), end = list.end();
  685. it != end; ++it)
  686. {
  687. if ((*it).name == name)
  688. {
  689. if (!perPoly)
  690. {
  691. DefaultLogger::get()->warn("LWO2: Found two VMAP sections with equal names");
  692. }
  693. return &(*it);
  694. }
  695. }
  696. list.push_back( T() );
  697. VMapEntry* p = &list.back();
  698. p->name = name;
  699. return p;
  700. }
  701. // ------------------------------------------------------------------------------------------------
  702. template <class T>
  703. void CreateNewEntry(std::vector< T >& list, unsigned int srcIdx)
  704. {
  705. for (typename std::vector< T >::iterator
  706. it = list.begin(), end = list.end();
  707. it != end;++it)
  708. {
  709. T& chan = *it;
  710. chan.abAssigned[srcIdx] = true;
  711. chan.abAssigned.resize(chan.abAssigned.size()+1,false);
  712. for (unsigned int a = 0; a < chan.dims;++a)
  713. chan.rawData.push_back(chan.rawData[srcIdx*chan.dims+a]);
  714. }
  715. }
  716. // ------------------------------------------------------------------------------------------------
  717. void LWOImporter::DoRecursiveVMAPAssignment(VMapEntry* base, unsigned int numRead,
  718. unsigned int idx, float* data)
  719. {
  720. ai_assert(NULL != data);
  721. LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
  722. unsigned int i;
  723. base->abAssigned[idx] = true;
  724. for (i = 0; i < numRead;++i)
  725. base->rawData[idx*base->dims+i]= data[i];
  726. if (0xffffffff != (i = refList[idx]))
  727. DoRecursiveVMAPAssignment(base,numRead,i,data);
  728. }
  729. // ------------------------------------------------------------------------------------------------
  730. void AddToSingleLinkedList(ReferrerList& refList, unsigned int srcIdx, unsigned int destIdx)
  731. {
  732. if(0xffffffff == refList[srcIdx])
  733. {
  734. refList[srcIdx] = destIdx;
  735. return;
  736. }
  737. AddToSingleLinkedList(refList,refList[srcIdx],destIdx);
  738. }
  739. // ------------------------------------------------------------------------------------------------
  740. void LWOImporter::LoadLWO2VertexMap(unsigned int length, bool perPoly)
  741. {
  742. LE_NCONST uint8_t* const end = mFileBuffer+length;
  743. AI_LWO_VALIDATE_CHUNK_LENGTH(length,VMAP,6);
  744. unsigned int type = GetU4();
  745. unsigned int dims = GetU2();
  746. VMapEntry* base;
  747. // read the name of the vertex map
  748. std::string name;
  749. GetS0(name,length);
  750. switch (type)
  751. {
  752. case AI_LWO_TXUV:
  753. if (dims != 2)
  754. {
  755. DefaultLogger::get()->warn("LWO2: Found UV channel with != 2 components");
  756. }
  757. base = FindEntry(mCurLayer->mUVChannels,name,perPoly);
  758. break;
  759. case AI_LWO_WGHT:
  760. if (dims != 1)
  761. {
  762. DefaultLogger::get()->warn("LWO2: found vertex weight map with != 1 components");
  763. }
  764. base = FindEntry(mCurLayer->mWeightChannels,name,perPoly);
  765. break;
  766. case AI_LWO_RGB:
  767. case AI_LWO_RGBA:
  768. if (dims != 3 && dims != 4)
  769. {
  770. DefaultLogger::get()->warn("LWO2: found vertex color map with != 3&4 components");
  771. }
  772. base = FindEntry(mCurLayer->mVColorChannels,name,perPoly);
  773. break;
  774. default: return;
  775. };
  776. base->Allocate((unsigned int)mCurLayer->mTempPoints.size());
  777. // now read all entries in the map
  778. type = std::min(dims,base->dims);
  779. const unsigned int diff = (dims - type)<<2;
  780. LWO::FaceList& list = mCurLayer->mFaces;
  781. LWO::PointList& pointList = mCurLayer->mTempPoints;
  782. LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
  783. float temp[4];
  784. const unsigned int numPoints = (unsigned int)pointList.size();
  785. const unsigned int numFaces = (unsigned int)list.size();
  786. while (mFileBuffer < end)
  787. {
  788. unsigned int idx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mPointIDXOfs;
  789. if (idx >= numPoints)
  790. {
  791. DefaultLogger::get()->warn("LWO2: vertex index in vmap/vmad is out of range");
  792. mFileBuffer += base->dims*4;continue;
  793. }
  794. if (perPoly)
  795. {
  796. unsigned int polyIdx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  797. if (base->abAssigned[idx])
  798. {
  799. // we have already a VMAP entry for this vertex - thus
  800. // we need to duplicate the corresponding polygon.
  801. if (polyIdx >= numFaces)
  802. {
  803. DefaultLogger::get()->warn("LWO2: VMAD polygon index is out of range");
  804. mFileBuffer += base->dims*4;continue;
  805. }
  806. LWO::Face& src = list[polyIdx];
  807. refList.resize(refList.size()+src.mNumIndices, 0xffffffff);
  808. // generate new vertex positions
  809. for (unsigned int i = 0; i < src.mNumIndices;++i)
  810. {
  811. register unsigned int srcIdx = src.mIndices[i];
  812. if (idx == srcIdx)
  813. {
  814. idx = (unsigned int)pointList.size();
  815. }
  816. src.mIndices[i] = (unsigned int)pointList.size();
  817. // store the index of the new vertex in the old vertex
  818. // so we get a single linked list we can traverse in
  819. // only one direction
  820. AddToSingleLinkedList(refList,srcIdx,src.mIndices[i]);
  821. pointList.push_back(pointList[srcIdx]);
  822. CreateNewEntry(mCurLayer->mVColorChannels, srcIdx );
  823. CreateNewEntry(mCurLayer->mUVChannels, srcIdx );
  824. CreateNewEntry(mCurLayer->mWeightChannels, srcIdx );
  825. }
  826. }
  827. }
  828. for (unsigned int l = 0; l < type;++l)
  829. temp[l] = GetF4();
  830. DoRecursiveVMAPAssignment(base,type,idx, temp);
  831. mFileBuffer += diff;
  832. }
  833. }
  834. // ------------------------------------------------------------------------------------------------
  835. void LWOImporter::LoadLWO2Clip(unsigned int length)
  836. {
  837. AI_LWO_VALIDATE_CHUNK_LENGTH(length,CLIP,10);
  838. mClips.push_back(LWO::Clip());
  839. LWO::Clip& clip = mClips.back();
  840. // first - get the index of the clip
  841. clip.idx = GetU4();
  842. IFF::SubChunkHeader* const head = IFF::LoadSubChunk(mFileBuffer);
  843. switch (head->type)
  844. {
  845. case AI_LWO_STIL:
  846. GetS0(clip.path,head->length);
  847. clip.type = Clip::STILL;
  848. break;
  849. case AI_LWO_ISEQ:
  850. {
  851. uint8_t digits = GetU1(); mFileBuffer++;
  852. int16_t offset = GetU2(); mFileBuffer+=4;
  853. int16_t start = GetU2(); mFileBuffer+=4;
  854. std::string s;std::stringstream ss;
  855. GetS0(s,head->length);
  856. head->length -= (unsigned int)s.length()+1;
  857. ss << s;
  858. ss << std::setw(digits) << offset + start;
  859. GetS0(s,head->length);
  860. ss << s;
  861. clip.path = ss.str();
  862. clip.type = Clip::SEQ;
  863. }
  864. break;
  865. case AI_LWO_STCC:
  866. DefaultLogger::get()->warn("LWO2: Color shifted images are not supported");
  867. break;
  868. case AI_LWO_ANIM:
  869. DefaultLogger::get()->warn("LWO2: Animated textures are not supported");
  870. break;
  871. case AI_LWO_XREF:
  872. clip.type = Clip::REF;
  873. clip.clipRef = GetU4();
  874. break;
  875. default:
  876. DefaultLogger::get()->warn("LWO2: Encountered unknown CLIP subchunk");
  877. }
  878. }
  879. // ------------------------------------------------------------------------------------------------
  880. void LWOImporter::LoadLWO2File()
  881. {
  882. LE_NCONST uint8_t* const end = mFileBuffer + fileSize;
  883. while (true)
  884. {
  885. if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break;
  886. IFF::ChunkHeader* const head = IFF::LoadChunk(mFileBuffer);
  887. if (mFileBuffer + head->length > end)
  888. {
  889. throw new ImportErrorException("LWO2: Chunk length points behind the file");
  890. break;
  891. }
  892. uint8_t* const next = mFileBuffer+head->length;
  893. unsigned int iUnnamed = 0;
  894. switch (head->type)
  895. {
  896. // new layer
  897. case AI_LWO_LAYR:
  898. {
  899. // add a new layer to the list ....
  900. mLayers->push_back ( LWO::Layer() );
  901. LWO::Layer& layer = mLayers->back();
  902. mCurLayer = &layer;
  903. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,LAYR,16);
  904. // and parse its properties, e.g. the pivot point
  905. mFileBuffer += 2;
  906. mCurLayer->mPivot.x = GetF4();
  907. mCurLayer->mPivot.y = GetF4();
  908. mCurLayer->mPivot.z = GetF4();
  909. mFileBuffer += 2;
  910. GetS0(layer.mName,head->length-16);
  911. // if the name is empty, generate a default name
  912. if (layer.mName.empty())
  913. {
  914. char buffer[128]; // should be sufficiently large
  915. ::sprintf(buffer,"Layer_%i", iUnnamed++);
  916. layer.mName = buffer;
  917. }
  918. if (mFileBuffer + 2 <= next)
  919. layer.mParent = GetU2();
  920. break;
  921. }
  922. // vertex list
  923. case AI_LWO_PNTS:
  924. {
  925. unsigned int old = (unsigned int)mCurLayer->mTempPoints.size();
  926. LoadLWOPoints(head->length);
  927. mCurLayer->mPointIDXOfs = old;
  928. break;
  929. }
  930. // vertex tags
  931. case AI_LWO_VMAD:
  932. if (mCurLayer->mFaces.empty())
  933. {
  934. DefaultLogger::get()->warn("LWO2: Unexpected VMAD chunk");
  935. break;
  936. }
  937. // --- intentionally no break here
  938. case AI_LWO_VMAP:
  939. {
  940. if (mCurLayer->mTempPoints.empty())
  941. DefaultLogger::get()->warn("LWO2: Unexpected VMAP chunk");
  942. else LoadLWO2VertexMap(head->length,head->type == AI_LWO_VMAD);
  943. break;
  944. }
  945. // face list
  946. case AI_LWO_POLS:
  947. {
  948. unsigned int old = (unsigned int)mCurLayer->mFaces.size();
  949. LoadLWO2Polygons(head->length);
  950. mCurLayer->mFaceIDXOfs = old;
  951. break;
  952. }
  953. // polygon tags
  954. case AI_LWO_PTAG:
  955. {
  956. if (mCurLayer->mFaces.empty())
  957. DefaultLogger::get()->warn("LWO2: Unexpected PTAG");
  958. else LoadLWO2PolygonTags(head->length);
  959. break;
  960. }
  961. // list of tags
  962. case AI_LWO_TAGS:
  963. {
  964. if (!mTags->empty())
  965. DefaultLogger::get()->warn("LWO2: SRFS chunk encountered twice");
  966. else LoadLWOTags(head->length);
  967. break;
  968. }
  969. // surface chunk
  970. case AI_LWO_SURF:
  971. {
  972. LoadLWO2Surface(head->length);
  973. break;
  974. }
  975. // clip chunk
  976. case AI_LWO_CLIP:
  977. {
  978. LoadLWO2Clip(head->length);
  979. break;
  980. }
  981. }
  982. mFileBuffer = next;
  983. }
  984. }