2
0

LWOLoader.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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. // internal headers
  36. #include "LWOLoader.h"
  37. #include "MaterialSystem.h"
  38. #include "StringComparison.h"
  39. #include "ByteSwap.h"
  40. // public assimp headers
  41. #include "../include/IOStream.h"
  42. #include "../include/IOSystem.h"
  43. #include "../include/aiScene.h"
  44. #include "../include/aiAssert.h"
  45. #include "../include/DefaultLogger.h"
  46. #include "../include/assimp.hpp"
  47. // boost headers
  48. #include <boost/scoped_ptr.hpp>
  49. using namespace Assimp;
  50. // ------------------------------------------------------------------------------------------------
  51. // Constructor to be privately used by Importer
  52. LWOImporter::LWOImporter()
  53. {
  54. }
  55. // ------------------------------------------------------------------------------------------------
  56. // Destructor, private as well
  57. LWOImporter::~LWOImporter()
  58. {
  59. }
  60. // ------------------------------------------------------------------------------------------------
  61. // Returns whether the class can handle the format of the given file.
  62. bool LWOImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  63. {
  64. // simple check of file extension is enough for the moment
  65. std::string::size_type pos = pFile.find_last_of('.');
  66. // no file extension - can't read
  67. if( pos == std::string::npos)return false;
  68. std::string extension = pFile.substr( pos);
  69. if (extension.length() < 4)return false;
  70. if (extension[0] != '.')return false;
  71. if (extension[1] != 'l' && extension[1] != 'L')return false;
  72. if (extension[2] != 'w' && extension[2] != 'W')return false;
  73. if (extension[3] != 'o' && extension[3] != 'O')return false;
  74. return true;
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Setup configuration properties
  78. void LWOImporter::SetupProperties(const Importer* pImp)
  79. {
  80. this->configGradientResX = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_LWO_GRADIENT_RESX,512);
  81. this->configGradientResY = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_LWO_GRADIENT_RESY,512);
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Imports the given file into the given scene structure.
  85. void LWOImporter::InternReadFile( const std::string& pFile,
  86. aiScene* pScene,
  87. IOSystem* pIOHandler)
  88. {
  89. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  90. // Check whether we can read from the file
  91. if( file.get() == NULL)
  92. throw new ImportErrorException( "Failed to open LWO file " + pFile + ".");
  93. if((this->fileSize = (unsigned int)file->FileSize()) < 12)
  94. throw new ImportErrorException("LWO: The file is too small to contain the IFF header");
  95. // allocate storage and copy the contents of the file to a memory buffer
  96. std::vector< uint8_t > mBuffer(fileSize);
  97. file->Read( &mBuffer[0], 1, fileSize);
  98. this->pScene = pScene;
  99. // determine the type of the file
  100. uint32_t fileType;
  101. const char* sz = IFF::ReadHeader(&mBuffer[0],fileType);
  102. if (sz)throw new ImportErrorException(sz);
  103. mFileBuffer = &mBuffer[0] + 12;
  104. fileSize -= 12;
  105. // create temporary storage on the stack but store pointers to it in the class
  106. // instance. Therefore everything will be destructed properly if an exception
  107. // is thrown and we needn't take care of that.
  108. LayerList _mLayers;
  109. mLayers = &_mLayers;
  110. TagList _mTags;
  111. mTags = &_mTags;
  112. TagMappingTable _mMapping;
  113. mMapping = &_mMapping;
  114. SurfaceList _mSurfaces;
  115. mSurfaces = &_mSurfaces;
  116. // allocate a default layer
  117. mLayers->push_back(Layer());
  118. mCurLayer = &mLayers->back();
  119. mCurLayer->mName = "<LWODefault>";
  120. // old lightwave file format (prior to v6)
  121. if (AI_LWO_FOURCC_LWOB == fileType)
  122. {
  123. mIsLWO2 = false;
  124. this->LoadLWOBFile();
  125. }
  126. // new lightwave format
  127. else if (AI_LWO_FOURCC_LWO2 == fileType)
  128. {
  129. mIsLWO2 = true;
  130. this->LoadLWO2File();
  131. }
  132. // we don't know this format
  133. else
  134. {
  135. char szBuff[5];
  136. szBuff[0] = (char)(fileType >> 24u);
  137. szBuff[1] = (char)(fileType >> 16u);
  138. szBuff[2] = (char)(fileType >> 8u);
  139. szBuff[3] = (char)(fileType);
  140. throw new ImportErrorException(std::string("Unknown LWO sub format: ") + szBuff);
  141. }
  142. ResolveTags();
  143. // now process all layers and build meshes and nodes
  144. std::vector<aiMesh*> apcMeshes;
  145. std::vector<aiNode*> apcNodes;
  146. apcNodes.reserve(mLayers->size());
  147. apcMeshes.reserve(mLayers->size()*std::min(((unsigned int)mSurfaces->size()/2u), 1u));
  148. // the RemoveRedundantMaterials step will clean this up later
  149. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = (unsigned int)mSurfaces->size()];
  150. for (unsigned int mat = 0; mat < pScene->mNumMaterials;++mat)
  151. {
  152. MaterialHelper* pcMat = new MaterialHelper();
  153. pScene->mMaterials[mat] = pcMat;
  154. ConvertMaterial((*mSurfaces)[mat],pcMat);
  155. }
  156. unsigned int iDefaultSurface = 0xffffffff; // index of the default surface
  157. for (LayerList::const_iterator lit = mLayers->begin(), lend = mLayers->end();
  158. lit != lend;++lit)
  159. {
  160. const LWO::Layer& layer = *lit;
  161. // I don't know whether there could be dummy layers, but it would be possible
  162. const unsigned int meshStart = (unsigned int)apcMeshes.size();
  163. if (!layer.mFaces.empty() && !layer.mTempPoints.empty())
  164. {
  165. // now sort all faces by the surfaces assigned to them
  166. typedef std::vector<unsigned int> SortedRep;
  167. std::vector<SortedRep> pSorted(mSurfaces->size()+1);
  168. unsigned int i = 0;
  169. for (FaceList::const_iterator it = layer.mFaces.begin(), end = layer.mFaces.end();
  170. it != end;++it,++i)
  171. {
  172. unsigned int idx = (*it).surfaceIndex;
  173. if (idx >= mTags->size())
  174. {
  175. DefaultLogger::get()->warn("LWO: Invalid face surface index");
  176. idx = (unsigned int)mTags->size()-1;
  177. }
  178. if(0xffffffff == (idx = _mMapping[idx]))
  179. {
  180. if (0xffffffff == iDefaultSurface)
  181. {
  182. iDefaultSurface = (unsigned int)mSurfaces->size();
  183. mSurfaces->push_back(LWO::Surface());
  184. LWO::Surface& surf = mSurfaces->back();
  185. surf.mColor.r = surf.mColor.g = surf.mColor.b = 0.6f;
  186. }
  187. idx = iDefaultSurface;
  188. }
  189. pSorted[idx].push_back(i);
  190. }
  191. if (0xffffffff == iDefaultSurface)pSorted.erase(pSorted.end()-1);
  192. // now generate output meshes
  193. for (unsigned int p = 0; p < mSurfaces->size();++p)
  194. if (!pSorted[p].empty())pScene->mNumMeshes++;
  195. if (!pScene->mNumMeshes)
  196. throw new ImportErrorException("LWO: There are no meshes");
  197. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  198. for (unsigned int p = 0,i = 0;i < mSurfaces->size();++i)
  199. {
  200. SortedRep& sorted = pSorted[i];
  201. if (sorted.empty())continue;
  202. // generate the mesh
  203. aiMesh* mesh = new aiMesh();
  204. apcMeshes.push_back(mesh);
  205. mesh->mNumFaces = (unsigned int)sorted.size();
  206. for (SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  207. it != end;++it)
  208. {
  209. mesh->mNumVertices += layer.mFaces[*it].mNumIndices;
  210. }
  211. aiVector3D* pv = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  212. aiFace* pf = mesh->mFaces = new aiFace[mesh->mNumFaces];
  213. mesh->mMaterialIndex = i;
  214. // find out which vertex color channels and which texture coordinate
  215. // channels are really required by the material attached to this mesh
  216. unsigned int vUVChannelIndices[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  217. unsigned int vVColorIndices[AI_MAX_NUMBER_OF_COLOR_SETS];
  218. #if _DEBUG
  219. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  220. vUVChannelIndices[mui] = 0xffffffff;
  221. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui )
  222. vVColorIndices[mui] = 0xffffffff;
  223. #endif
  224. FindUVChannels(_mSurfaces[i],layer,vUVChannelIndices);
  225. FindVCChannels(_mSurfaces[i],layer,vVColorIndices);
  226. // allocate storage for UV and CV channels
  227. aiVector3D* pvUV[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  228. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  229. {
  230. if (0xffffffff == vUVChannelIndices[mui])break;
  231. pvUV[mui] = mesh->mTextureCoords[mui] = new aiVector3D[mesh->mNumVertices];
  232. // LightWave doesn't support more than 2 UV components
  233. mesh->mNumUVComponents[0] = 2;
  234. }
  235. aiColor4D* pvVC[AI_MAX_NUMBER_OF_COLOR_SETS];
  236. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui)
  237. {
  238. if (0xffffffff == vVColorIndices[mui])break;
  239. pvVC[mui] = mesh->mColors[mui] = new aiColor4D[mesh->mNumVertices];
  240. }
  241. // now convert all faces
  242. unsigned int vert = 0;
  243. for (SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  244. it != end;++it)
  245. {
  246. const LWO::Face& face = layer.mFaces[*it];
  247. // copy all vertices
  248. for (unsigned int q = 0; q < face.mNumIndices;++q)
  249. {
  250. register unsigned int idx = face.mIndices[q];
  251. *pv++ = layer.mTempPoints[idx];
  252. // process UV coordinates
  253. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_TEXTURECOORDS;++w)
  254. {
  255. if (0xffffffff == vUVChannelIndices[w])break;
  256. *(pvUV[w])++ = layer.mUVChannels[vUVChannelIndices[w]].data[idx];
  257. }
  258. // process vertex colors
  259. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_COLOR_SETS;++w)
  260. {
  261. if (0xffffffff == vVColorIndices[w])break;
  262. *(pvVC[w])++ = layer.mVColorChannels[vVColorIndices[w]].data[idx];
  263. }
  264. #if 0
  265. // process vertex weights - not yet supported
  266. for (unsigned int w = 0; w < layer.mWeightChannels.size();++w)
  267. {
  268. }
  269. #endif
  270. face.mIndices[q] = vert++;
  271. }
  272. pf->mIndices = face.mIndices;
  273. pf->mNumIndices = face.mNumIndices;
  274. const_cast<unsigned int*>(face.mIndices) = NULL; // make sure it won't be deleted
  275. pf++;
  276. }
  277. ++p;
  278. }
  279. }
  280. // generate nodes to render the mesh. Store the parent index
  281. // in the mParent member of the nodes
  282. aiNode* pcNode = new aiNode();
  283. apcNodes.push_back(pcNode);
  284. pcNode->mName.Set(layer.mName);
  285. pcNode->mParent = reinterpret_cast<aiNode*>(layer.mParent);
  286. pcNode->mNumMeshes = (unsigned int)apcMeshes.size() - meshStart;
  287. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  288. for (unsigned int p = 0; p < pcNode->mNumMeshes;++p)
  289. pcNode->mMeshes[p] = p + meshStart;
  290. }
  291. // generate the final node graph
  292. GenerateNodeGraph(apcNodes);
  293. // copy the meshes to the output structure
  294. if (apcMeshes.size()) // shouldn't occur, just to be sure we don't crash
  295. {
  296. pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes = (unsigned int)apcMeshes.size() ];
  297. ::memcpy(pScene->mMeshes,&apcMeshes[0],pScene->mNumMeshes*sizeof(void*));
  298. }
  299. }
  300. // ------------------------------------------------------------------------------------------------
  301. void LWOImporter::GenerateNodeGraph(std::vector<aiNode*>& apcNodes)
  302. {
  303. // now generate the final nodegraph
  304. uint16_t curIndex = 0;
  305. while (curIndex < (uint16_t)apcNodes.size())
  306. {
  307. aiNode* node;
  308. uint16_t iCurParent = curIndex-1;
  309. node = curIndex ? apcNodes[iCurParent] : new aiNode("<dummy_root>");
  310. unsigned int numChilds = 0;
  311. for (unsigned int i = 0; i < apcNodes.size();++i)
  312. {
  313. if (i == iCurParent)continue;
  314. if ( reinterpret_cast<uint16_t>(apcNodes[i]->mParent) == iCurParent)++numChilds;
  315. }
  316. if (numChilds)
  317. {
  318. if (!pScene->mRootNode)
  319. {
  320. pScene->mRootNode = node;
  321. }
  322. node->mChildren = new aiNode* [ node->mNumChildren = numChilds ];
  323. for (unsigned int i = 0, p = 0; i < apcNodes.size();++i)
  324. {
  325. if (i == iCurParent)continue;
  326. uint16_t parent = reinterpret_cast<uint16_t>(apcNodes[i]->mParent);
  327. if (parent == iCurParent)
  328. {
  329. node->mChildren[p++] = apcNodes[i];
  330. apcNodes[i]->mParent = node;
  331. apcNodes[i] = NULL;
  332. }
  333. }
  334. }
  335. else if (!curIndex)delete node;
  336. ++curIndex;
  337. }
  338. // remove a single root node
  339. // TODO: implement directly in the above loop, no need to deallocate here
  340. if (1 == pScene->mRootNode->mNumChildren)
  341. {
  342. aiNode* pc = pScene->mRootNode->mChildren[0];
  343. pc->mParent = pScene->mRootNode->mChildren[0] = NULL;
  344. delete pScene->mRootNode;
  345. pScene->mRootNode = pc;
  346. }
  347. // add unreferenced nodes to a dummy root
  348. unsigned int m = 0;
  349. for (std::vector<aiNode*>::iterator it = apcNodes.begin(), end = apcNodes.end();
  350. it != end;++it)
  351. {
  352. aiNode* p = *it;
  353. if (p)++m;
  354. }
  355. if (m)
  356. {
  357. aiNode* pc = new aiNode();
  358. pc->mName.Set("<dummy_root>");
  359. aiNode** cc = pc->mChildren = new aiNode*[ pc->mNumChildren = m+1 ];
  360. for (std::vector<aiNode*>::iterator it = apcNodes.begin(), end = apcNodes.end();
  361. it != end;++it)
  362. {
  363. aiNode* p = *it;
  364. if (p)*cc++ = p;
  365. }
  366. if (pScene->mRootNode)
  367. {
  368. *cc = pScene->mRootNode;
  369. pScene->mRootNode->mParent = pc;
  370. }
  371. else --pc->mNumChildren;
  372. pScene->mRootNode = pc;
  373. }
  374. if (!pScene->mRootNode)throw new ImportErrorException("LWO: Unable to build a valid node graph");
  375. }
  376. // ------------------------------------------------------------------------------------------------
  377. void LWOImporter::ResolveTags()
  378. {
  379. // --- this function is used for both LWO2 and LWOB
  380. mMapping->resize(mTags->size(),0xffffffff);
  381. for (unsigned int a = 0; a < mTags->size();++a)
  382. {
  383. for (unsigned int i = 0; i < mSurfaces->size();++i)
  384. {
  385. const std::string& c = (*mTags)[a];
  386. const std::string& d = (*mSurfaces)[i].mName;
  387. if (!ASSIMP_stricmp(c,d))
  388. {
  389. (*mMapping)[a] = i;
  390. break;
  391. }
  392. }
  393. }
  394. }
  395. // ------------------------------------------------------------------------------------------------
  396. void LWOImporter::ParseString(std::string& out,unsigned int max)
  397. {
  398. // --- this function is used for both LWO2 and LWOB
  399. unsigned int iCursor = 0;
  400. const char* in = (const char*)mFileBuffer,*sz = in;
  401. while (*in)
  402. {
  403. if (++iCursor > max)
  404. {
  405. DefaultLogger::get()->warn("LWOB: Invalid file, string is is too long");
  406. break;
  407. }
  408. ++in;
  409. }
  410. unsigned int len = (unsigned int) (in-sz);
  411. out = std::string(sz,len);
  412. }
  413. // ------------------------------------------------------------------------------------------------
  414. void LWOImporter::AdjustTexturePath(std::string& out)
  415. {
  416. // --- this function is used for both LWO2 and LWOB
  417. if (::strstr(out.c_str(), "(sequence)"))
  418. {
  419. // remove the (sequence) and append 000
  420. DefaultLogger::get()->info("LWO: Sequence of animated texture found. It will be ignored");
  421. out = out.substr(0,out.length()-10) + "000";
  422. }
  423. }
  424. // ------------------------------------------------------------------------------------------------
  425. int LWOImporter::ReadVSizedIntLWO2(uint8_t*& inout)
  426. {
  427. int i;
  428. int c = *inout;inout++;
  429. if(c != 0xFF)
  430. {
  431. i = c << 8;
  432. c = *inout;inout++;
  433. i |= c;
  434. }
  435. else
  436. {
  437. c = *inout;inout++;
  438. i = c << 16;
  439. c = *inout;inout++;
  440. i |= c << 8;
  441. c = *inout;inout++;
  442. i |= c;
  443. }
  444. return i;
  445. }
  446. // ------------------------------------------------------------------------------------------------
  447. void LWOImporter::LoadLWOTags(unsigned int size)
  448. {
  449. // --- this function is used for both LWO2 and LWOB
  450. const char* szCur = (const char*)mFileBuffer, *szLast = szCur;
  451. const char* const szEnd = szLast+size;
  452. while (szCur < szEnd)
  453. {
  454. if (!(*szCur))
  455. {
  456. const unsigned int len = (unsigned int)(szCur-szLast);
  457. mTags->push_back(std::string(szLast,len));
  458. szCur += len & 1;
  459. szLast = szCur;
  460. }
  461. szCur++;
  462. }
  463. }
  464. // ------------------------------------------------------------------------------------------------
  465. void LWOImporter::LoadLWOPoints(unsigned int length)
  466. {
  467. // --- this function is used for both LWO2 and LWOB
  468. mCurLayer->mTempPoints.resize( length / 12 );
  469. // perform endianess conversions
  470. #ifndef AI_BUILD_BIG_ENDIAN
  471. for (unsigned int i = 0; i < length>>2;++i)
  472. ByteSwap::Swap4( mFileBuffer + (i << 2));
  473. #endif
  474. ::memcpy(&mCurLayer->mTempPoints[0],mFileBuffer,length);
  475. }
  476. // ------------------------------------------------------------------------------------------------
  477. void LWOImporter::LoadLWOPolygons(unsigned int length)
  478. {
  479. // --- this function is used for both LWO2 and LWOB
  480. if (mIsLWO2)
  481. {
  482. uint32_t type = *((LE_NCONST uint32_t*)mFileBuffer);mFileBuffer += 4;
  483. if (type != AI_LWO_FACE)
  484. {
  485. DefaultLogger::get()->warn("LWO2: Only POLS.FACE chunsk are supported.");
  486. return;
  487. }
  488. }
  489. // first find out how many faces and vertices we'll finally need
  490. LE_NCONST uint16_t* const end = (LE_NCONST uint16_t*)(mFileBuffer+length);
  491. LE_NCONST uint16_t* cursor = (LE_NCONST uint16_t*)mFileBuffer;
  492. // perform endianess conversions
  493. #ifndef AI_BUILD_BIG_ENDIAN
  494. while (cursor < end)ByteSwap::Swap2(cursor++);
  495. cursor = (LE_NCONST uint16_t*)mFileBuffer;
  496. #endif
  497. unsigned int iNumFaces = 0,iNumVertices = 0;
  498. if (mIsLWO2)CountVertsAndFacesLWO2(iNumVertices,iNumFaces,cursor,end);
  499. else CountVertsAndFacesLWOB(iNumVertices,iNumFaces,cursor,end);
  500. // allocate the output array and copy face indices
  501. if (iNumFaces)
  502. {
  503. cursor = (LE_NCONST uint16_t*)mFileBuffer;
  504. mCurLayer->mFaces.resize(iNumFaces);
  505. FaceList::iterator it = mCurLayer->mFaces.begin();
  506. if (mIsLWO2)CopyFaceIndicesLWO2(it,cursor,end);
  507. else CopyFaceIndicesLWOB(it,cursor,end);
  508. }
  509. }
  510. // ------------------------------------------------------------------------------------------------
  511. void LWOImporter::CountVertsAndFacesLWO2(unsigned int& verts, unsigned int& faces,
  512. LE_NCONST uint16_t*& cursor, const uint16_t* const end, unsigned int max)
  513. {
  514. while (cursor < end && max--)
  515. {
  516. uint16_t numIndices = *cursor++;
  517. numIndices &= 0x03FF;
  518. verts += numIndices;++faces;
  519. for(uint16_t i = 0; i < numIndices; i++)
  520. ReadVSizedIntLWO2((uint8_t*&)cursor);
  521. }
  522. }
  523. // ------------------------------------------------------------------------------------------------
  524. void LWOImporter::CopyFaceIndicesLWO2(FaceList::iterator& it,
  525. LE_NCONST uint16_t*& cursor,
  526. const uint16_t* const end,
  527. unsigned int max)
  528. {
  529. while (cursor < end && max--)
  530. {
  531. LWO::Face& face = *it;++it;
  532. if(face.mNumIndices = (*cursor++) & 0x03FF)
  533. {
  534. face.mIndices = new unsigned int[face.mNumIndices];
  535. for(unsigned int i = 0; i < face.mNumIndices; i++)
  536. {
  537. face.mIndices[i] = ReadVSizedIntLWO2((uint8_t*&)cursor) + mCurLayer->mPointIDXOfs;
  538. if(face.mIndices[i] > mCurLayer->mTempPoints.size())
  539. {
  540. DefaultLogger::get()->warn("LWO2: face index is out of range");
  541. face.mIndices[i] = (unsigned int)mCurLayer->mTempPoints.size()-1;
  542. }
  543. }
  544. }
  545. else DefaultLogger::get()->warn("LWO2: face has 0 indices");
  546. }
  547. }
  548. // ------------------------------------------------------------------------------------------------
  549. void LWOImporter::LoadLWO2PolygonTags(unsigned int length)
  550. {
  551. uint32_t type = *((LE_NCONST uint32_t*)mFileBuffer);mFileBuffer+=4;
  552. AI_LSWAP4(type);
  553. if (type != AI_LWO_SURF && type != AI_LWO_SMGP)
  554. return;
  555. LE_NCONST uint8_t* const end = mFileBuffer+length;
  556. while (mFileBuffer < end)
  557. {
  558. unsigned int i = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  559. unsigned int j = ReadVSizedIntLWO2(mFileBuffer);
  560. if (i > mCurLayer->mFaces.size())
  561. {
  562. DefaultLogger::get()->warn("LWO2: face index in ptag list is out of range");
  563. continue;
  564. }
  565. switch (type)
  566. {
  567. case AI_LWO_SURF:
  568. mCurLayer->mFaces[i].surfaceIndex = j;
  569. break;
  570. case AI_LWO_SMGP:
  571. mCurLayer->mFaces[i].smoothGroup = j;
  572. break;
  573. };
  574. }
  575. }
  576. // ------------------------------------------------------------------------------------------------
  577. void LWOImporter::LoadLWO2VertexMap(unsigned int length, bool perPoly)
  578. {
  579. unsigned int type = *((LE_NCONST uint32_t*)mFileBuffer);mFileBuffer+=4;
  580. unsigned int dims = *((LE_NCONST uint16_t*)mFileBuffer);mFileBuffer+=2;
  581. VMapEntry* base;
  582. switch (type)
  583. {
  584. case AI_LWO_TXUV:
  585. if (dims != 2)
  586. {
  587. DefaultLogger::get()->warn("LWO2: Found UV channel with != 2 components");
  588. }
  589. mCurLayer->mUVChannels.push_back(UVChannel(mCurLayer->mTempPoints.size()));
  590. base = &mCurLayer->mUVChannels.back();
  591. case AI_LWO_WGHT:
  592. if (dims != 1)
  593. {
  594. DefaultLogger::get()->warn("LWO2: found vertex weight map with != 1 components");
  595. }
  596. mCurLayer->mWeightChannels.push_back(WeightChannel(mCurLayer->mTempPoints.size()));
  597. base = &mCurLayer->mWeightChannels.back();
  598. case AI_LWO_RGB:
  599. case AI_LWO_RGBA:
  600. if (dims != 3 && dims != 4)
  601. {
  602. DefaultLogger::get()->warn("LWO2: found vertex color map with != 3&4 components");
  603. }
  604. mCurLayer->mVColorChannels.push_back(VColorChannel(mCurLayer->mTempPoints.size()));
  605. base = &mCurLayer->mVColorChannels.back();
  606. default: return;
  607. };
  608. // read the name of the vertex map
  609. ParseString(base->name,length);
  610. // now read all entries in the map
  611. type = std::min(dims,base->dims);
  612. const unsigned int diff = (dims - type)<<2;
  613. LE_NCONST uint8_t* const end = mFileBuffer+length;
  614. while (mFileBuffer < end)
  615. {
  616. unsigned int idx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mPointIDXOfs;
  617. if (idx > mCurLayer->mTempPoints.size())
  618. {
  619. DefaultLogger::get()->warn("LWO2: vertex index in vmap/vmad is out of range");
  620. continue;
  621. }
  622. for (unsigned int i = 0; i < type;++i)
  623. {
  624. base->rawData[idx*dims+i]= *((float*)mFileBuffer);
  625. mFileBuffer += 4;
  626. }
  627. mFileBuffer += diff;
  628. }
  629. }
  630. // ------------------------------------------------------------------------------------------------
  631. void LWOImporter::LoadLWO2File()
  632. {
  633. LE_NCONST uint8_t* const end = mFileBuffer + fileSize;
  634. while (true)
  635. {
  636. if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break;
  637. LE_NCONST IFF::ChunkHeader* const head = (LE_NCONST IFF::ChunkHeader*)mFileBuffer;
  638. AI_LSWAP4(head->length);
  639. AI_LSWAP4(head->type);
  640. mFileBuffer += sizeof(IFF::ChunkHeader);
  641. if (mFileBuffer + head->length > end)
  642. {
  643. throw new ImportErrorException("LWOB: Invalid file, the size attribute of "
  644. "a chunk points behind the end of the file");
  645. break;
  646. }
  647. LE_NCONST uint8_t* const next = mFileBuffer+head->length;
  648. unsigned int iUnnamed = 0;
  649. switch (head->type)
  650. {
  651. // new layer
  652. case AI_LWO_LAYR:
  653. {
  654. // add a new layer to the list ....
  655. mLayers->push_back ( LWO::Layer() );
  656. LWO::Layer& layer = mLayers->back();
  657. mCurLayer = &layer;
  658. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,LAYR,16);
  659. // and parse its properties
  660. mFileBuffer += 16;
  661. ParseString(layer.mName,head->length-16);
  662. // if the name is empty, generate a default name
  663. if (layer.mName.empty())
  664. {
  665. char buffer[128]; // should be sufficiently large
  666. ::sprintf(buffer,"Layer_%i", iUnnamed++);
  667. layer.mName = buffer;
  668. }
  669. if (mFileBuffer + 2 <= next)
  670. layer.mParent = *((uint16_t*)mFileBuffer);
  671. break;
  672. }
  673. // vertex list
  674. case AI_LWO_PNTS:
  675. {
  676. unsigned int old = (unsigned int)mCurLayer->mTempPoints.size();
  677. LoadLWOPoints(head->length);
  678. mCurLayer->mPointIDXOfs = old;
  679. break;
  680. }
  681. // vertex tags
  682. //case AI_LWO_VMAD:
  683. case AI_LWO_VMAP:
  684. {
  685. if (mCurLayer->mTempPoints.empty())
  686. DefaultLogger::get()->warn("LWO2: Unexpected VMAD/VMAP chunk");
  687. else LoadLWO2VertexMap(head->length,head->type == AI_LWO_VMAD);
  688. break;
  689. }
  690. // face list
  691. case AI_LWO_POLS:
  692. {
  693. unsigned int old = (unsigned int)mCurLayer->mFaces.size();
  694. LoadLWOPolygons(head->length);
  695. mCurLayer->mFaceIDXOfs = old;
  696. break;
  697. }
  698. // polygon tags
  699. case AI_LWO_PTAG:
  700. {
  701. if (mCurLayer->mFaces.empty())
  702. DefaultLogger::get()->warn("LWO2: Unexpected PTAG");
  703. else LoadLWO2PolygonTags(head->length);
  704. break;
  705. }
  706. // list of tags
  707. case AI_LWO_SRFS:
  708. {
  709. if (!mTags->empty())
  710. DefaultLogger::get()->warn("LWO2: SRFS chunk encountered twice");
  711. else LoadLWOTags(head->length);
  712. break;
  713. }
  714. // surface chunk
  715. case AI_LWO_SURF:
  716. {
  717. if (!mSurfaces->empty())
  718. DefaultLogger::get()->warn("LWO2: SURF chunk encountered twice");
  719. else LoadLWO2Surface(head->length);
  720. break;
  721. }
  722. }
  723. mFileBuffer = next;
  724. }
  725. }