3DSLoader.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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 3DSLoader.cpp
  35. * @brief Implementation of the 3ds importer class
  36. *
  37. * http://www.the-labs.com/Blender/3DS-details.html
  38. */
  39. #include "AssimpPCH.h"
  40. #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
  41. // internal headers
  42. #include "3DSLoader.h"
  43. using namespace Assimp;
  44. // ------------------------------------------------------------------------------------------------
  45. // Begins a new parsing block
  46. // - Reads the current chunk and validates it
  47. // - computes its length
  48. #define ASSIMP_3DS_BEGIN_CHUNK() \
  49. if (stream->GetRemainingSizeToLimit() < sizeof(Discreet3DS::Chunk)) \
  50. return; \
  51. Discreet3DS::Chunk chunk; \
  52. ReadChunk(&chunk); \
  53. int chunkSize = chunk.Size-sizeof(Discreet3DS::Chunk); \
  54. const int oldReadLimit = stream->GetReadLimit(); \
  55. stream->SetReadLimit(stream->GetCurrentPos() + chunkSize);
  56. // ------------------------------------------------------------------------------------------------
  57. // End a parsing block
  58. // Must follow at the end of each parsing block, reset chunk end marker to previous value
  59. #define ASSIMP_3DS_END_CHUNK() \
  60. stream->SkipToReadLimit(); \
  61. stream->SetReadLimit(oldReadLimit); \
  62. if (stream->GetRemainingSizeToLimit() == 0) \
  63. return;
  64. // ------------------------------------------------------------------------------------------------
  65. // Constructor to be privately used by Importer
  66. Discreet3DSImporter::Discreet3DSImporter()
  67. {}
  68. // ------------------------------------------------------------------------------------------------
  69. // Destructor, private as well
  70. Discreet3DSImporter::~Discreet3DSImporter()
  71. {}
  72. // ------------------------------------------------------------------------------------------------
  73. // Returns whether the class can handle the format of the given file.
  74. bool Discreet3DSImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  75. {
  76. std::string extension = GetExtension(pFile);
  77. if(extension == "3ds" || extension == "prj" ) {
  78. return true;
  79. }
  80. if (!extension.length() || checkSig) {
  81. uint16_t token[3];
  82. token[0] = 0x4d4d;
  83. token[1] = 0x3dc2;
  84. //token[2] = 0x3daa;
  85. return CheckMagicToken(pIOHandler,pFile,token,2,0,2);
  86. }
  87. return false;
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. // Get list of all extension supported by this loader
  91. void Discreet3DSImporter::GetExtensionList(std::string& append)
  92. {
  93. append.append("*.3ds;*.prj");
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // Setup configuration properties
  97. void Discreet3DSImporter::SetupProperties(const Importer* pImp)
  98. {
  99. // nothing to be done for the moment
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. // Imports the given file into the given scene structure.
  103. void Discreet3DSImporter::InternReadFile( const std::string& pFile,
  104. aiScene* pScene, IOSystem* pIOHandler)
  105. {
  106. StreamReaderLE stream(pIOHandler->Open(pFile,"rb"));
  107. this->stream = &stream;
  108. // We should have at least one chunk
  109. if (stream.GetRemainingSize() < 16)
  110. throw new ImportErrorException("3DS file is either empty or corrupt: " + pFile);
  111. // Allocate our temporary 3DS representation
  112. mScene = new D3DS::Scene();
  113. // Initialize members
  114. mLastNodeIndex = -1;
  115. mCurrentNode = new D3DS::Node();
  116. mRootNode = mCurrentNode;
  117. mRootNode->mHierarchyPos = -1;
  118. mRootNode->mHierarchyIndex = -1;
  119. mRootNode->mParent = NULL;
  120. mMasterScale = 1.0f;
  121. mBackgroundImage = "";
  122. bHasBG = false;
  123. bIsPrj = false;
  124. // Parse the file
  125. ParseMainChunk();
  126. // Process all meshes in the file. First check whether all
  127. // face indices haev valid values. The generate our
  128. // internal verbose representation. Finally compute normal
  129. // vectors from the smoothing groups we read from the
  130. // file.
  131. for (std::vector<D3DS::Mesh>::iterator i = mScene->mMeshes.begin(),
  132. end = mScene->mMeshes.end(); i != end;++i) {
  133. CheckIndices(*i);
  134. MakeUnique (*i);
  135. ComputeNormalsWithSmoothingsGroups<D3DS::Face>(*i);
  136. }
  137. // Replace all occurences of the default material with a
  138. // valid material. Generate it if no material containing
  139. // DEFAULT in its name has been found in the file
  140. ReplaceDefaultMaterial();
  141. // Convert the scene from our internal representation to an
  142. // aiScene object. This involves copying all meshes, lights
  143. // and cameras to the scene
  144. ConvertScene(pScene);
  145. // Generate the node graph for the scene. This is a little bit
  146. // tricky since we'll need to split some meshes into submeshes
  147. GenerateNodeGraph(pScene);
  148. // Now apply the master scaling factor to the scene
  149. ApplyMasterScale(pScene);
  150. // Delete our internal scene representation and the root
  151. // node, so the whole hierarchy will follow
  152. delete mRootNode;
  153. delete mScene;
  154. AI_DEBUG_INVALIDATE_PTR(mRootNode);
  155. AI_DEBUG_INVALIDATE_PTR(mScene);
  156. AI_DEBUG_INVALIDATE_PTR(this->stream);
  157. }
  158. // ------------------------------------------------------------------------------------------------
  159. // Applies a master-scaling factor to the imported scene
  160. void Discreet3DSImporter::ApplyMasterScale(aiScene* pScene)
  161. {
  162. // There are some 3DS files with a zero scaling factor
  163. if (!mMasterScale)mMasterScale = 1.0f;
  164. else mMasterScale = 1.0f / mMasterScale;
  165. // Construct an uniform scaling matrix and multiply with it
  166. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  167. mMasterScale,0.0f, 0.0f, 0.0f,
  168. 0.0f, mMasterScale,0.0f, 0.0f,
  169. 0.0f, 0.0f, mMasterScale,0.0f,
  170. 0.0f, 0.0f, 0.0f, 1.0f);
  171. // Check whether a scaling track is assigned to the root node.
  172. }
  173. // ------------------------------------------------------------------------------------------------
  174. // Reads a new chunk from the file
  175. void Discreet3DSImporter::ReadChunk(Discreet3DS::Chunk* pcOut)
  176. {
  177. ai_assert(pcOut != NULL);
  178. pcOut->Flag = stream->GetI2();
  179. pcOut->Size = stream->GetI4();
  180. if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSize())
  181. throw new ImportErrorException("Chunk is too large");
  182. if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSizeToLimit())
  183. DefaultLogger::get()->error("3DS: Chunk overflow");
  184. }
  185. // ------------------------------------------------------------------------------------------------
  186. // Skip a chunk
  187. void Discreet3DSImporter::SkipChunk()
  188. {
  189. Discreet3DS::Chunk psChunk;
  190. ReadChunk(&psChunk);
  191. stream->IncPtr(psChunk.Size-sizeof(Discreet3DS::Chunk));
  192. return;
  193. }
  194. // ------------------------------------------------------------------------------------------------
  195. // Process the primary chunk of the file
  196. void Discreet3DSImporter::ParseMainChunk()
  197. {
  198. ASSIMP_3DS_BEGIN_CHUNK();
  199. // get chunk type
  200. switch (chunk.Flag)
  201. {
  202. case Discreet3DS::CHUNK_PRJ:
  203. bIsPrj = true;
  204. case Discreet3DS::CHUNK_MAIN:
  205. ParseEditorChunk();
  206. break;
  207. };
  208. ASSIMP_3DS_END_CHUNK();
  209. // recursively continue processing this hierarchy level
  210. return ParseMainChunk();
  211. }
  212. // ------------------------------------------------------------------------------------------------
  213. void Discreet3DSImporter::ParseEditorChunk()
  214. {
  215. ASSIMP_3DS_BEGIN_CHUNK();
  216. // get chunk type
  217. switch (chunk.Flag)
  218. {
  219. case Discreet3DS::CHUNK_OBJMESH:
  220. ParseObjectChunk();
  221. break;
  222. // NOTE: In several documentations in the internet this
  223. // chunk appears at different locations
  224. case Discreet3DS::CHUNK_KEYFRAMER:
  225. ParseKeyframeChunk();
  226. break;
  227. case Discreet3DS::CHUNK_VERSION:
  228. {
  229. // print the version number
  230. char buff[10];
  231. ASSIMP_itoa10(buff,stream->GetI2());
  232. DefaultLogger::get()->info(std::string("3DS file format version: ") + buff);
  233. }
  234. break;
  235. };
  236. ASSIMP_3DS_END_CHUNK();
  237. // recursively continue processing this hierarchy level
  238. return ParseEditorChunk();
  239. }
  240. // ------------------------------------------------------------------------------------------------
  241. void Discreet3DSImporter::ParseObjectChunk()
  242. {
  243. ASSIMP_3DS_BEGIN_CHUNK();
  244. // get chunk type
  245. switch (chunk.Flag)
  246. {
  247. case Discreet3DS::CHUNK_OBJBLOCK:
  248. {
  249. unsigned int cnt = 0;
  250. const char* sz = (const char*)stream->GetPtr();
  251. // Get the name of the geometry object
  252. while (stream->GetI1())++cnt;
  253. ParseChunk(sz,cnt);
  254. }
  255. break;
  256. case Discreet3DS::CHUNK_MAT_MATERIAL:
  257. // Add a new material to the list
  258. mScene->mMaterials.push_back(D3DS::Material());
  259. ParseMaterialChunk();
  260. break;
  261. case Discreet3DS::CHUNK_AMBCOLOR:
  262. // This is the ambient base color of the scene.
  263. // We add it to the ambient color of all materials
  264. ParseColorChunk(&mClrAmbient,true);
  265. if (is_qnan(mClrAmbient.r))
  266. {
  267. // We failed to read the ambient base color.
  268. DefaultLogger::get()->error("3DS: Failed to read ambient base color");
  269. mClrAmbient.r = mClrAmbient.g = mClrAmbient.b = 0.0f;
  270. }
  271. break;
  272. case Discreet3DS::CHUNK_BIT_MAP:
  273. {
  274. // Specifies the background image. The string should already be
  275. // properly 0 terminated but we need to be sure
  276. unsigned int cnt = 0;
  277. const char* sz = (const char*)stream->GetPtr();
  278. while (stream->GetI1())++cnt;
  279. mBackgroundImage = std::string(sz,cnt);
  280. }
  281. break;
  282. case Discreet3DS::CHUNK_BIT_MAP_EXISTS:
  283. bHasBG = true;
  284. break;
  285. case Discreet3DS::CHUNK_MASTER_SCALE:
  286. // Scene master scaling factor
  287. mMasterScale = stream->GetF4();
  288. break;
  289. };
  290. ASSIMP_3DS_END_CHUNK();
  291. // recursively continue processing this hierarchy level
  292. return ParseObjectChunk();
  293. }
  294. // ------------------------------------------------------------------------------------------------
  295. void Discreet3DSImporter::ParseChunk(const char* name, unsigned int num)
  296. {
  297. ASSIMP_3DS_BEGIN_CHUNK();
  298. // IMPLEMENTATION NOTE;
  299. // Cameras or lights define their transformation in their parent node and in the
  300. // corresponding light or camera chunks. However, we read and process the latter
  301. // to to be able to return valid cameras/lights even if no scenegraph is given.
  302. // get chunk type
  303. switch (chunk.Flag)
  304. {
  305. case Discreet3DS::CHUNK_TRIMESH:
  306. {
  307. // this starts a new triangle mesh
  308. mScene->mMeshes.push_back(D3DS::Mesh());
  309. D3DS::Mesh& m = mScene->mMeshes.back();
  310. // Setup the name of the mesh
  311. m.mName = std::string(name, num);
  312. // Read mesh chunks
  313. ParseMeshChunk();
  314. }
  315. break;
  316. case Discreet3DS::CHUNK_LIGHT:
  317. {
  318. // This starts a new light
  319. aiLight* light = new aiLight();
  320. mScene->mLights.push_back(light);
  321. light->mName.Set(std::string(name, num));
  322. // First read the position of the light
  323. light->mPosition.x = stream->GetF4();
  324. light->mPosition.y = stream->GetF4();
  325. light->mPosition.z = stream->GetF4();
  326. light->mColorDiffuse = aiColor3D(1.f,1.f,1.f);
  327. // Now check for further subchunks
  328. if (!bIsPrj) /* fixme */
  329. ParseLightChunk();
  330. // The specular light color is identical the the diffuse light color. The ambient light color
  331. // is equal to the ambient base color of the whole scene.
  332. light->mColorSpecular = light->mColorDiffuse;
  333. light->mColorAmbient = mClrAmbient;
  334. if (light->mType == aiLightSource_UNDEFINED)
  335. {
  336. // It must be a point light
  337. light->mType = aiLightSource_POINT;
  338. }}
  339. break;
  340. case Discreet3DS::CHUNK_CAMERA:
  341. {
  342. // This starts a new camera
  343. aiCamera* camera = new aiCamera();
  344. mScene->mCameras.push_back(camera);
  345. camera->mName.Set(std::string(name, num));
  346. // First read the position of the camera
  347. camera->mPosition.x = stream->GetF4();
  348. camera->mPosition.y = stream->GetF4();
  349. camera->mPosition.z = stream->GetF4();
  350. // Then the camera target
  351. camera->mLookAt.x = stream->GetF4() - camera->mPosition.x;
  352. camera->mLookAt.y = stream->GetF4() - camera->mPosition.y;
  353. camera->mLookAt.z = stream->GetF4() - camera->mPosition.z;
  354. float len = camera->mLookAt.Length();
  355. if (len < 1e-5f) {
  356. // There are some files with lookat == position. Don't know why or whether it's ok or not.
  357. DefaultLogger::get()->error("3DS: Unable to read proper camera look-at vector");
  358. camera->mLookAt = aiVector3D(0.f,1.f,0.f);
  359. }
  360. else camera->mLookAt /= len;
  361. // And finally - the camera rotation angle, in counter clockwise direction
  362. const float angle = AI_DEG_TO_RAD( stream->GetF4() );
  363. aiQuaternion quat(camera->mLookAt,angle);
  364. camera->mUp = quat.GetMatrix() * aiVector3D(0.f,1.f,0.f);
  365. // Read the lense angle
  366. camera->mHorizontalFOV = AI_DEG_TO_RAD ( stream->GetF4() );
  367. if (camera->mHorizontalFOV < 0.001f)
  368. camera->mHorizontalFOV = AI_DEG_TO_RAD(45.f);
  369. }
  370. // Now check for further subchunks
  371. if (!bIsPrj) /* fixme */
  372. ParseCameraChunk();
  373. break;
  374. };
  375. ASSIMP_3DS_END_CHUNK();
  376. // recursively continue processing this hierarchy level
  377. return ParseChunk(name,num);
  378. }
  379. // ------------------------------------------------------------------------------------------------
  380. void Discreet3DSImporter::ParseLightChunk()
  381. {
  382. ASSIMP_3DS_BEGIN_CHUNK();
  383. aiLight* light = mScene->mLights.back();
  384. // get chunk type
  385. switch (chunk.Flag)
  386. {
  387. case Discreet3DS::CHUNK_DL_SPOTLIGHT:
  388. // Now we can be sure that the light is a spot light
  389. light->mType = aiLightSource_SPOT;
  390. // We wouldn't need to normalize here, but we do it
  391. light->mDirection.x = stream->GetF4() - light->mPosition.x;
  392. light->mDirection.y = stream->GetF4() - light->mPosition.y;
  393. light->mDirection.z = stream->GetF4() - light->mPosition.z;
  394. light->mDirection.Normalize();
  395. // Now the hotspot and falloff angles - in degrees
  396. light->mAngleInnerCone = AI_DEG_TO_RAD( stream->GetF4() );
  397. // FIX: the falloff angle is just an offset
  398. light->mAngleOuterCone = light->mAngleInnerCone+AI_DEG_TO_RAD( stream->GetF4() );
  399. break;
  400. // intensity multiplier
  401. case Discreet3DS::CHUNK_DL_MULTIPLIER:
  402. light->mColorDiffuse = light->mColorDiffuse * stream->GetF4();
  403. break;
  404. // light color
  405. case Discreet3DS::CHUNK_RGBF:
  406. case Discreet3DS::CHUNK_LINRGBF:
  407. light->mColorDiffuse.r *= stream->GetF4();
  408. light->mColorDiffuse.g *= stream->GetF4();
  409. light->mColorDiffuse.b *= stream->GetF4();
  410. break;
  411. // light attenuation
  412. case Discreet3DS::CHUNK_DL_ATTENUATE:
  413. light->mAttenuationLinear = stream->GetF4();
  414. break;
  415. };
  416. ASSIMP_3DS_END_CHUNK();
  417. // recursively continue processing this hierarchy level
  418. return ParseLightChunk();
  419. }
  420. // ------------------------------------------------------------------------------------------------
  421. void Discreet3DSImporter::ParseCameraChunk()
  422. {
  423. ASSIMP_3DS_BEGIN_CHUNK();
  424. aiCamera* camera = mScene->mCameras.back();
  425. // get chunk type
  426. switch (chunk.Flag)
  427. {
  428. // near and far clip plane
  429. case Discreet3DS::CHUNK_CAM_RANGES:
  430. camera->mClipPlaneNear = stream->GetF4();
  431. camera->mClipPlaneFar = stream->GetF4();
  432. break;
  433. }
  434. ASSIMP_3DS_END_CHUNK();
  435. // recursively continue processing this hierarchy level
  436. return ParseCameraChunk();
  437. }
  438. // ------------------------------------------------------------------------------------------------
  439. void Discreet3DSImporter::ParseKeyframeChunk()
  440. {
  441. ASSIMP_3DS_BEGIN_CHUNK();
  442. // get chunk type
  443. switch (chunk.Flag)
  444. {
  445. case Discreet3DS::CHUNK_TRACKCAMTGT:
  446. case Discreet3DS::CHUNK_TRACKSPOTL:
  447. case Discreet3DS::CHUNK_TRACKCAMERA:
  448. case Discreet3DS::CHUNK_TRACKINFO:
  449. case Discreet3DS::CHUNK_TRACKLIGHT:
  450. case Discreet3DS::CHUNK_TRACKLIGTGT:
  451. // this starts a new mesh hierarchy chunk
  452. ParseHierarchyChunk(chunk.Flag);
  453. break;
  454. };
  455. ASSIMP_3DS_END_CHUNK();
  456. // recursively continue processing this hierarchy level
  457. return ParseKeyframeChunk();
  458. }
  459. // ------------------------------------------------------------------------------------------------
  460. // Little helper function for ParseHierarchyChunk
  461. void Discreet3DSImporter::InverseNodeSearch(D3DS::Node* pcNode,D3DS::Node* pcCurrent)
  462. {
  463. if (!pcCurrent) {
  464. mRootNode->push_back(pcNode);
  465. return;
  466. }
  467. if (pcCurrent->mHierarchyPos == pcNode->mHierarchyPos) {
  468. if(pcCurrent->mParent)
  469. pcCurrent->mParent->push_back(pcNode);
  470. else pcCurrent->push_back(pcNode);
  471. return;
  472. }
  473. return InverseNodeSearch(pcNode,pcCurrent->mParent);
  474. }
  475. // ------------------------------------------------------------------------------------------------
  476. // Find a node with a specific name in the import hierarchy
  477. D3DS::Node* FindNode(D3DS::Node* root, const std::string& name)
  478. {
  479. if (root->mName == name)
  480. return root;
  481. for (std::vector<D3DS::Node*>::iterator it = root->mChildren.begin();it != root->mChildren.end(); ++it) {
  482. D3DS::Node* nd;
  483. if (( nd = FindNode(*it,name)))
  484. return nd;
  485. }
  486. return NULL;
  487. }
  488. // ------------------------------------------------------------------------------------------------
  489. // Binary predicate for std::unique()
  490. template <class T>
  491. bool KeyUniqueCompare(const T& first, const T& second)
  492. {
  493. return first.mTime == second.mTime;
  494. }
  495. // ------------------------------------------------------------------------------------------------
  496. // Skip some additional import data.
  497. void Discreet3DSImporter::SkipTCBInfo()
  498. {
  499. unsigned int flags = stream->GetI2();
  500. if (!flags) {
  501. // Currently we can't do anything with these values. They occur
  502. // quite rare, so it wouldn't be worth the effort implementing
  503. // them. 3DS ist not really suitable for complex animations,
  504. // so full support is not required.
  505. DefaultLogger::get()->warn("3DS: Skipping TCB animation info");
  506. }
  507. if (flags & Discreet3DS::KEY_USE_TENS)
  508. stream->IncPtr(4);
  509. if (flags & Discreet3DS::KEY_USE_BIAS)
  510. stream->IncPtr(4);
  511. if (flags & Discreet3DS::KEY_USE_CONT)
  512. stream->IncPtr(4);
  513. if (flags & Discreet3DS::KEY_USE_EASE_FROM)
  514. stream->IncPtr(4);
  515. if (flags & Discreet3DS::KEY_USE_EASE_TO)
  516. stream->IncPtr(4);
  517. }
  518. // ------------------------------------------------------------------------------------------------
  519. // Read hierarchy and keyframe info
  520. void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent)
  521. {
  522. ASSIMP_3DS_BEGIN_CHUNK();
  523. // get chunk type
  524. switch (chunk.Flag)
  525. {
  526. case Discreet3DS::CHUNK_TRACKOBJNAME:
  527. // This is the name of the object to which the track applies. The chunk also
  528. // defines the position of this object in the hierarchy.
  529. {
  530. // First of all: get the name of the object
  531. unsigned int cnt = 0;
  532. const char* sz = (const char*)stream->GetPtr();
  533. while (stream->GetI1())++cnt;
  534. std::string name = std::string(sz,cnt);
  535. // Now find out whether we have this node already (target animation channels
  536. // are stored with a separate object ID)
  537. D3DS::Node* pcNode = FindNode(mRootNode,name);
  538. if (pcNode)
  539. {
  540. // Make this node the current node
  541. mCurrentNode = pcNode;
  542. break;
  543. }
  544. pcNode = new D3DS::Node();
  545. pcNode->mName = name;
  546. // There are two unknown values which we can safely ignore
  547. stream->IncPtr(4);
  548. // Now read the hierarchy position of the object
  549. uint16_t hierarchy = stream->GetI2() + 1;
  550. pcNode->mHierarchyPos = hierarchy;
  551. pcNode->mHierarchyIndex = mLastNodeIndex;
  552. // And find a proper position in the graph for it
  553. if (mCurrentNode && mCurrentNode->mHierarchyPos == hierarchy)
  554. {
  555. // add to the parent of the last touched node
  556. mCurrentNode->mParent->push_back(pcNode);
  557. mLastNodeIndex++;
  558. }
  559. else if(hierarchy >= mLastNodeIndex)
  560. {
  561. // place it at the current position in the hierarchy
  562. mCurrentNode->push_back(pcNode);
  563. mLastNodeIndex = hierarchy;
  564. }
  565. else
  566. {
  567. // need to go back to the specified position in the hierarchy.
  568. InverseNodeSearch(pcNode,mCurrentNode);
  569. mLastNodeIndex++;
  570. }
  571. // Make this node the current node
  572. mCurrentNode = pcNode;
  573. }
  574. break;
  575. case Discreet3DS::CHUNK_TRACKDUMMYOBJNAME:
  576. // This is the "real" name of a $$$DUMMY object
  577. {
  578. const char* sz = (const char*) stream->GetPtr();
  579. while (stream->GetI1());
  580. // If object name is DUMMY, take this one instead
  581. if (mCurrentNode->mName == "$$$DUMMY") {
  582. //DefaultLogger::get()->warn("3DS: Skipping dummy object name for non-dummy object");
  583. mCurrentNode->mName = std::string(sz);
  584. break;
  585. }
  586. }
  587. break;
  588. case Discreet3DS::CHUNK_TRACKPIVOT:
  589. if ( Discreet3DS::CHUNK_TRACKINFO != parent)
  590. {
  591. DefaultLogger::get()->warn("3DS: Skipping pivot subchunk for non usual object");
  592. break;
  593. }
  594. // Pivot = origin of rotation and scaling
  595. mCurrentNode->vPivot.x = stream->GetF4();
  596. mCurrentNode->vPivot.y = stream->GetF4();
  597. mCurrentNode->vPivot.z = stream->GetF4();
  598. break;
  599. // ////////////////////////////////////////////////////////////////////
  600. // POSITION KEYFRAME
  601. case Discreet3DS::CHUNK_TRACKPOS:
  602. {
  603. stream->IncPtr(10);
  604. const unsigned int numFrames = stream->GetI4();
  605. bool sortKeys = false;
  606. // This could also be meant as the target position for
  607. // (targeted) lights and cameras
  608. std::vector<aiVectorKey>* l;
  609. if ( Discreet3DS::CHUNK_TRACKCAMTGT == parent || Discreet3DS::CHUNK_TRACKLIGTGT == parent)
  610. {
  611. l = & mCurrentNode->aTargetPositionKeys;
  612. }
  613. else l = & mCurrentNode->aPositionKeys;
  614. l->reserve(numFrames);
  615. for (unsigned int i = 0; i < numFrames;++i)
  616. {
  617. const unsigned int fidx = stream->GetI4();
  618. // Setup a new position key
  619. aiVectorKey v;
  620. v.mTime = (double)fidx;
  621. SkipTCBInfo();
  622. v.mValue.x = stream->GetF4();
  623. v.mValue.y = stream->GetF4();
  624. v.mValue.z = stream->GetF4();
  625. // check whether we'll need to sort the keys
  626. if (!l->empty() && v.mTime <= l->back().mTime)
  627. sortKeys = true;
  628. // Add the new keyframe to the list
  629. l->push_back(v);
  630. }
  631. // Sort all keys with ascending time values and remove duplicates?
  632. if (sortKeys)
  633. {
  634. std::stable_sort(l->begin(),l->end());
  635. l->erase ( std::unique (l->begin(),l->end(),&KeyUniqueCompare<aiVectorKey>), l->end() );
  636. }}
  637. break;
  638. // ////////////////////////////////////////////////////////////////////
  639. // CAMERA ROLL KEYFRAME
  640. case Discreet3DS::CHUNK_TRACKROLL:
  641. {
  642. // roll keys are accepted for cameras only
  643. if (parent != Discreet3DS::CHUNK_TRACKCAMERA)
  644. {
  645. DefaultLogger::get()->warn("3DS: Ignoring roll track for non-camera object");
  646. break;
  647. }
  648. bool sortKeys = false;
  649. std::vector<aiFloatKey>* l = &mCurrentNode->aCameraRollKeys;
  650. stream->IncPtr(10);
  651. const unsigned int numFrames = stream->GetI4();
  652. l->reserve(numFrames);
  653. for (unsigned int i = 0; i < numFrames;++i)
  654. {
  655. const unsigned int fidx = stream->GetI4();
  656. // Setup a new position key
  657. aiFloatKey v;
  658. v.mTime = (double)fidx;
  659. // This is just a single float
  660. SkipTCBInfo();
  661. v.mValue = stream->GetF4();
  662. // Check whether we'll need to sort the keys
  663. if (!l->empty() && v.mTime <= l->back().mTime)
  664. sortKeys = true;
  665. // Add the new keyframe to the list
  666. l->push_back(v);
  667. }
  668. // Sort all keys with ascending time values and remove duplicates?
  669. if (sortKeys)
  670. {
  671. std::stable_sort(l->begin(),l->end());
  672. l->erase ( std::unique (l->begin(),l->end(),&KeyUniqueCompare<aiFloatKey>), l->end() );
  673. }}
  674. break;
  675. // ////////////////////////////////////////////////////////////////////
  676. // CAMERA FOV KEYFRAME
  677. case Discreet3DS::CHUNK_TRACKFOV:
  678. {
  679. DefaultLogger::get()->error("3DS: Skipping FOV animation track. "
  680. "This is not supported");
  681. }
  682. break;
  683. // ////////////////////////////////////////////////////////////////////
  684. // ROTATION KEYFRAME
  685. case Discreet3DS::CHUNK_TRACKROTATE:
  686. {
  687. stream->IncPtr(10);
  688. const unsigned int numFrames = stream->GetI4();
  689. bool sortKeys = false;
  690. std::vector<aiQuatKey>* l = &mCurrentNode->aRotationKeys;
  691. l->reserve(numFrames);
  692. for (unsigned int i = 0; i < numFrames;++i)
  693. {
  694. const unsigned int fidx = stream->GetI4();
  695. SkipTCBInfo();
  696. aiQuatKey v;
  697. v.mTime = (double)fidx;
  698. // The rotation keyframe is given as an axis-angle pair
  699. const float rad = stream->GetF4();
  700. aiVector3D axis;
  701. axis.x = stream->GetF4();
  702. axis.y = stream->GetF4();
  703. axis.z = stream->GetF4();
  704. if (!axis.x && !axis.y && !axis.z)
  705. axis.y = 1.f;
  706. // Construct a rotation quaternion from the axis-angle pair
  707. v.mValue = aiQuaternion(axis,rad);
  708. // Check whether we'll need to sort the keys
  709. if (!l->empty() && v.mTime <= l->back().mTime)
  710. sortKeys = true;
  711. // add the new keyframe to the list
  712. l->push_back(v);
  713. }
  714. // Sort all keys with ascending time values and remove duplicates?
  715. if (sortKeys)
  716. {
  717. std::stable_sort(l->begin(),l->end());
  718. l->erase ( std::unique (l->begin(),l->end(),&KeyUniqueCompare<aiQuatKey>), l->end() );
  719. }}
  720. break;
  721. // ////////////////////////////////////////////////////////////////////
  722. // SCALING KEYFRAME
  723. case Discreet3DS::CHUNK_TRACKSCALE:
  724. {
  725. stream->IncPtr(10);
  726. const unsigned int numFrames = stream->GetI2();
  727. stream->IncPtr(2);
  728. bool sortKeys = false;
  729. std::vector<aiVectorKey>* l = &mCurrentNode->aScalingKeys;
  730. l->reserve(numFrames);
  731. for (unsigned int i = 0; i < numFrames;++i)
  732. {
  733. const unsigned int fidx = stream->GetI4();
  734. SkipTCBInfo();
  735. // Setup a new key
  736. aiVectorKey v;
  737. v.mTime = (double)fidx;
  738. // ... and read its value
  739. v.mValue.x = stream->GetF4();
  740. v.mValue.y = stream->GetF4();
  741. v.mValue.z = stream->GetF4();
  742. // check whether we'll need to sort the keys
  743. if (!l->empty() && v.mTime <= l->back().mTime)
  744. sortKeys = true;
  745. // Remove zero-scalings
  746. if (!v.mValue.x)v.mValue.x = 1.f;
  747. if (!v.mValue.y)v.mValue.y = 1.f;
  748. if (!v.mValue.z)v.mValue.z = 1.f;
  749. l->push_back(v);
  750. }
  751. // Sort all keys with ascending time values and remove duplicates?
  752. if (sortKeys)
  753. {
  754. std::stable_sort(l->begin(),l->end());
  755. l->erase ( std::unique (l->begin(),l->end(),&KeyUniqueCompare<aiVectorKey>), l->end() );
  756. }}
  757. break;
  758. };
  759. ASSIMP_3DS_END_CHUNK();
  760. // recursively continue processing this hierarchy level
  761. return ParseHierarchyChunk(parent);
  762. }
  763. // ------------------------------------------------------------------------------------------------
  764. // Read a face chunk - it contains smoothing groups and material assignments
  765. void Discreet3DSImporter::ParseFaceChunk()
  766. {
  767. ASSIMP_3DS_BEGIN_CHUNK();
  768. // Get the mesh we're currently working on
  769. D3DS::Mesh& mMesh = mScene->mMeshes.back();
  770. // Get chunk type
  771. switch (chunk.Flag)
  772. {
  773. case Discreet3DS::CHUNK_SMOOLIST:
  774. {
  775. // This is the list of smoothing groups - a bitfield for every face.
  776. // Up to 32 smoothing groups assigned to a single face.
  777. unsigned int num = chunkSize/4, m = 0;
  778. for (std::vector<D3DS::Face>::iterator i = mMesh.mFaces.begin(); m != num;++i, ++m) {
  779. // nth bit is set for nth smoothing group
  780. (*i).iSmoothGroup = stream->GetI4();
  781. }}
  782. break;
  783. case Discreet3DS::CHUNK_FACEMAT:
  784. {
  785. // at fist an asciiz with the material name
  786. const char* sz = (const char*)stream->GetPtr();
  787. while (stream->GetI1());
  788. // find the index of the material
  789. unsigned int idx = 0xcdcdcdcd, cnt = 0;
  790. for (std::vector<D3DS::Material>::const_iterator i = mScene->mMaterials.begin();i != mScene->mMaterials.end();++i,++cnt) {
  791. // use case independent comparisons. hopefully it will work.
  792. if ((*i).mName.length() && !ASSIMP_stricmp(sz, (*i).mName.c_str())) {
  793. idx = cnt;
  794. break;
  795. }
  796. }
  797. if (0xcdcdcdcd == idx) {
  798. DefaultLogger::get()->error(std::string("3DS: Unknown material: ") + sz);
  799. }
  800. // Now continue and read all material indices
  801. cnt = (uint16_t)stream->GetI2();
  802. for (unsigned int i = 0; i < cnt;++i) {
  803. unsigned int fidx = (uint16_t)stream->GetI2();
  804. // check range
  805. if (fidx >= mMesh.mFaceMaterials.size()) {
  806. DefaultLogger::get()->error("3DS: Invalid face index in face material list");
  807. }
  808. else mMesh.mFaceMaterials[fidx] = idx;
  809. }}
  810. break;
  811. };
  812. ASSIMP_3DS_END_CHUNK();
  813. // recursively continue processing this hierarchy level
  814. return ParseFaceChunk();
  815. }
  816. // ------------------------------------------------------------------------------------------------
  817. // Read a mesh chunk. Here's the actual mesh data
  818. void Discreet3DSImporter::ParseMeshChunk()
  819. {
  820. ASSIMP_3DS_BEGIN_CHUNK();
  821. // Get the mesh we're currently working on
  822. D3DS::Mesh& mMesh = mScene->mMeshes.back();
  823. // get chunk type
  824. switch (chunk.Flag)
  825. {
  826. case Discreet3DS::CHUNK_VERTLIST:
  827. {
  828. // This is the list of all vertices in the current mesh
  829. int num = (int)(uint16_t)stream->GetI2();
  830. mMesh.mPositions.reserve(num);
  831. while (num-- > 0) {
  832. aiVector3D v;
  833. v.x = stream->GetF4();
  834. v.y = stream->GetF4();
  835. v.z = stream->GetF4();
  836. mMesh.mPositions.push_back(v);
  837. }}
  838. break;
  839. case Discreet3DS::CHUNK_TRMATRIX:
  840. {
  841. // This is the RLEATIVE transformation matrix of the current mesh. Vertices are
  842. // pretransformed by this matrix wonder.
  843. mMesh.mMat.a1 = stream->GetF4();
  844. mMesh.mMat.b1 = stream->GetF4();
  845. mMesh.mMat.c1 = stream->GetF4();
  846. mMesh.mMat.a2 = stream->GetF4();
  847. mMesh.mMat.b2 = stream->GetF4();
  848. mMesh.mMat.c2 = stream->GetF4();
  849. mMesh.mMat.a3 = stream->GetF4();
  850. mMesh.mMat.b3 = stream->GetF4();
  851. mMesh.mMat.c3 = stream->GetF4();
  852. mMesh.mMat.a4 = stream->GetF4();
  853. mMesh.mMat.b4 = stream->GetF4();
  854. mMesh.mMat.c4 = stream->GetF4();
  855. }
  856. break;
  857. case Discreet3DS::CHUNK_MAPLIST:
  858. {
  859. // This is the list of all UV coords in the current mesh
  860. int num = (int)(uint16_t)stream->GetI2();
  861. mMesh.mTexCoords.reserve(num);
  862. while (num-- > 0) {
  863. aiVector3D v;
  864. v.x = stream->GetF4();
  865. v.y = stream->GetF4();
  866. mMesh.mTexCoords.push_back(v);
  867. }}
  868. break;
  869. case Discreet3DS::CHUNK_FACELIST:
  870. {
  871. // This is the list of all faces in the current mesh
  872. int num = (int)(uint16_t)stream->GetI2();
  873. mMesh.mFaces.reserve(num);
  874. while (num-- > 0) {
  875. // 3DS faces are ALWAYS triangles
  876. mMesh.mFaces.push_back(D3DS::Face());
  877. D3DS::Face& sFace = mMesh.mFaces.back();
  878. sFace.mIndices[0] = (uint16_t)stream->GetI2();
  879. sFace.mIndices[1] = (uint16_t)stream->GetI2();
  880. sFace.mIndices[2] = (uint16_t)stream->GetI2();
  881. stream->IncPtr(2); // skip edge visibility flag
  882. }
  883. // Resize the material array (0xcdcdcdcd marks the default material; so if a face is
  884. // not referenced by a material, $$DEFAULT will be assigned to it)
  885. mMesh.mFaceMaterials.resize(mMesh.mFaces.size(),0xcdcdcdcd);
  886. // Larger 3DS files could have multiple FACE chunks here
  887. chunkSize = stream->GetRemainingSizeToLimit();
  888. if (chunkSize > sizeof(Discreet3DS::Chunk))
  889. ParseFaceChunk();
  890. }
  891. break;
  892. };
  893. ASSIMP_3DS_END_CHUNK();
  894. // recursively continue processing this hierarchy level
  895. return ParseMeshChunk();
  896. }
  897. // ------------------------------------------------------------------------------------------------
  898. // Read a 3DS material chunk
  899. void Discreet3DSImporter::ParseMaterialChunk()
  900. {
  901. ASSIMP_3DS_BEGIN_CHUNK();
  902. switch (chunk.Flag)
  903. {
  904. case Discreet3DS::CHUNK_MAT_MATNAME:
  905. {
  906. // The material name string is already zero-terminated, but we need to be sure ...
  907. const char* sz = (const char*)stream->GetPtr();
  908. unsigned int cnt = 0;
  909. while (stream->GetI1())
  910. ++cnt;
  911. if (!cnt) {
  912. // This may not be, we use the default name instead
  913. DefaultLogger::get()->error("3DS: Empty material name");
  914. }
  915. else mScene->mMaterials.back().mName = std::string(sz,cnt);
  916. }
  917. break;
  918. case Discreet3DS::CHUNK_MAT_DIFFUSE:
  919. {
  920. // This is the diffuse material color
  921. aiColor3D* pc = &mScene->mMaterials.back().mDiffuse;
  922. ParseColorChunk(pc);
  923. if (is_qnan(pc->r)) {
  924. // color chunk is invalid. Simply ignore it
  925. DefaultLogger::get()->error("3DS: Unable to read DIFFUSE chunk");
  926. pc->r = pc->g = pc->b = 1.0f;
  927. }}
  928. break;
  929. case Discreet3DS::CHUNK_MAT_SPECULAR:
  930. {
  931. // This is the specular material color
  932. aiColor3D* pc = &mScene->mMaterials.back().mSpecular;
  933. ParseColorChunk(pc);
  934. if (is_qnan(pc->r)) {
  935. // color chunk is invalid. Simply ignore it
  936. DefaultLogger::get()->error("3DS: Unable to read SPECULAR chunk");
  937. pc->r = pc->g = pc->b = 1.0f;
  938. }}
  939. break;
  940. case Discreet3DS::CHUNK_MAT_AMBIENT:
  941. {
  942. // This is the ambient material color
  943. aiColor3D* pc = &mScene->mMaterials.back().mAmbient;
  944. ParseColorChunk(pc);
  945. if (is_qnan(pc->r)) {
  946. // color chunk is invalid. Simply ignore it
  947. DefaultLogger::get()->error("3DS: Unable to read AMBIENT chunk");
  948. pc->r = pc->g = pc->b = 0.0f;
  949. }}
  950. break;
  951. case Discreet3DS::CHUNK_MAT_SELF_ILLUM:
  952. {
  953. // This is the emissive material color
  954. aiColor3D* pc = &mScene->mMaterials.back().mEmissive;
  955. ParseColorChunk(pc);
  956. if (is_qnan(pc->r)) {
  957. // color chunk is invalid. Simply ignore it
  958. DefaultLogger::get()->error("3DS: Unable to read EMISSIVE chunk");
  959. pc->r = pc->g = pc->b = 0.0f;
  960. }}
  961. break;
  962. case Discreet3DS::CHUNK_MAT_TRANSPARENCY:
  963. {
  964. // This is the material's transparency
  965. float* pcf = &mScene->mMaterials.back().mTransparency;
  966. *pcf = ParsePercentageChunk();
  967. // NOTE: transparency, not opacity
  968. if (is_qnan(*pcf))
  969. *pcf = 1.0f;
  970. else *pcf = 1.0f - *pcf * (float)0xFFFF / 100.0f;
  971. }
  972. break;
  973. case Discreet3DS::CHUNK_MAT_SHADING:
  974. // This is the material shading mode
  975. mScene->mMaterials.back().mShading = (D3DS::Discreet3DS::shadetype3ds)stream->GetI2();
  976. break;
  977. case Discreet3DS::CHUNK_MAT_TWO_SIDE:
  978. // This is the two-sided flag
  979. mScene->mMaterials.back().mTwoSided = true;
  980. break;
  981. case Discreet3DS::CHUNK_MAT_SHININESS:
  982. { // This is the shininess of the material
  983. float* pcf = &mScene->mMaterials.back().mSpecularExponent;
  984. *pcf = ParsePercentageChunk();
  985. if (is_qnan(*pcf))
  986. *pcf = 0.0f;
  987. else *pcf *= (float)0xFFFF;
  988. }
  989. break;
  990. case Discreet3DS::CHUNK_MAT_SHININESS_PERCENT:
  991. { // This is the shininess strength of the material
  992. float* pcf = &mScene->mMaterials.back().mShininessStrength;
  993. *pcf = ParsePercentageChunk();
  994. if (is_qnan(*pcf))
  995. *pcf = 0.0f;
  996. else *pcf *= (float)0xffff / 100.0f;
  997. }
  998. break;
  999. case Discreet3DS::CHUNK_MAT_SELF_ILPCT:
  1000. { // This is the self illumination strength of the material
  1001. float f = ParsePercentageChunk();
  1002. if (is_qnan(f))
  1003. f = 0.0f;
  1004. else f *= (float)0xFFFF / 100.0f;
  1005. mScene->mMaterials.back().mEmissive = aiColor3D(f,f,f);
  1006. }
  1007. break;
  1008. // Parse texture chunks
  1009. case Discreet3DS::CHUNK_MAT_TEXTURE:
  1010. // Diffuse texture
  1011. ParseTextureChunk(&mScene->mMaterials.back().sTexDiffuse);
  1012. break;
  1013. case Discreet3DS::CHUNK_MAT_BUMPMAP:
  1014. // Height map
  1015. ParseTextureChunk(&mScene->mMaterials.back().sTexBump);
  1016. break;
  1017. case Discreet3DS::CHUNK_MAT_OPACMAP:
  1018. // Opacity texture
  1019. ParseTextureChunk(&mScene->mMaterials.back().sTexOpacity);
  1020. break;
  1021. case Discreet3DS::CHUNK_MAT_MAT_SHINMAP:
  1022. // Shininess map
  1023. ParseTextureChunk(&mScene->mMaterials.back().sTexShininess);
  1024. break;
  1025. case Discreet3DS::CHUNK_MAT_SPECMAP:
  1026. // Specular map
  1027. ParseTextureChunk(&mScene->mMaterials.back().sTexSpecular);
  1028. break;
  1029. case Discreet3DS::CHUNK_MAT_SELFIMAP:
  1030. // Self-illumination (emissive) map
  1031. ParseTextureChunk(&mScene->mMaterials.back().sTexEmissive);
  1032. break;
  1033. case Discreet3DS::CHUNK_MAT_REFLMAP:
  1034. // Reflection map
  1035. ParseTextureChunk(&mScene->mMaterials.back().sTexReflective);
  1036. break;
  1037. };
  1038. ASSIMP_3DS_END_CHUNK();
  1039. // recursively continue processing this hierarchy level
  1040. return ParseMaterialChunk();
  1041. }
  1042. // ------------------------------------------------------------------------------------------------
  1043. void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture* pcOut)
  1044. {
  1045. ASSIMP_3DS_BEGIN_CHUNK();
  1046. // get chunk type
  1047. switch (chunk.Flag)
  1048. {
  1049. case Discreet3DS::CHUNK_MAPFILE:
  1050. {
  1051. // The material name string is already zero-terminated, but we need to be sure ...
  1052. const char* sz = (const char*)stream->GetPtr();
  1053. unsigned int cnt = 0;
  1054. while (stream->GetI1())
  1055. ++cnt;
  1056. pcOut->mMapName = std::string(sz,cnt);
  1057. }
  1058. break;
  1059. case Discreet3DS::CHUNK_PERCENTF:
  1060. // Manually parse the blend factor
  1061. pcOut->mTextureBlend = stream->GetF4();
  1062. break;
  1063. case Discreet3DS::CHUNK_PERCENTW:
  1064. // Manually parse the blend factor
  1065. pcOut->mTextureBlend = (float)((uint16_t)stream->GetI2()) / 100.0f;
  1066. break;
  1067. case Discreet3DS::CHUNK_MAT_MAP_USCALE:
  1068. // Texture coordinate scaling in the U direction
  1069. pcOut->mScaleU = stream->GetF4();
  1070. if (0.0f == pcOut->mScaleU)
  1071. {
  1072. DefaultLogger::get()->warn("Texture coordinate scaling in the x direction is zero. Assuming 1.");
  1073. pcOut->mScaleU = 1.0f;
  1074. }
  1075. break;
  1076. case Discreet3DS::CHUNK_MAT_MAP_VSCALE:
  1077. // Texture coordinate scaling in the V direction
  1078. pcOut->mScaleV = stream->GetF4();
  1079. if (0.0f == pcOut->mScaleV)
  1080. {
  1081. DefaultLogger::get()->warn("Texture coordinate scaling in the y direction is zero. Assuming 1.");
  1082. pcOut->mScaleV = 1.0f;
  1083. }
  1084. break;
  1085. case Discreet3DS::CHUNK_MAT_MAP_UOFFSET:
  1086. // Texture coordinate offset in the U direction
  1087. pcOut->mOffsetU = -stream->GetF4();
  1088. break;
  1089. case Discreet3DS::CHUNK_MAT_MAP_VOFFSET:
  1090. // Texture coordinate offset in the V direction
  1091. pcOut->mOffsetV = stream->GetF4();
  1092. break;
  1093. case Discreet3DS::CHUNK_MAT_MAP_ANG:
  1094. // Texture coordinate rotation, CCW in DEGREES
  1095. pcOut->mRotation = -AI_DEG_TO_RAD( stream->GetF4() );
  1096. break;
  1097. case Discreet3DS::CHUNK_MAT_MAP_TILING:
  1098. {
  1099. const uint16_t iFlags = stream->GetI2();
  1100. // Get the mapping mode (for both axes)
  1101. if (iFlags & 0x2u)
  1102. pcOut->mMapMode = aiTextureMapMode_Mirror;
  1103. else if (iFlags & 0x10u)
  1104. pcOut->mMapMode = aiTextureMapMode_Decal;
  1105. // wrapping in all remaining cases
  1106. else pcOut->mMapMode = aiTextureMapMode_Wrap;
  1107. }
  1108. break;
  1109. };
  1110. ASSIMP_3DS_END_CHUNK();
  1111. // recursively continue processing this hierarchy level
  1112. return ParseTextureChunk(pcOut);
  1113. }
  1114. // ------------------------------------------------------------------------------------------------
  1115. // Read a percentage chunk
  1116. float Discreet3DSImporter::ParsePercentageChunk()
  1117. {
  1118. Discreet3DS::Chunk chunk;
  1119. ReadChunk(&chunk);
  1120. if (Discreet3DS::CHUNK_PERCENTF == chunk.Flag)
  1121. return stream->GetF4();
  1122. else if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag)
  1123. return (float)((uint16_t)stream->GetI2()) / (float)0xFFFF;
  1124. return get_qnan();
  1125. }
  1126. // ------------------------------------------------------------------------------------------------
  1127. // Read a color chunk. If a percentage chunk is found instead it is read as a grayscale color
  1128. void Discreet3DSImporter::ParseColorChunk(aiColor3D* out,
  1129. bool acceptPercent)
  1130. {
  1131. ai_assert(out != NULL);
  1132. // error return value
  1133. const float qnan = get_qnan();
  1134. static const aiColor3D clrError = aiColor3D(qnan,qnan,qnan);
  1135. Discreet3DS::Chunk chunk;
  1136. ReadChunk(&chunk);
  1137. const unsigned int diff = chunk.Size - sizeof(Discreet3DS::Chunk);
  1138. bool bGamma = false;
  1139. // Get the type of the chunk
  1140. switch(chunk.Flag)
  1141. {
  1142. case Discreet3DS::CHUNK_LINRGBF:
  1143. bGamma = true;
  1144. case Discreet3DS::CHUNK_RGBF:
  1145. if (sizeof(float) * 3 > diff)
  1146. {
  1147. *out = clrError;
  1148. return;
  1149. }
  1150. out->r = stream->GetF4();
  1151. out->g = stream->GetF4();
  1152. out->b = stream->GetF4();
  1153. break;
  1154. case Discreet3DS::CHUNK_LINRGBB:
  1155. bGamma = true;
  1156. case Discreet3DS::CHUNK_RGBB:
  1157. if (sizeof(char) * 3 > diff)
  1158. {
  1159. *out = clrError;
  1160. return;
  1161. }
  1162. out->r = (float)(uint8_t)stream->GetI1() / 255.0f;
  1163. out->g = (float)(uint8_t)stream->GetI1() / 255.0f;
  1164. out->b = (float)(uint8_t)stream->GetI1() / 255.0f;
  1165. break;
  1166. // Percentage chunks are accepted, too.
  1167. case Discreet3DS::CHUNK_PERCENTF:
  1168. if (acceptPercent && 4 <= diff)
  1169. {
  1170. out->g = out->b = out->r = stream->GetF4();
  1171. break;
  1172. }
  1173. *out = clrError;
  1174. return;
  1175. case Discreet3DS::CHUNK_PERCENTW:
  1176. if (acceptPercent && 1 <= diff)
  1177. {
  1178. out->g = out->b = out->r = (float)(uint8_t)stream->GetI1() / 255.0f;
  1179. break;
  1180. }
  1181. *out = clrError;
  1182. return;
  1183. default:
  1184. stream->IncPtr(diff);
  1185. // Skip unknown chunks, hope this won't cause any problems.
  1186. return ParseColorChunk(out,acceptPercent);
  1187. };
  1188. }
  1189. #endif // !! ASSIMP_BUILD_NO_3DS_IMPORTER