LWOLoader.cpp 45 KB

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