LWOLoader.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, assimp 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 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 LWOLoader.cpp
  35. * @brief Implementation of the LWO importer class
  36. */
  37. #include "AssimpPCH.h"
  38. #ifndef ASSIMP_BUILD_NO_LWO_IMPORTER
  39. // internal headers
  40. #include "LWOLoader.h"
  41. #include "StringComparison.h"
  42. #include "SGSpatialSort.h"
  43. #include "ByteSwap.h"
  44. #include "ProcessHelper.h"
  45. #include "ConvertToLHProcess.h"
  46. using namespace Assimp;
  47. static const aiImporterDesc desc = {
  48. "LightWave/Modo Object Importer",
  49. "",
  50. "",
  51. "http://www.newtek.com/lightwave.html\nhttp://www.luxology.com/modo/",
  52. aiImporterFlags_SupportTextFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "lwo lxo"
  58. };
  59. // ------------------------------------------------------------------------------------------------
  60. // Constructor to be privately used by Importer
  61. LWOImporter::LWOImporter()
  62. {}
  63. // ------------------------------------------------------------------------------------------------
  64. // Destructor, private as well
  65. LWOImporter::~LWOImporter()
  66. {}
  67. // ------------------------------------------------------------------------------------------------
  68. // Returns whether the class can handle the format of the given file.
  69. bool LWOImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  70. {
  71. const std::string extension = GetExtension(pFile);
  72. if (extension == "lwo" || extension == "lxo") {
  73. return true;
  74. }
  75. // if check for extension is not enough, check for the magic tokens
  76. if (!extension.length() || checkSig) {
  77. uint32_t tokens[3];
  78. tokens[0] = AI_LWO_FOURCC_LWOB;
  79. tokens[1] = AI_LWO_FOURCC_LWO2;
  80. tokens[2] = AI_LWO_FOURCC_LXOB;
  81. return CheckMagicToken(pIOHandler,pFile,tokens,3,8);
  82. }
  83. return false;
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. // Setup configuration properties
  87. void LWOImporter::SetupProperties(const Importer* pImp)
  88. {
  89. configSpeedFlag = ( 0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0) ? true : false);
  90. configLayerIndex = pImp->GetPropertyInteger (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,UINT_MAX);
  91. configLayerName = pImp->GetPropertyString (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,"");
  92. }
  93. // ------------------------------------------------------------------------------------------------
  94. // Get list of file extensions
  95. const aiImporterDesc* LWOImporter::GetInfo () const
  96. {
  97. return &desc;
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Imports the given file into the given scene structure.
  101. void LWOImporter::InternReadFile( const std::string& pFile,
  102. aiScene* pScene,
  103. IOSystem* pIOHandler)
  104. {
  105. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  106. // Check whether we can read from the file
  107. if( file.get() == NULL)
  108. throw DeadlyImportError( "Failed to open LWO file " + pFile + ".");
  109. if((this->fileSize = (unsigned int)file->FileSize()) < 12)
  110. throw DeadlyImportError("LWO: The file is too small to contain the IFF header");
  111. // Allocate storage and copy the contents of the file to a memory buffer
  112. std::vector< uint8_t > mBuffer(fileSize);
  113. file->Read( &mBuffer[0], 1, fileSize);
  114. this->pScene = pScene;
  115. // Determine the type of the file
  116. uint32_t fileType;
  117. const char* sz = IFF::ReadHeader(&mBuffer[0],fileType);
  118. if (sz)throw DeadlyImportError(sz);
  119. mFileBuffer = &mBuffer[0] + 12;
  120. fileSize -= 12;
  121. // Initialize some members with their default values
  122. hasNamedLayer = false;
  123. // Create temporary storage on the stack but store pointers to it in the class
  124. // instance. Therefore everything will be destructed properly if an exception
  125. // is thrown and we needn't take care of that.
  126. LayerList _mLayers;
  127. SurfaceList _mSurfaces;
  128. TagList _mTags;
  129. TagMappingTable _mMapping;
  130. mLayers = &_mLayers;
  131. mTags = &_mTags;
  132. mMapping = &_mMapping;
  133. mSurfaces = &_mSurfaces;
  134. // Allocate a default layer (layer indices are 1-based from now)
  135. mLayers->push_back(Layer());
  136. mCurLayer = &mLayers->back();
  137. mCurLayer->mName = "<LWODefault>";
  138. mCurLayer->mIndex = -1;
  139. // old lightwave file format (prior to v6)
  140. if (AI_LWO_FOURCC_LWOB == fileType) {
  141. DefaultLogger::get()->info("LWO file format: LWOB (<= LightWave 5.5)");
  142. mIsLWO2 = false;
  143. mIsLXOB = false;
  144. LoadLWOBFile();
  145. }
  146. // New lightwave format
  147. else if (AI_LWO_FOURCC_LWO2 == fileType) {
  148. mIsLXOB = false;
  149. DefaultLogger::get()->info("LWO file format: LWO2 (>= LightWave 6)");
  150. }
  151. // MODO file format
  152. else if (AI_LWO_FOURCC_LXOB == fileType) {
  153. mIsLXOB = true;
  154. DefaultLogger::get()->info("LWO file format: LXOB (Modo)");
  155. }
  156. // we don't know this format
  157. else
  158. {
  159. char szBuff[5];
  160. szBuff[0] = (char)(fileType >> 24u);
  161. szBuff[1] = (char)(fileType >> 16u);
  162. szBuff[2] = (char)(fileType >> 8u);
  163. szBuff[3] = (char)(fileType);
  164. szBuff[4] = '\0';
  165. throw DeadlyImportError(std::string("Unknown LWO sub format: ") + szBuff);
  166. }
  167. if (AI_LWO_FOURCC_LWOB != fileType) {
  168. mIsLWO2 = true;
  169. LoadLWO2File();
  170. // The newer lightwave format allows the user to configure the
  171. // loader that just one layer is used. If this is the case
  172. // we need to check now whether the requested layer has been found.
  173. if (UINT_MAX != configLayerIndex) {
  174. unsigned int layerCount = 0;
  175. for(std::list<LWO::Layer>::iterator itLayers=mLayers->begin(); itLayers!=mLayers->end(); itLayers++)
  176. if (!itLayers->skip)
  177. layerCount++;
  178. if (layerCount!=2)
  179. throw DeadlyImportError("LWO2: The requested layer was not found");
  180. }
  181. if (configLayerName.length() && !hasNamedLayer) {
  182. throw DeadlyImportError("LWO2: Unable to find the requested layer: "
  183. + configLayerName);
  184. }
  185. }
  186. // now, as we have loaded all data, we can resolve cross-referenced tags and clips
  187. ResolveTags();
  188. ResolveClips();
  189. // now process all layers and build meshes and nodes
  190. std::vector<aiMesh*> apcMeshes;
  191. std::map<uint16_t, aiNode*> apcNodes;
  192. apcMeshes.reserve(mLayers->size()*std::min(((unsigned int)mSurfaces->size()/2u), 1u));
  193. unsigned int iDefaultSurface = UINT_MAX; // index of the default surface
  194. for (LayerList::iterator lit = mLayers->begin(), lend = mLayers->end();lit != lend;++lit) {
  195. LWO::Layer& layer = *lit;
  196. if (layer.skip)
  197. continue;
  198. // I don't know whether there could be dummy layers, but it would be possible
  199. const unsigned int meshStart = (unsigned int)apcMeshes.size();
  200. if (!layer.mFaces.empty() && !layer.mTempPoints.empty()) {
  201. // now sort all faces by the surfaces assigned to them
  202. std::vector<SortedRep> pSorted(mSurfaces->size()+1);
  203. unsigned int i = 0;
  204. for (FaceList::iterator it = layer.mFaces.begin(), end = layer.mFaces.end();it != end;++it,++i) {
  205. // Check whether we support this face's type
  206. if ((*it).type != AI_LWO_FACE && (*it).type != AI_LWO_PTCH &&
  207. (*it).type != AI_LWO_BONE && (*it).type != AI_LWO_SUBD) {
  208. continue;
  209. }
  210. unsigned int idx = (*it).surfaceIndex;
  211. if (idx >= mTags->size())
  212. {
  213. DefaultLogger::get()->warn("LWO: Invalid face surface index");
  214. idx = UINT_MAX;
  215. }
  216. if(UINT_MAX == idx || UINT_MAX == (idx = _mMapping[idx])) {
  217. if (UINT_MAX == iDefaultSurface) {
  218. iDefaultSurface = (unsigned int)mSurfaces->size();
  219. mSurfaces->push_back(LWO::Surface());
  220. LWO::Surface& surf = mSurfaces->back();
  221. surf.mColor.r = surf.mColor.g = surf.mColor.b = 0.6f;
  222. surf.mName = "LWODefaultSurface";
  223. }
  224. idx = iDefaultSurface;
  225. }
  226. pSorted[idx].push_back(i);
  227. }
  228. if (UINT_MAX == iDefaultSurface) {
  229. pSorted.erase(pSorted.end()-1);
  230. }
  231. for (unsigned int p = 0,i = 0;i < mSurfaces->size();++i) {
  232. SortedRep& sorted = pSorted[i];
  233. if (sorted.empty())
  234. continue;
  235. // generate the mesh
  236. aiMesh* mesh = new aiMesh();
  237. apcMeshes.push_back(mesh);
  238. mesh->mNumFaces = (unsigned int)sorted.size();
  239. // count the number of vertices
  240. SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  241. for (;it != end;++it) {
  242. mesh->mNumVertices += layer.mFaces[*it].mNumIndices;
  243. }
  244. aiVector3D *nrm = NULL, * pv = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  245. aiFace* pf = mesh->mFaces = new aiFace[mesh->mNumFaces];
  246. mesh->mMaterialIndex = i;
  247. // find out which vertex color channels and which texture coordinate
  248. // channels are really required by the material attached to this mesh
  249. unsigned int vUVChannelIndices[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  250. unsigned int vVColorIndices[AI_MAX_NUMBER_OF_COLOR_SETS];
  251. #ifdef ASSIMP_BUILD_DEBUG
  252. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui ) {
  253. vUVChannelIndices[mui] = UINT_MAX;
  254. }
  255. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui ) {
  256. vVColorIndices[mui] = UINT_MAX;
  257. }
  258. #endif
  259. FindUVChannels(_mSurfaces[i],sorted,layer,vUVChannelIndices);
  260. FindVCChannels(_mSurfaces[i],sorted,layer,vVColorIndices);
  261. // allocate storage for UV and CV channels
  262. aiVector3D* pvUV[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  263. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui ) {
  264. if (UINT_MAX == vUVChannelIndices[mui]) {
  265. break;
  266. }
  267. pvUV[mui] = mesh->mTextureCoords[mui] = new aiVector3D[mesh->mNumVertices];
  268. // LightWave doesn't support more than 2 UV components (?)
  269. mesh->mNumUVComponents[0] = 2;
  270. }
  271. if (layer.mNormals.name.length())
  272. nrm = mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  273. aiColor4D* pvVC[AI_MAX_NUMBER_OF_COLOR_SETS];
  274. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui) {
  275. if (UINT_MAX == vVColorIndices[mui]) {
  276. break;
  277. }
  278. pvVC[mui] = mesh->mColors[mui] = new aiColor4D[mesh->mNumVertices];
  279. }
  280. // we would not need this extra array, but the code is much cleaner if we use it
  281. std::vector<unsigned int>& smoothingGroups = layer.mPointReferrers;
  282. smoothingGroups.erase (smoothingGroups.begin(),smoothingGroups.end());
  283. smoothingGroups.resize(mesh->mNumFaces,0);
  284. // now convert all faces
  285. unsigned int vert = 0;
  286. std::vector<unsigned int>::iterator outIt = smoothingGroups.begin();
  287. for (it = sorted.begin(); it != end;++it,++outIt) {
  288. const LWO::Face& face = layer.mFaces[*it];
  289. *outIt = face.smoothGroup;
  290. // copy all vertices
  291. for (unsigned int q = 0; q < face.mNumIndices;++q,++vert) {
  292. unsigned int idx = face.mIndices[q];
  293. *pv++ = layer.mTempPoints[idx] /*- layer.mPivot*/;
  294. // process UV coordinates
  295. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_TEXTURECOORDS;++w) {
  296. if (UINT_MAX == vUVChannelIndices[w]) {
  297. break;
  298. }
  299. aiVector3D*& pp = pvUV[w];
  300. const aiVector2D& src = ((aiVector2D*)&layer.mUVChannels[vUVChannelIndices[w]].rawData[0])[idx];
  301. pp->x = src.x;
  302. pp->y = src.y;
  303. pp++;
  304. }
  305. // process normals (MODO extension)
  306. if (nrm) {
  307. *nrm = ((aiVector3D*)&layer.mNormals.rawData[0])[idx];
  308. nrm->z *= -1.f;
  309. ++nrm;
  310. }
  311. // process vertex colors
  312. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_COLOR_SETS;++w) {
  313. if (UINT_MAX == vVColorIndices[w]) {
  314. break;
  315. }
  316. *pvVC[w] = ((aiColor4D*)&layer.mVColorChannels[vVColorIndices[w]].rawData[0])[idx];
  317. // If a RGB color map is explicitly requested delete the
  318. // alpha channel - it could theoretically be != 1.
  319. if(_mSurfaces[i].mVCMapType == AI_LWO_RGB)
  320. pvVC[w]->a = 1.f;
  321. pvVC[w]++;
  322. }
  323. #if 0
  324. // process vertex weights. We can't properly reconstruct the whole skeleton for now,
  325. // but we can create dummy bones for all weight channels which we have.
  326. for (unsigned int w = 0; w < layer.mWeightChannels.size();++w)
  327. {
  328. }
  329. #endif
  330. face.mIndices[q] = vert;
  331. }
  332. pf->mIndices = face.mIndices;
  333. pf->mNumIndices = face.mNumIndices;
  334. unsigned int** p = (unsigned int**)&face.mIndices;*p = NULL; // HACK: make sure it won't be deleted
  335. pf++;
  336. }
  337. if (!mesh->mNormals) {
  338. // Compute normal vectors for the mesh - we can't use our GenSmoothNormal-
  339. // Step here since it wouldn't handle smoothing groups correctly for LWO.
  340. // So we use a separate implementation.
  341. ComputeNormals(mesh,smoothingGroups,_mSurfaces[i]);
  342. }
  343. else DefaultLogger::get()->debug("LWO2: No need to compute normals, they're already there");
  344. ++p;
  345. }
  346. }
  347. // Generate nodes to render the mesh. Store the source layer in the mParent member of the nodes
  348. unsigned int num = apcMeshes.size() - meshStart;
  349. if (layer.mName != "<LWODefault>" || num > 0) {
  350. aiNode* pcNode = new aiNode();
  351. apcNodes[layer.mIndex] = pcNode;
  352. pcNode->mName.Set(layer.mName);
  353. pcNode->mParent = (aiNode*)&layer;
  354. pcNode->mNumMeshes = num;
  355. if (pcNode->mNumMeshes) {
  356. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  357. for (unsigned int p = 0; p < pcNode->mNumMeshes;++p)
  358. pcNode->mMeshes[p] = p + meshStart;
  359. }
  360. }
  361. }
  362. if (apcNodes.empty() || apcMeshes.empty())
  363. throw DeadlyImportError("LWO: No meshes loaded");
  364. // The RemoveRedundantMaterials step will clean this up later
  365. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = (unsigned int)mSurfaces->size()];
  366. for (unsigned int mat = 0; mat < pScene->mNumMaterials;++mat) {
  367. aiMaterial* pcMat = new aiMaterial();
  368. pScene->mMaterials[mat] = pcMat;
  369. ConvertMaterial((*mSurfaces)[mat],pcMat);
  370. }
  371. // copy the meshes to the output structure
  372. pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes = (unsigned int)apcMeshes.size() ];
  373. ::memcpy(pScene->mMeshes,&apcMeshes[0],pScene->mNumMeshes*sizeof(void*));
  374. // generate the final node graph
  375. GenerateNodeGraph(apcNodes);
  376. }
  377. // ------------------------------------------------------------------------------------------------
  378. void LWOImporter::ComputeNormals(aiMesh* mesh, const std::vector<unsigned int>& smoothingGroups,
  379. const LWO::Surface& surface)
  380. {
  381. // Allocate output storage
  382. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  383. // First generate per-face normals
  384. aiVector3D* out;
  385. std::vector<aiVector3D> faceNormals;
  386. // ... in some cases that's already enough
  387. if (!surface.mMaximumSmoothAngle)
  388. out = mesh->mNormals;
  389. else {
  390. faceNormals.resize(mesh->mNumVertices);
  391. out = &faceNormals[0];
  392. }
  393. aiFace* begin = mesh->mFaces, *const end = mesh->mFaces+mesh->mNumFaces;
  394. for (; begin != end; ++begin) {
  395. aiFace& face = *begin;
  396. if(face.mNumIndices < 3) {
  397. continue;
  398. }
  399. // LWO doc: "the normal is defined as the cross product of the first and last edges"
  400. aiVector3D* pV1 = mesh->mVertices + face.mIndices[0];
  401. aiVector3D* pV2 = mesh->mVertices + face.mIndices[1];
  402. aiVector3D* pV3 = mesh->mVertices + face.mIndices[face.mNumIndices-1];
  403. aiVector3D vNor = ((*pV2 - *pV1) ^(*pV3 - *pV1)).Normalize();
  404. for (unsigned int i = 0; i < face.mNumIndices;++i)
  405. out[face.mIndices[i]] = vNor;
  406. }
  407. if (!surface.mMaximumSmoothAngle)return;
  408. const float posEpsilon = ComputePositionEpsilon(mesh);
  409. // Now generate the spatial sort tree
  410. SGSpatialSort sSort;
  411. std::vector<unsigned int>::const_iterator it = smoothingGroups.begin();
  412. for( begin = mesh->mFaces; begin != end; ++begin, ++it)
  413. {
  414. aiFace& face = *begin;
  415. for (unsigned int i = 0; i < face.mNumIndices;++i)
  416. {
  417. unsigned int tt = face.mIndices[i];
  418. sSort.Add(mesh->mVertices[tt],tt,*it);
  419. }
  420. }
  421. // Sort everything - this takes O(nlogn) time
  422. sSort.Prepare();
  423. std::vector<unsigned int> poResult;
  424. poResult.reserve(20);
  425. // Generate vertex normals. We have O(logn) for the binary lookup, which we need
  426. // for n elements, thus the EXPECTED complexity is O(nlogn)
  427. if (surface.mMaximumSmoothAngle < 3.f && !configSpeedFlag) {
  428. const float fLimit = std::cos(surface.mMaximumSmoothAngle);
  429. for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it) {
  430. const aiFace& face = *begin;
  431. unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
  432. for (; beginIdx != endIdx; ++beginIdx)
  433. {
  434. unsigned int idx = *beginIdx;
  435. sSort.FindPositions(mesh->mVertices[idx],*it,posEpsilon,poResult,true);
  436. std::vector<unsigned int>::const_iterator a, end = poResult.end();
  437. aiVector3D vNormals;
  438. for (a = poResult.begin();a != end;++a) {
  439. const aiVector3D& v = faceNormals[*a];
  440. if (v * faceNormals[idx] < fLimit)
  441. continue;
  442. vNormals += v;
  443. }
  444. mesh->mNormals[idx] = vNormals.Normalize();
  445. }
  446. }
  447. }
  448. // faster code path in case there is no smooth angle
  449. else {
  450. std::vector<bool> vertexDone(mesh->mNumVertices,false);
  451. for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it) {
  452. const aiFace& face = *begin;
  453. unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
  454. for (; beginIdx != endIdx; ++beginIdx)
  455. {
  456. unsigned int idx = *beginIdx;
  457. if (vertexDone[idx])
  458. continue;
  459. sSort.FindPositions(mesh->mVertices[idx],*it,posEpsilon,poResult,true);
  460. std::vector<unsigned int>::const_iterator a, end = poResult.end();
  461. aiVector3D vNormals;
  462. for (a = poResult.begin();a != end;++a) {
  463. const aiVector3D& v = faceNormals[*a];
  464. vNormals += v;
  465. }
  466. vNormals.Normalize();
  467. for (a = poResult.begin();a != end;++a) {
  468. mesh->mNormals[*a] = vNormals;
  469. vertexDone[*a] = true;
  470. }
  471. }
  472. }
  473. }
  474. }
  475. // ------------------------------------------------------------------------------------------------
  476. void LWOImporter::GenerateNodeGraph(std::map<uint16_t,aiNode*>& apcNodes)
  477. {
  478. // now generate the final nodegraph - generate a root node and attach children
  479. aiNode* root = pScene->mRootNode = new aiNode();
  480. root->mName.Set("<LWORoot>");
  481. //Set parent of all children, inserting pivots
  482. //std::cout << "Set parent of all children" << std::endl;
  483. std::map<uint16_t, aiNode*> mapPivot;
  484. for (std::map<uint16_t,aiNode*>::iterator itapcNodes = apcNodes.begin(); itapcNodes != apcNodes.end(); ++itapcNodes) {
  485. //Get the parent index
  486. LWO::Layer* nodeLayer = (LWO::Layer*)(itapcNodes->second->mParent);
  487. uint16_t parentIndex = nodeLayer->mParent;
  488. //Create pivot node, store it into the pivot map, and set the parent as the pivot
  489. aiNode* pivotNode = new aiNode();
  490. pivotNode->mName.Set("Pivot-"+std::string(itapcNodes->second->mName.data));
  491. mapPivot[-(itapcNodes->first+2)] = pivotNode;
  492. itapcNodes->second->mParent = pivotNode;
  493. //Look for the parent node to attach the pivot to
  494. if (apcNodes.find(parentIndex) != apcNodes.end()) {
  495. pivotNode->mParent = apcNodes[parentIndex];
  496. } else {
  497. //If not, attach to the root node
  498. pivotNode->mParent = root;
  499. }
  500. //Set the node and the pivot node transformation
  501. itapcNodes->second->mTransformation.a4 = -nodeLayer->mPivot.x;
  502. itapcNodes->second->mTransformation.b4 = -nodeLayer->mPivot.y;
  503. itapcNodes->second->mTransformation.c4 = -nodeLayer->mPivot.z;
  504. pivotNode->mTransformation.a4 = nodeLayer->mPivot.x;
  505. pivotNode->mTransformation.b4 = nodeLayer->mPivot.y;
  506. pivotNode->mTransformation.c4 = nodeLayer->mPivot.z;
  507. }
  508. //Merge pivot map into node map
  509. //std::cout << "Merge pivot map into node map" << std::endl;
  510. for (std::map<uint16_t, aiNode*>::iterator itMapPivot = mapPivot.begin(); itMapPivot != mapPivot.end(); ++itMapPivot) {
  511. apcNodes[itMapPivot->first] = itMapPivot->second;
  512. }
  513. //Set children of all parents
  514. apcNodes[-1] = root;
  515. for (std::map<uint16_t,aiNode*>::iterator itMapParentNodes = apcNodes.begin(); itMapParentNodes != apcNodes.end(); ++itMapParentNodes) {
  516. for (std::map<uint16_t,aiNode*>::iterator itMapChildNodes = apcNodes.begin(); itMapChildNodes != apcNodes.end(); ++itMapChildNodes) {
  517. if ((itMapParentNodes->first != itMapChildNodes->first) && (itMapParentNodes->second == itMapChildNodes->second->mParent)) {
  518. ++(itMapParentNodes->second->mNumChildren);
  519. }
  520. }
  521. if (itMapParentNodes->second->mNumChildren) {
  522. itMapParentNodes->second->mChildren = new aiNode* [ itMapParentNodes->second->mNumChildren ];
  523. uint16_t p = 0;
  524. for (std::map<uint16_t,aiNode*>::iterator itMapChildNodes = apcNodes.begin(); itMapChildNodes != apcNodes.end(); ++itMapChildNodes) {
  525. if ((itMapParentNodes->first != itMapChildNodes->first) && (itMapParentNodes->second == itMapChildNodes->second->mParent)) {
  526. itMapParentNodes->second->mChildren[p++] = itMapChildNodes->second;
  527. }
  528. }
  529. }
  530. }
  531. if (!pScene->mRootNode->mNumChildren)
  532. throw DeadlyImportError("LWO: Unable to build a valid node graph");
  533. // Remove a single root node with no meshes assigned to it ...
  534. if (1 == pScene->mRootNode->mNumChildren) {
  535. aiNode* pc = pScene->mRootNode->mChildren[0];
  536. pc->mParent = pScene->mRootNode->mChildren[0] = NULL;
  537. delete pScene->mRootNode;
  538. pScene->mRootNode = pc;
  539. }
  540. // convert the whole stuff to RH with CCW winding
  541. MakeLeftHandedProcess maker;
  542. maker.Execute(pScene);
  543. FlipWindingOrderProcess flipper;
  544. flipper.Execute(pScene);
  545. }
  546. // ------------------------------------------------------------------------------------------------
  547. void LWOImporter::ResolveTags()
  548. {
  549. // --- this function is used for both LWO2 and LWOB
  550. mMapping->resize(mTags->size(), UINT_MAX);
  551. for (unsigned int a = 0; a < mTags->size();++a) {
  552. const std::string& c = (*mTags)[a];
  553. for (unsigned int i = 0; i < mSurfaces->size();++i) {
  554. const std::string& d = (*mSurfaces)[i].mName;
  555. if (!ASSIMP_stricmp(c,d)) {
  556. (*mMapping)[a] = i;
  557. break;
  558. }
  559. }
  560. }
  561. }
  562. // ------------------------------------------------------------------------------------------------
  563. void LWOImporter::ResolveClips()
  564. {
  565. for( unsigned int i = 0; i < mClips.size();++i) {
  566. Clip& clip = mClips[i];
  567. if (Clip::REF == clip.type) {
  568. if (clip.clipRef >= mClips.size()) {
  569. DefaultLogger::get()->error("LWO2: Clip referrer index is out of range");
  570. clip.clipRef = 0;
  571. }
  572. Clip& dest = mClips[clip.clipRef];
  573. if (Clip::REF == dest.type) {
  574. DefaultLogger::get()->error("LWO2: Clip references another clip reference");
  575. clip.type = Clip::UNSUPPORTED;
  576. }
  577. else {
  578. clip.path = dest.path;
  579. clip.type = dest.type;
  580. }
  581. }
  582. }
  583. }
  584. // ------------------------------------------------------------------------------------------------
  585. void LWOImporter::AdjustTexturePath(std::string& out)
  586. {
  587. // --- this function is used for both LWO2 and LWOB
  588. if (!mIsLWO2 && ::strstr(out.c_str(), "(sequence)")) {
  589. // remove the (sequence) and append 000
  590. DefaultLogger::get()->info("LWOB: Sequence of animated texture found. It will be ignored");
  591. out = out.substr(0,out.length()-10) + "000";
  592. }
  593. // format: drive:path/file - we just need to insert a slash after the drive
  594. std::string::size_type n = out.find_first_of(':');
  595. if (std::string::npos != n) {
  596. out.insert(n+1,"/");
  597. }
  598. }
  599. // ------------------------------------------------------------------------------------------------
  600. void LWOImporter::LoadLWOTags(unsigned int size)
  601. {
  602. // --- this function is used for both LWO2 and LWOB
  603. const char* szCur = (const char*)mFileBuffer, *szLast = szCur;
  604. const char* const szEnd = szLast+size;
  605. while (szCur < szEnd)
  606. {
  607. if (!(*szCur))
  608. {
  609. const size_t len = (size_t)(szCur-szLast);
  610. // FIX: skip empty-sized tags
  611. if (len)
  612. mTags->push_back(std::string(szLast,len));
  613. szCur += (len&0x1 ? 1 : 2);
  614. szLast = szCur;
  615. }
  616. szCur++;
  617. }
  618. }
  619. // ------------------------------------------------------------------------------------------------
  620. void LWOImporter::LoadLWOPoints(unsigned int length)
  621. {
  622. // --- this function is used for both LWO2 and LWOB but for
  623. // LWO2 we need to allocate 25% more storage - it could be we'll
  624. // need to duplicate some points later.
  625. const size_t vertexLen = 12;
  626. if ((length % vertexLen) != 0)
  627. {
  628. throw DeadlyImportError( "LWO2: Points chunk length is not multiple of vertexLen (12)");
  629. }
  630. unsigned int regularSize = (unsigned int)mCurLayer->mTempPoints.size() + length / 12;
  631. if (mIsLWO2)
  632. {
  633. mCurLayer->mTempPoints.reserve ( regularSize + (regularSize>>2u) );
  634. mCurLayer->mTempPoints.resize ( regularSize );
  635. // initialize all point referrers with the default values
  636. mCurLayer->mPointReferrers.reserve ( regularSize + (regularSize>>2u) );
  637. mCurLayer->mPointReferrers.resize ( regularSize, UINT_MAX );
  638. }
  639. else mCurLayer->mTempPoints.resize( regularSize );
  640. // perform endianess conversions
  641. #ifndef AI_BUILD_BIG_ENDIAN
  642. for (unsigned int i = 0; i < length>>2;++i)
  643. ByteSwap::Swap4( mFileBuffer + (i << 2));
  644. #endif
  645. ::memcpy(&mCurLayer->mTempPoints[0],mFileBuffer,length);
  646. }
  647. // ------------------------------------------------------------------------------------------------
  648. void LWOImporter::LoadLWO2Polygons(unsigned int length)
  649. {
  650. LE_NCONST uint16_t* const end = (LE_NCONST uint16_t*)(mFileBuffer+length);
  651. const uint32_t type = GetU4();
  652. // Determine the type of the polygons
  653. switch (type)
  654. {
  655. // read unsupported stuff too (although we wont process it)
  656. case AI_LWO_MBAL:
  657. DefaultLogger::get()->warn("LWO2: Encountered unsupported primitive chunk (METABALL)");
  658. break;
  659. case AI_LWO_CURV:
  660. DefaultLogger::get()->warn("LWO2: Encountered unsupported primitive chunk (SPLINE)");;
  661. break;
  662. // These are ok with no restrictions
  663. case AI_LWO_PTCH:
  664. case AI_LWO_FACE:
  665. case AI_LWO_BONE:
  666. case AI_LWO_SUBD:
  667. break;
  668. default:
  669. // hm!? wtf is this? ok ...
  670. DefaultLogger::get()->error("LWO2: Ignoring unknown polygon type.");
  671. break;
  672. }
  673. // first find out how many faces and vertices we'll finally need
  674. uint16_t* cursor= (uint16_t*)mFileBuffer;
  675. unsigned int iNumFaces = 0,iNumVertices = 0;
  676. CountVertsAndFacesLWO2(iNumVertices,iNumFaces,cursor,end);
  677. // allocate the output array and copy face indices
  678. if (iNumFaces)
  679. {
  680. cursor = (uint16_t*)mFileBuffer;
  681. mCurLayer->mFaces.resize(iNumFaces,LWO::Face(type));
  682. FaceList::iterator it = mCurLayer->mFaces.begin();
  683. CopyFaceIndicesLWO2(it,cursor,end);
  684. }
  685. }
  686. // ------------------------------------------------------------------------------------------------
  687. void LWOImporter::CountVertsAndFacesLWO2(unsigned int& verts, unsigned int& faces,
  688. uint16_t*& cursor, const uint16_t* const end, unsigned int max)
  689. {
  690. while (cursor < end && max--)
  691. {
  692. uint16_t numIndices;
  693. ::memcpy(&numIndices, cursor++, 2);
  694. AI_LSWAP2(numIndices);
  695. numIndices &= 0x03FF;
  696. verts += numIndices;
  697. ++faces;
  698. for(uint16_t i = 0; i < numIndices; i++)
  699. {
  700. ReadVSizedIntLWO2((uint8_t*&)cursor);
  701. }
  702. }
  703. }
  704. // ------------------------------------------------------------------------------------------------
  705. void LWOImporter::CopyFaceIndicesLWO2(FaceList::iterator& it,
  706. uint16_t*& cursor,
  707. const uint16_t* const end)
  708. {
  709. while (cursor < end)
  710. {
  711. LWO::Face& face = *it++;
  712. uint16_t numIndices;
  713. ::memcpy(&numIndices, cursor++, 2);
  714. AI_LSWAP2(numIndices);
  715. face.mNumIndices = numIndices & 0x03FF;
  716. if(face.mNumIndices) /* byte swapping has already been done */
  717. {
  718. face.mIndices = new unsigned int[face.mNumIndices];
  719. for(unsigned int i = 0; i < face.mNumIndices; i++)
  720. {
  721. face.mIndices[i] = ReadVSizedIntLWO2((uint8_t*&)cursor) + mCurLayer->mPointIDXOfs;
  722. if(face.mIndices[i] > mCurLayer->mTempPoints.size())
  723. {
  724. DefaultLogger::get()->warn("LWO2: Failure evaluating face record, index is out of range");
  725. face.mIndices[i] = (unsigned int)mCurLayer->mTempPoints.size()-1;
  726. }
  727. }
  728. }
  729. else throw DeadlyImportError("LWO2: Encountered invalid face record with zero indices");
  730. }
  731. }
  732. // ------------------------------------------------------------------------------------------------
  733. void LWOImporter::LoadLWO2PolygonTags(unsigned int length)
  734. {
  735. LE_NCONST uint8_t* const end = mFileBuffer+length;
  736. AI_LWO_VALIDATE_CHUNK_LENGTH(length,PTAG,4);
  737. uint32_t type = GetU4();
  738. if (type != AI_LWO_SURF && type != AI_LWO_SMGP)
  739. return;
  740. while (mFileBuffer < end)
  741. {
  742. unsigned int i = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  743. unsigned int j = GetU2();
  744. if (i >= mCurLayer->mFaces.size()) {
  745. DefaultLogger::get()->warn("LWO2: face index in PTAG is out of range");
  746. continue;
  747. }
  748. switch (type) {
  749. case AI_LWO_SURF:
  750. mCurLayer->mFaces[i].surfaceIndex = j;
  751. break;
  752. case AI_LWO_SMGP: /* is that really used? */
  753. mCurLayer->mFaces[i].smoothGroup = j;
  754. break;
  755. };
  756. }
  757. }
  758. // ------------------------------------------------------------------------------------------------
  759. template <class T>
  760. VMapEntry* FindEntry(std::vector< T >& list,const std::string& name, bool perPoly)
  761. {
  762. for (typename std::vector< T >::iterator it = list.begin(), end = list.end();it != end; ++it) {
  763. if ((*it).name == name) {
  764. if (!perPoly) {
  765. DefaultLogger::get()->warn("LWO2: Found two VMAP sections with equal names");
  766. }
  767. return &(*it);
  768. }
  769. }
  770. list.push_back( T() );
  771. VMapEntry* p = &list.back();
  772. p->name = name;
  773. return p;
  774. }
  775. // ------------------------------------------------------------------------------------------------
  776. template <class T>
  777. inline void CreateNewEntry(T& chan, unsigned int srcIdx)
  778. {
  779. if (!chan.name.length())
  780. return;
  781. chan.abAssigned[srcIdx] = true;
  782. chan.abAssigned.resize(chan.abAssigned.size()+1,false);
  783. for (unsigned int a = 0; a < chan.dims;++a)
  784. chan.rawData.push_back(chan.rawData[srcIdx*chan.dims+a]);
  785. }
  786. // ------------------------------------------------------------------------------------------------
  787. template <class T>
  788. inline void CreateNewEntry(std::vector< T >& list, unsigned int srcIdx)
  789. {
  790. for (typename std::vector< T >::iterator it = list.begin(), end = list.end();it != end;++it) {
  791. CreateNewEntry( *it, srcIdx );
  792. }
  793. }
  794. // ------------------------------------------------------------------------------------------------
  795. inline void LWOImporter::DoRecursiveVMAPAssignment(VMapEntry* base, unsigned int numRead,
  796. unsigned int idx, float* data)
  797. {
  798. ai_assert(NULL != data);
  799. LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
  800. unsigned int i;
  801. base->abAssigned[idx] = true;
  802. for (i = 0; i < numRead;++i) {
  803. base->rawData[idx*base->dims+i]= data[i];
  804. }
  805. if (UINT_MAX != (i = refList[idx])) {
  806. DoRecursiveVMAPAssignment(base,numRead,i,data);
  807. }
  808. }
  809. // ------------------------------------------------------------------------------------------------
  810. inline void AddToSingleLinkedList(ReferrerList& refList, unsigned int srcIdx, unsigned int destIdx)
  811. {
  812. if(UINT_MAX == refList[srcIdx]) {
  813. refList[srcIdx] = destIdx;
  814. return;
  815. }
  816. AddToSingleLinkedList(refList,refList[srcIdx],destIdx);
  817. }
  818. // ------------------------------------------------------------------------------------------------
  819. // Load LWO2 vertex map
  820. void LWOImporter::LoadLWO2VertexMap(unsigned int length, bool perPoly)
  821. {
  822. LE_NCONST uint8_t* const end = mFileBuffer+length;
  823. AI_LWO_VALIDATE_CHUNK_LENGTH(length,VMAP,6);
  824. unsigned int type = GetU4();
  825. unsigned int dims = GetU2();
  826. VMapEntry* base;
  827. // read the name of the vertex map
  828. std::string name;
  829. GetS0(name,length);
  830. switch (type)
  831. {
  832. case AI_LWO_TXUV:
  833. if (dims != 2) {
  834. DefaultLogger::get()->warn("LWO2: Skipping UV channel \'"
  835. + name + "\' with !2 components");
  836. return;
  837. }
  838. base = FindEntry(mCurLayer->mUVChannels,name,perPoly);
  839. break;
  840. case AI_LWO_WGHT:
  841. case AI_LWO_MNVW:
  842. if (dims != 1) {
  843. DefaultLogger::get()->warn("LWO2: Skipping Weight Channel \'"
  844. + name + "\' with !1 components");
  845. return;
  846. }
  847. base = FindEntry((type == AI_LWO_WGHT ? mCurLayer->mWeightChannels
  848. : mCurLayer->mSWeightChannels),name,perPoly);
  849. break;
  850. case AI_LWO_RGB:
  851. case AI_LWO_RGBA:
  852. if (dims != 3 && dims != 4) {
  853. DefaultLogger::get()->warn("LWO2: Skipping Color Map \'"
  854. + name + "\' with a dimension > 4 or < 3");
  855. return;
  856. }
  857. base = FindEntry(mCurLayer->mVColorChannels,name,perPoly);
  858. break;
  859. case AI_LWO_MODO_NORM:
  860. /* This is a non-standard extension chunk used by Luxology's MODO.
  861. * It stores per-vertex normals. This VMAP exists just once, has
  862. * 3 dimensions and is btw extremely beautiful.
  863. */
  864. if (name != "vert_normals" || dims != 3 || mCurLayer->mNormals.name.length())
  865. return;
  866. DefaultLogger::get()->info("Processing non-standard extension: MODO VMAP.NORM.vert_normals");
  867. mCurLayer->mNormals.name = name;
  868. base = & mCurLayer->mNormals;
  869. break;
  870. case AI_LWO_PICK: /* these VMAPs are just silently dropped */
  871. case AI_LWO_MORF:
  872. case AI_LWO_SPOT:
  873. return;
  874. default:
  875. if (name == "APS.Level") {
  876. // XXX handle this (seems to be subdivision-related).
  877. }
  878. DefaultLogger::get()->warn("LWO2: Skipping unknown VMAP/VMAD channel \'" + name + "\'");
  879. return;
  880. };
  881. base->Allocate((unsigned int)mCurLayer->mTempPoints.size());
  882. // now read all entries in the map
  883. type = std::min(dims,base->dims);
  884. const unsigned int diff = (dims - type)<<2u;
  885. LWO::FaceList& list = mCurLayer->mFaces;
  886. LWO::PointList& pointList = mCurLayer->mTempPoints;
  887. LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
  888. float temp[4];
  889. const unsigned int numPoints = (unsigned int)pointList.size();
  890. const unsigned int numFaces = (unsigned int)list.size();
  891. while (mFileBuffer < end) {
  892. unsigned int idx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mPointIDXOfs;
  893. if (idx >= numPoints) {
  894. DefaultLogger::get()->warn("LWO2: Failure evaluating VMAP/VMAD entry \'" + name + "\', vertex index is out of range");
  895. mFileBuffer += base->dims<<2u;
  896. continue;
  897. }
  898. if (perPoly) {
  899. unsigned int polyIdx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  900. if (base->abAssigned[idx]) {
  901. // we have already a VMAP entry for this vertex - thus
  902. // we need to duplicate the corresponding polygon.
  903. if (polyIdx >= numFaces) {
  904. DefaultLogger::get()->warn("LWO2: Failure evaluating VMAD entry \'" + name + "\', polygon index is out of range");
  905. mFileBuffer += base->dims<<2u;
  906. continue;
  907. }
  908. LWO::Face& src = list[polyIdx];
  909. // generate a new unique vertex for the corresponding index - but only
  910. // if we can find the index in the face
  911. bool had = false;
  912. for (unsigned int i = 0; i < src.mNumIndices;++i) {
  913. unsigned int srcIdx = src.mIndices[i], tmp = idx;
  914. do {
  915. if (tmp == srcIdx)
  916. break;
  917. }
  918. while ((tmp = refList[tmp]) != UINT_MAX);
  919. if (tmp == UINT_MAX) {
  920. continue;
  921. }
  922. had = true;
  923. refList.resize(refList.size()+1, UINT_MAX);
  924. idx = (unsigned int)pointList.size();
  925. src.mIndices[i] = (unsigned int)pointList.size();
  926. // store the index of the new vertex in the old vertex
  927. // so we get a single linked list we can traverse in
  928. // only one direction
  929. AddToSingleLinkedList(refList,srcIdx,src.mIndices[i]);
  930. pointList.push_back(pointList[srcIdx]);
  931. CreateNewEntry(mCurLayer->mVColorChannels, srcIdx );
  932. CreateNewEntry(mCurLayer->mUVChannels, srcIdx );
  933. CreateNewEntry(mCurLayer->mWeightChannels, srcIdx );
  934. CreateNewEntry(mCurLayer->mSWeightChannels, srcIdx );
  935. CreateNewEntry(mCurLayer->mNormals, srcIdx );
  936. }
  937. if (!had) {
  938. DefaultLogger::get()->warn("LWO2: Failure evaluating VMAD entry \'" + name + "\', vertex index wasn't found in that polygon");
  939. ai_assert(had);
  940. }
  941. }
  942. }
  943. for (unsigned int l = 0; l < type;++l)
  944. temp[l] = GetF4();
  945. DoRecursiveVMAPAssignment(base,type,idx, temp);
  946. mFileBuffer += diff;
  947. }
  948. }
  949. // ------------------------------------------------------------------------------------------------
  950. // Load LWO2 clip
  951. void LWOImporter::LoadLWO2Clip(unsigned int length)
  952. {
  953. AI_LWO_VALIDATE_CHUNK_LENGTH(length,CLIP,10);
  954. mClips.push_back(LWO::Clip());
  955. LWO::Clip& clip = mClips.back();
  956. // first - get the index of the clip
  957. clip.idx = GetU4();
  958. IFF::SubChunkHeader head = IFF::LoadSubChunk(mFileBuffer);
  959. switch (head.type)
  960. {
  961. case AI_LWO_STIL:
  962. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,STIL,1);
  963. // "Normal" texture
  964. GetS0(clip.path,head.length);
  965. clip.type = Clip::STILL;
  966. break;
  967. case AI_LWO_ISEQ:
  968. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,ISEQ,16);
  969. // Image sequence. We'll later take the first.
  970. {
  971. uint8_t digits = GetU1(); mFileBuffer++;
  972. int16_t offset = GetU2(); mFileBuffer+=4;
  973. int16_t start = GetU2(); mFileBuffer+=4;
  974. std::string s;
  975. std::ostringstream ss;
  976. GetS0(s,head.length);
  977. head.length -= (unsigned int)s.length()+1;
  978. ss << s;
  979. ss << std::setw(digits) << offset + start;
  980. GetS0(s,head.length);
  981. ss << s;
  982. clip.path = ss.str();
  983. clip.type = Clip::SEQ;
  984. }
  985. break;
  986. case AI_LWO_STCC:
  987. DefaultLogger::get()->warn("LWO2: Color shifted images are not supported");
  988. break;
  989. case AI_LWO_ANIM:
  990. DefaultLogger::get()->warn("LWO2: Animated textures are not supported");
  991. break;
  992. case AI_LWO_XREF:
  993. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,XREF,4);
  994. // Just a cross-reference to another CLIp
  995. clip.type = Clip::REF;
  996. clip.clipRef = GetU4();
  997. break;
  998. case AI_LWO_NEGA:
  999. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,NEGA,2);
  1000. clip.negate = (0 != GetU2());
  1001. break;
  1002. default:
  1003. DefaultLogger::get()->warn("LWO2: Encountered unknown CLIP subchunk");
  1004. }
  1005. }
  1006. // ------------------------------------------------------------------------------------------------
  1007. // Load envelope description
  1008. void LWOImporter::LoadLWO2Envelope(unsigned int length)
  1009. {
  1010. LE_NCONST uint8_t* const end = mFileBuffer + length;
  1011. AI_LWO_VALIDATE_CHUNK_LENGTH(length,ENVL,4);
  1012. mEnvelopes.push_back(LWO::Envelope());
  1013. LWO::Envelope& envelope = mEnvelopes.back();
  1014. // Get the index of the envelope
  1015. envelope.index = ReadVSizedIntLWO2(mFileBuffer);
  1016. // It looks like there might be an extra U4 right after the index,
  1017. // at least in modo (LXOB) files: we'll ignore it if it's zero,
  1018. // otherwise it represents the start of a subchunk, so we backtrack.
  1019. if (mIsLXOB)
  1020. {
  1021. uint32_t extra = GetU4();
  1022. if (extra)
  1023. {
  1024. mFileBuffer -= 4;
  1025. }
  1026. }
  1027. // ... and read all subchunks
  1028. while (true)
  1029. {
  1030. if (mFileBuffer + 6 >= end)break;
  1031. LE_NCONST IFF::SubChunkHeader head = IFF::LoadSubChunk(mFileBuffer);
  1032. if (mFileBuffer + head.length > end)
  1033. throw DeadlyImportError("LWO2: Invalid envelope chunk length");
  1034. uint8_t* const next = mFileBuffer+head.length;
  1035. switch (head.type)
  1036. {
  1037. // Type & representation of the envelope
  1038. case AI_LWO_TYPE:
  1039. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,TYPE,2);
  1040. mFileBuffer++; // skip user format
  1041. // Determine type of envelope
  1042. envelope.type = (LWO::EnvelopeType)*mFileBuffer;
  1043. ++mFileBuffer;
  1044. break;
  1045. // precondition
  1046. case AI_LWO_PRE:
  1047. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,PRE,2);
  1048. envelope.pre = (LWO::PrePostBehaviour)GetU2();
  1049. break;
  1050. // postcondition
  1051. case AI_LWO_POST:
  1052. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,POST,2);
  1053. envelope.post = (LWO::PrePostBehaviour)GetU2();
  1054. break;
  1055. // keyframe
  1056. case AI_LWO_KEY:
  1057. {
  1058. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,KEY,8);
  1059. envelope.keys.push_back(LWO::Key());
  1060. LWO::Key& key = envelope.keys.back();
  1061. key.time = GetF4();
  1062. key.value = GetF4();
  1063. break;
  1064. }
  1065. // interval interpolation
  1066. case AI_LWO_SPAN:
  1067. {
  1068. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,SPAN,4);
  1069. if (envelope.keys.size()<2)
  1070. DefaultLogger::get()->warn("LWO2: Unexpected SPAN chunk");
  1071. else {
  1072. LWO::Key& key = envelope.keys.back();
  1073. switch (GetU4())
  1074. {
  1075. case AI_LWO_STEP:
  1076. key.inter = LWO::IT_STEP;break;
  1077. case AI_LWO_LINE:
  1078. key.inter = LWO::IT_LINE;break;
  1079. case AI_LWO_TCB:
  1080. key.inter = LWO::IT_TCB;break;
  1081. case AI_LWO_HERM:
  1082. key.inter = LWO::IT_HERM;break;
  1083. case AI_LWO_BEZI:
  1084. key.inter = LWO::IT_BEZI;break;
  1085. case AI_LWO_BEZ2:
  1086. key.inter = LWO::IT_BEZ2;break;
  1087. default:
  1088. DefaultLogger::get()->warn("LWO2: Unknown interval interpolation mode");
  1089. };
  1090. // todo ... read params
  1091. }
  1092. break;
  1093. }
  1094. default:
  1095. DefaultLogger::get()->warn("LWO2: Encountered unknown ENVL subchunk");
  1096. }
  1097. // regardless how much we did actually read, go to the next chunk
  1098. mFileBuffer = next;
  1099. }
  1100. }
  1101. // ------------------------------------------------------------------------------------------------
  1102. // Load file - master function
  1103. void LWOImporter::LoadLWO2File()
  1104. {
  1105. bool skip = false;
  1106. LE_NCONST uint8_t* const end = mFileBuffer + fileSize;
  1107. while (true)
  1108. {
  1109. if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break;
  1110. const IFF::ChunkHeader head = IFF::LoadChunk(mFileBuffer);
  1111. if (mFileBuffer + head.length > end)
  1112. {
  1113. throw DeadlyImportError("LWO2: Chunk length points behind the file");
  1114. break;
  1115. }
  1116. uint8_t* const next = mFileBuffer+head.length;
  1117. unsigned int iUnnamed = 0;
  1118. if(!head.length) {
  1119. mFileBuffer = next;
  1120. continue;
  1121. }
  1122. switch (head.type)
  1123. {
  1124. // new layer
  1125. case AI_LWO_LAYR:
  1126. {
  1127. // add a new layer to the list ....
  1128. mLayers->push_back ( LWO::Layer() );
  1129. LWO::Layer& layer = mLayers->back();
  1130. mCurLayer = &layer;
  1131. AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,LAYR,16);
  1132. // layer index.
  1133. layer.mIndex = GetU2();
  1134. // Continue loading this layer or ignore it? Check the layer index property
  1135. if (UINT_MAX != configLayerIndex && (configLayerIndex-1) != layer.mIndex) {
  1136. skip = true;
  1137. }
  1138. else skip = false;
  1139. // pivot point
  1140. mFileBuffer += 2; /* unknown */
  1141. mCurLayer->mPivot.x = GetF4();
  1142. mCurLayer->mPivot.y = GetF4();
  1143. mCurLayer->mPivot.z = GetF4();
  1144. GetS0(layer.mName,head.length-16);
  1145. // if the name is empty, generate a default name
  1146. if (layer.mName.empty()) {
  1147. char buffer[128]; // should be sufficiently large
  1148. ::sprintf(buffer,"Layer_%i", iUnnamed++);
  1149. layer.mName = buffer;
  1150. }
  1151. // load this layer or ignore it? Check the layer name property
  1152. if (configLayerName.length() && configLayerName != layer.mName) {
  1153. skip = true;
  1154. }
  1155. else hasNamedLayer = true;
  1156. // optional: parent of this layer
  1157. if (mFileBuffer + 2 <= next)
  1158. layer.mParent = GetU2();
  1159. else layer.mParent = -1;
  1160. // Set layer skip parameter
  1161. layer.skip = skip;
  1162. break;
  1163. }
  1164. // vertex list
  1165. case AI_LWO_PNTS:
  1166. {
  1167. if (skip)
  1168. break;
  1169. unsigned int old = (unsigned int)mCurLayer->mTempPoints.size();
  1170. LoadLWOPoints(head.length);
  1171. mCurLayer->mPointIDXOfs = old;
  1172. break;
  1173. }
  1174. // vertex tags
  1175. case AI_LWO_VMAD:
  1176. if (mCurLayer->mFaces.empty())
  1177. {
  1178. DefaultLogger::get()->warn("LWO2: Unexpected VMAD chunk");
  1179. break;
  1180. }
  1181. // --- intentionally no break here
  1182. case AI_LWO_VMAP:
  1183. {
  1184. if (skip)
  1185. break;
  1186. if (mCurLayer->mTempPoints.empty())
  1187. DefaultLogger::get()->warn("LWO2: Unexpected VMAP chunk");
  1188. else LoadLWO2VertexMap(head.length,head.type == AI_LWO_VMAD);
  1189. break;
  1190. }
  1191. // face list
  1192. case AI_LWO_POLS:
  1193. {
  1194. if (skip)
  1195. break;
  1196. unsigned int old = (unsigned int)mCurLayer->mFaces.size();
  1197. LoadLWO2Polygons(head.length);
  1198. mCurLayer->mFaceIDXOfs = old;
  1199. break;
  1200. }
  1201. // polygon tags
  1202. case AI_LWO_PTAG:
  1203. {
  1204. if (skip)
  1205. break;
  1206. if (mCurLayer->mFaces.empty())
  1207. DefaultLogger::get()->warn("LWO2: Unexpected PTAG");
  1208. else LoadLWO2PolygonTags(head.length);
  1209. break;
  1210. }
  1211. // list of tags
  1212. case AI_LWO_TAGS:
  1213. {
  1214. if (!mTags->empty())
  1215. DefaultLogger::get()->warn("LWO2: SRFS chunk encountered twice");
  1216. else LoadLWOTags(head.length);
  1217. break;
  1218. }
  1219. // surface chunk
  1220. case AI_LWO_SURF:
  1221. {
  1222. LoadLWO2Surface(head.length);
  1223. break;
  1224. }
  1225. // clip chunk
  1226. case AI_LWO_CLIP:
  1227. {
  1228. LoadLWO2Clip(head.length);
  1229. break;
  1230. }
  1231. // envelope chunk
  1232. case AI_LWO_ENVL:
  1233. {
  1234. LoadLWO2Envelope(head.length);
  1235. break;
  1236. }
  1237. }
  1238. mFileBuffer = next;
  1239. }
  1240. }
  1241. #endif // !! ASSIMP_BUILD_NO_LWO_IMPORTER