LWOLoader.cpp 44 KB

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