3DSLoader.cpp 40 KB

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