3DSLoader.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  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. DefaultLogger::get()->error("3DS: Failed to read ambient base color");
  253. mClrAmbient.r = mClrAmbient.g = mClrAmbient.b = 0.0f;
  254. }
  255. break;
  256. case Discreet3DS::CHUNK_BIT_MAP:
  257. {
  258. // Specifies the background image. The string should already be
  259. // properly 0 terminated but we need to be sure
  260. unsigned int cnt = 0;
  261. const char* sz = (const char*)stream->GetPtr();
  262. while (stream->GetI1())++cnt;
  263. mBackgroundImage = std::string(sz,cnt);
  264. }
  265. break;
  266. case Discreet3DS::CHUNK_BIT_MAP_EXISTS:
  267. bHasBG = true;
  268. break;
  269. case Discreet3DS::CHUNK_MASTER_SCALE:
  270. // Scene master scaling factor
  271. mMasterScale = stream->GetF4();
  272. break;
  273. };
  274. ASSIMP_3DS_END_CHUNK();
  275. // recursively continue processing this hierarchy level
  276. return ParseObjectChunk();
  277. }
  278. // ------------------------------------------------------------------------------------------------
  279. void Discreet3DSImporter::ParseChunk(const char* name, unsigned int num)
  280. {
  281. ASSIMP_3DS_BEGIN_CHUNK();
  282. // get chunk type
  283. switch (chunk.Flag)
  284. {
  285. case Discreet3DS::CHUNK_TRIMESH:
  286. {
  287. // this starts a new triangle mesh
  288. mScene->mMeshes.push_back(D3DS::Mesh());
  289. D3DS::Mesh& m = mScene->mMeshes.back();
  290. // Setup the name of the mesh
  291. m.mName = std::string(name, num);
  292. // Read mesh chunks
  293. ParseMeshChunk();
  294. }
  295. break;
  296. case Discreet3DS::CHUNK_LIGHT:
  297. {
  298. // This starts a new light
  299. aiLight* light = new aiLight();
  300. mScene->mLights.push_back(light);
  301. light->mName.Set(std::string(name, num));
  302. // First read the position of the light
  303. light->mPosition.x = stream->GetF4();
  304. light->mPosition.y = stream->GetF4();
  305. light->mPosition.z = stream->GetF4();
  306. light->mColorDiffuse = aiColor3D(1.f,1.f,1.f);
  307. // Now check for further subchunks (excluding color)
  308. int8_t* p = stream->GetPtr();
  309. ParseLightChunk();
  310. // The specular light color is identical the the diffuse light
  311. // color. The ambient light color is equal to the ambient base
  312. // color of the whole scene.
  313. light->mColorSpecular = light->mColorDiffuse;
  314. light->mColorAmbient = mClrAmbient;
  315. if (light->mType == aiLightSource_UNDEFINED)
  316. {
  317. // It must be a point light
  318. light->mType = aiLightSource_POINT;
  319. }}
  320. break;
  321. case Discreet3DS::CHUNK_CAMERA:
  322. {
  323. // This starts a new camera
  324. aiCamera* camera = new aiCamera();
  325. mScene->mCameras.push_back(camera);
  326. camera->mName.Set(std::string(name, num));
  327. // Camera position and look-at vector are difficult to handle.
  328. // If an animation track is given, we must make sure that
  329. // the track is relative to these values - or , easier
  330. // we must copy the information here to the node matrix of
  331. // the camera's parent in the graph.
  332. // First read the position of the camera
  333. camera->mPosition.x = stream->GetF4();
  334. camera->mPosition.y = stream->GetF4();
  335. camera->mPosition.z = stream->GetF4();
  336. // Then the camera target
  337. camera->mLookAt.x = stream->GetF4() - camera->mPosition.x;
  338. camera->mLookAt.y = stream->GetF4() - camera->mPosition.y;
  339. camera->mLookAt.z = stream->GetF4() - camera->mPosition.z;
  340. camera->mLookAt.Normalize();
  341. // And finally - the camera rotation angle, in
  342. // counter clockwise direction
  343. float angle = AI_DEG_TO_RAD( stream->GetF4() );
  344. aiQuaternion quat(camera->mLookAt,angle);
  345. camera->mUp = quat.GetMatrix() * aiVector3D(0.f,1.f,0.f);
  346. // Read the lense angle
  347. camera->mHorizontalFOV = AI_DEG_TO_RAD ( stream->GetF4() );
  348. if (camera->mHorizontalFOV < 0.001f)
  349. camera->mHorizontalFOV = AI_DEG_TO_RAD(45.f);
  350. }
  351. break;
  352. };
  353. ASSIMP_3DS_END_CHUNK();
  354. // recursively continue processing this hierarchy level
  355. return ParseChunk(name,num);
  356. }
  357. // ------------------------------------------------------------------------------------------------
  358. void Discreet3DSImporter::ParseLightChunk()
  359. {
  360. ASSIMP_3DS_BEGIN_CHUNK();
  361. aiLight* light = mScene->mLights.back();
  362. // get chunk type
  363. switch (chunk.Flag)
  364. {
  365. case Discreet3DS::CHUNK_SPOTLIGHT:
  366. // Now we can be sure that the light is a spot light
  367. light->mType = aiLightSource_SPOT;
  368. // We wouldn't need to normalize here, but we do it
  369. light->mDirection.x = stream->GetF4() - light->mPosition.x;
  370. light->mDirection.y = stream->GetF4() - light->mPosition.y;
  371. light->mDirection.z = stream->GetF4() - light->mPosition.z;
  372. light->mDirection.Normalize();
  373. // Now the hotspot and falloff angles - in degrees
  374. light->mAngleInnerCone = AI_DEG_TO_RAD( stream->GetF4() );
  375. // FIX: the falloff angle is just an offset
  376. light->mAngleOuterCone = light->mAngleInnerCone+AI_DEG_TO_RAD( stream->GetF4() );
  377. break;
  378. // intensity multiplier
  379. case Discreet3DS::CHUNK_DL_MULTIPLIER:
  380. light->mColorDiffuse = light->mColorDiffuse * stream->GetF4();
  381. break;
  382. // light color
  383. case Discreet3DS::CHUNK_RGBF:
  384. case Discreet3DS::CHUNK_LINRGBF:
  385. light->mColorDiffuse.r *= stream->GetF4();
  386. light->mColorDiffuse.g *= stream->GetF4();
  387. light->mColorDiffuse.b *= stream->GetF4();
  388. break;
  389. // light attenuation
  390. case Discreet3DS::CHUNK_DL_ATTENUATE:
  391. light->mAttenuationLinear = stream->GetF4();
  392. break;
  393. };
  394. ASSIMP_3DS_END_CHUNK();
  395. // recursively continue processing this hierarchy level
  396. return ParseLightChunk();
  397. }
  398. // ------------------------------------------------------------------------------------------------
  399. void Discreet3DSImporter::ParseCameraChunk()
  400. {
  401. ASSIMP_3DS_BEGIN_CHUNK();
  402. aiCamera* camera = mScene->mCameras.back();
  403. // get chunk type
  404. switch (chunk.Flag)
  405. {
  406. // near and far clip plane
  407. case Discreet3DS::CHUNK_CAM_RANGES:
  408. camera->mClipPlaneNear = stream->GetF4();
  409. camera->mClipPlaneFar = stream->GetF4();
  410. break;
  411. }
  412. ASSIMP_3DS_END_CHUNK();
  413. // recursively continue processing this hierarchy level
  414. return ParseCameraChunk();
  415. }
  416. // ------------------------------------------------------------------------------------------------
  417. void Discreet3DSImporter::ParseKeyframeChunk()
  418. {
  419. ASSIMP_3DS_BEGIN_CHUNK();
  420. // get chunk type
  421. switch (chunk.Flag)
  422. {
  423. case Discreet3DS::CHUNK_TRACKCAMTGT:
  424. case Discreet3DS::CHUNK_SPOTLIGHT:
  425. case Discreet3DS::CHUNK_TRACKCAMERA:
  426. case Discreet3DS::CHUNK_TRACKINFO:
  427. case Discreet3DS::CHUNK_TRACKLIGHT:
  428. case Discreet3DS::CHUNK_TRACKLIGTGT:
  429. // this starts a new mesh hierarchy chunk
  430. ParseHierarchyChunk(chunk.Flag);
  431. break;
  432. };
  433. ASSIMP_3DS_END_CHUNK();
  434. // recursively continue processing this hierarchy level
  435. return ParseKeyframeChunk();
  436. }
  437. // ------------------------------------------------------------------------------------------------
  438. // Little helper function for ParseHierarchyChunk
  439. void Discreet3DSImporter::InverseNodeSearch(D3DS::Node* pcNode,D3DS::Node* pcCurrent)
  440. {
  441. if (!pcCurrent)
  442. {
  443. mRootNode->push_back(pcNode);
  444. return;
  445. }
  446. if (pcCurrent->mHierarchyPos == pcNode->mHierarchyPos)
  447. {
  448. if(pcCurrent->mParent)pcCurrent->mParent->push_back(pcNode);
  449. else pcCurrent->push_back(pcNode);
  450. return;
  451. }
  452. return InverseNodeSearch(pcNode,pcCurrent->mParent);
  453. }
  454. // ------------------------------------------------------------------------------------------------
  455. D3DS::Node* FindNode(D3DS::Node* root, const std::string& name)
  456. {
  457. if (root->mName == name)return root;
  458. for (std::vector<D3DS::Node*>::iterator it = root->mChildren.begin();
  459. it != root->mChildren.end(); ++it)
  460. {
  461. D3DS::Node* nd;
  462. if (( nd = FindNode(*it,name)))return nd;
  463. }
  464. return NULL;
  465. }
  466. // ------------------------------------------------------------------------------------------------
  467. // Binary predicate for std::unique()
  468. template <class T>
  469. bool KeyUniqueCompare(const T& first, const T& second)
  470. {
  471. return first.mTime == second.mTime;
  472. }
  473. // ------------------------------------------------------------------------------------------------
  474. void Discreet3DSImporter::SkipTCBInfo()
  475. {
  476. unsigned int flags = stream->GetI2();
  477. if (!flags)
  478. {
  479. // ******************************************************************
  480. // Currently we can't do anything with these values. They occur
  481. // quite rare, so it wouldn't be worth the effort implementing
  482. // them. 3DS ist not really suitable for complex animations,
  483. // so full support is not required.
  484. // ******************************************************************
  485. DefaultLogger::get()->warn("3DS: Skipping TCB animation info");
  486. }
  487. if (flags & Discreet3DS::KEY_USE_TENS)
  488. stream->IncPtr(4);
  489. if (flags & Discreet3DS::KEY_USE_BIAS)
  490. stream->IncPtr(4);
  491. if (flags & Discreet3DS::KEY_USE_CONT)
  492. stream->IncPtr(4);
  493. if (flags & Discreet3DS::KEY_USE_EASE_FROM)
  494. stream->IncPtr(4);
  495. if (flags & Discreet3DS::KEY_USE_EASE_TO)
  496. stream->IncPtr(4);
  497. }
  498. // ------------------------------------------------------------------------------------------------
  499. void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent)
  500. {
  501. ASSIMP_3DS_BEGIN_CHUNK();
  502. // get chunk type
  503. switch (chunk.Flag)
  504. {
  505. case Discreet3DS::CHUNK_TRACKOBJNAME:
  506. // This is the name of the object to which the track applies
  507. // The chunk also defines the position of this object in the
  508. // hierarchy.
  509. {
  510. // First of all: get the name of the object
  511. unsigned int cnt = 0;
  512. const char* sz = (const char*)stream->GetPtr();
  513. while (stream->GetI1())++cnt;
  514. std::string name = std::string(sz,cnt);
  515. // Now find out whether we have this node already
  516. // (target animation channels are stored with a
  517. // separate object ID)
  518. D3DS::Node* pcNode = FindNode(mRootNode,name);
  519. if (pcNode)
  520. {
  521. // Make this node the current node
  522. mCurrentNode = pcNode;
  523. break;
  524. }
  525. pcNode = new D3DS::Node();
  526. pcNode->mName = name;
  527. // There are two unknown values which we can safely ignore
  528. stream->IncPtr(4);
  529. // Now read the hierarchy position of the object
  530. uint16_t hierarchy = stream->GetI2() + 1;
  531. pcNode->mHierarchyPos = hierarchy;
  532. pcNode->mHierarchyIndex = mLastNodeIndex;
  533. // And find a proper position in the graph for it
  534. if (mCurrentNode && mCurrentNode->mHierarchyPos == hierarchy)
  535. {
  536. // add to the parent of the last touched node
  537. mCurrentNode->mParent->push_back(pcNode);
  538. mLastNodeIndex++;
  539. }
  540. else if(hierarchy >= mLastNodeIndex)
  541. {
  542. // place it at the current position in the hierarchy
  543. mCurrentNode->push_back(pcNode);
  544. mLastNodeIndex = hierarchy;
  545. }
  546. else
  547. {
  548. // need to go back to the specified position in the hierarchy.
  549. InverseNodeSearch(pcNode,mCurrentNode);
  550. mLastNodeIndex++;
  551. }
  552. // Make this node the current node
  553. mCurrentNode = pcNode;
  554. }
  555. break;
  556. case Discreet3DS::CHUNK_TRACKDUMMYOBJNAME:
  557. // This is the "real" name of a $$$DUMMY object
  558. {
  559. if (mCurrentNode->mName != "$$$DUMMY")
  560. {
  561. DefaultLogger::get()->warn("3DS: Skipping dummy object name for non-dummy object");
  562. break;
  563. }
  564. const char* sz = (const char*)stream->GetPtr();
  565. while (stream->GetI1());
  566. mCurrentNode->mDummyName = std::string(sz);
  567. }
  568. break;
  569. case Discreet3DS::CHUNK_TRACKPIVOT:
  570. if ( Discreet3DS::CHUNK_TRACKINFO != parent)
  571. {
  572. DefaultLogger::get()->warn("3DS: Skipping pivot subchunk for non usual object");
  573. break;
  574. }
  575. // Pivot = origin of rotation and scaling
  576. mCurrentNode->vPivot.x = stream->GetF4();
  577. mCurrentNode->vPivot.y = stream->GetF4();
  578. mCurrentNode->vPivot.z = stream->GetF4();
  579. break;
  580. // **************************************************************
  581. // POSITION KEYFRAME
  582. case Discreet3DS::CHUNK_TRACKPOS:
  583. {
  584. stream->IncPtr(10);
  585. const unsigned int numFrames = stream->GetI4();
  586. bool sortKeys = false;
  587. // This could also be meant as the target position for
  588. // (targeted) lights and cameras
  589. std::vector<aiVectorKey>* l;
  590. if ( Discreet3DS::CHUNK_TRACKCAMTGT == parent || Discreet3DS::CHUNK_TRACKLIGTGT == parent)
  591. {
  592. l = & mCurrentNode->aTargetPositionKeys;
  593. }
  594. else l = & mCurrentNode->aPositionKeys;
  595. l->reserve(numFrames);
  596. for (unsigned int i = 0; i < numFrames;++i)
  597. {
  598. const unsigned int fidx = stream->GetI4();
  599. // Setup a new position key
  600. aiVectorKey v;
  601. v.mTime = (double)fidx;
  602. SkipTCBInfo();
  603. v.mValue.x = stream->GetF4();
  604. v.mValue.y = stream->GetF4();
  605. v.mValue.z = stream->GetF4();
  606. // check whether we'll need to sort the keys
  607. if (!l->empty() && v.mTime <= l->back().mTime)
  608. sortKeys = true;
  609. // Add the new keyframe to the list
  610. l->push_back(v);
  611. }
  612. // Sort all keys with ascending time values and remove duplicates?
  613. if (sortKeys)
  614. {
  615. std::stable_sort(l->begin(),l->end());
  616. l->erase ( std::unique (l->begin(),l->end(),&KeyUniqueCompare<aiVectorKey>), l->end() );
  617. }}
  618. break;
  619. // **************************************************************
  620. // CAMERA ROLL KEYFRAME
  621. case Discreet3DS::CHUNK_TRACKROLL:
  622. {
  623. // roll keys are accepted for cameras only
  624. if (parent != Discreet3DS::CHUNK_TRACKCAMERA)
  625. {
  626. DefaultLogger::get()->warn("3DS: Ignoring roll track for non-camera object");
  627. break;
  628. }
  629. bool sortKeys = false;
  630. std::vector<aiFloatKey>* l = &mCurrentNode->aCameraRollKeys;
  631. stream->IncPtr(10);
  632. const unsigned int numFrames = stream->GetI4();
  633. l->reserve(numFrames);
  634. for (unsigned int i = 0; i < numFrames;++i)
  635. {
  636. const unsigned int fidx = stream->GetI4();
  637. // Setup a new position key
  638. aiFloatKey v;
  639. v.mTime = (double)fidx;
  640. // This is just a single float
  641. SkipTCBInfo();
  642. v.mValue = stream->GetF4();
  643. // Check whether we'll need to sort the keys
  644. if (!l->empty() && v.mTime <= l->back().mTime)
  645. sortKeys = true;
  646. // Add the new keyframe to the list
  647. l->push_back(v);
  648. }
  649. // Sort all keys with ascending time values and remove duplicates?
  650. if (sortKeys)
  651. {
  652. std::stable_sort(l->begin(),l->end());
  653. l->erase ( std::unique (l->begin(),l->end(),&KeyUniqueCompare<aiFloatKey>), l->end() );
  654. }}
  655. break;
  656. // **************************************************************
  657. // CAMERA FOV KEYFRAME
  658. case Discreet3DS::CHUNK_TRACKFOV:
  659. {
  660. DefaultLogger::get()->error("3DS: Skipping FOV animation track. "
  661. "This is not supported");
  662. }
  663. break;
  664. // **************************************************************
  665. // ROTATION KEYFRAME
  666. case Discreet3DS::CHUNK_TRACKROTATE:
  667. {
  668. stream->IncPtr(10);
  669. const unsigned int numFrames = stream->GetI4();
  670. bool sortKeys = false;
  671. std::vector<aiQuatKey>* l = &mCurrentNode->aRotationKeys;
  672. l->reserve(numFrames);
  673. for (unsigned int i = 0; i < numFrames;++i)
  674. {
  675. const unsigned int fidx = stream->GetI4();
  676. SkipTCBInfo();
  677. aiQuatKey v;
  678. v.mTime = (double)fidx;
  679. // The rotation keyframe is given as an axis-angle pair
  680. const float rad = stream->GetF4();
  681. aiVector3D axis;
  682. axis.x = stream->GetF4();
  683. axis.y = stream->GetF4();
  684. axis.z = stream->GetF4();
  685. if (!axis.x && !axis.y && !axis.z)
  686. axis.y = 1.f;
  687. // Construct a rotation quaternion from the axis-angle pair
  688. v.mValue = aiQuaternion(axis,rad);
  689. // Check whether we'll need to sort the keys
  690. if (!l->empty() && v.mTime <= l->back().mTime)
  691. sortKeys = true;
  692. // add the new keyframe to the list
  693. l->push_back(v);
  694. }
  695. // Sort all keys with ascending time values and remove duplicates?
  696. if (sortKeys)
  697. {
  698. std::stable_sort(l->begin(),l->end());
  699. l->erase ( std::unique (l->begin(),l->end(),&KeyUniqueCompare<aiQuatKey>), l->end() );
  700. }}
  701. break;
  702. // **************************************************************
  703. // SCALING KEYFRAME
  704. case Discreet3DS::CHUNK_TRACKSCALE:
  705. {
  706. stream->IncPtr(10);
  707. const unsigned int numFrames = stream->GetI2();
  708. stream->IncPtr(2);
  709. bool sortKeys = false;
  710. std::vector<aiVectorKey>* l = &mCurrentNode->aScalingKeys;
  711. l->reserve(numFrames);
  712. for (unsigned int i = 0; i < numFrames;++i)
  713. {
  714. const unsigned int fidx = stream->GetI4();
  715. SkipTCBInfo();
  716. // Setup a new key
  717. aiVectorKey v;
  718. v.mTime = (double)fidx;
  719. // ... and read its value
  720. v.mValue.x = stream->GetF4();
  721. v.mValue.y = stream->GetF4();
  722. v.mValue.z = stream->GetF4();
  723. // check whether we'll need to sort the keys
  724. if (!l->empty() && v.mTime <= l->back().mTime)
  725. sortKeys = true;
  726. // Remove zero-scalings
  727. if (!v.mValue.x)v.mValue.x = 1.f;
  728. if (!v.mValue.y)v.mValue.y = 1.f;
  729. if (!v.mValue.z)v.mValue.z = 1.f;
  730. l->push_back(v);
  731. }
  732. // Sort all keys with ascending time values and remove duplicates?
  733. if (sortKeys)
  734. {
  735. std::stable_sort(l->begin(),l->end());
  736. l->erase ( std::unique (l->begin(),l->end(),&KeyUniqueCompare<aiVectorKey>), l->end() );
  737. }}
  738. break;
  739. };
  740. ASSIMP_3DS_END_CHUNK();
  741. // recursively continue processing this hierarchy level
  742. return ParseHierarchyChunk(parent);
  743. }
  744. // ------------------------------------------------------------------------------------------------
  745. void Discreet3DSImporter::ParseFaceChunk()
  746. {
  747. ASSIMP_3DS_BEGIN_CHUNK();
  748. // Get the mesh we're currently working on
  749. D3DS::Mesh& mMesh = mScene->mMeshes.back();
  750. // Get chunk type
  751. switch (chunk.Flag)
  752. {
  753. case Discreet3DS::CHUNK_SMOOLIST:
  754. {
  755. // This is the list of smoothing groups - a bitfield for
  756. // every frame. Up to 32 smoothing groups assigned to a
  757. // face.
  758. unsigned int num = chunkSize/4, m = 0;
  759. for (std::vector<D3DS::Face>::iterator i = mMesh.mFaces.begin();
  760. m != num;++i, ++m)
  761. {
  762. // nth bit is set for nth smoothing group
  763. (*i).iSmoothGroup = stream->GetI4();
  764. }}
  765. break;
  766. case Discreet3DS::CHUNK_FACEMAT:
  767. {
  768. // at fist an asciiz with the material name
  769. const char* sz = (const char*)stream->GetPtr();
  770. while (stream->GetI1());
  771. // find the index of the material
  772. unsigned int idx = 0xcdcdcdcd, cnt = 0;
  773. for (std::vector<D3DS::Material>::const_iterator
  774. i = mScene->mMaterials.begin();
  775. i != mScene->mMaterials.end();++i,++cnt)
  776. {
  777. // compare case-independent to be sure it works
  778. if ((*i).mName.length() && !ASSIMP_stricmp(sz, (*i).mName.c_str()))
  779. {
  780. idx = cnt;
  781. break;
  782. }
  783. }
  784. if (0xcdcdcdcd == idx)
  785. {
  786. DefaultLogger::get()->error(std::string("3DS: Unknown material: ") + sz);
  787. // ******************************************************************
  788. // This material is not known. Ignore this. We will later
  789. // assign the default material to all faces using *this*
  790. // material. We use 0xcdcdcdcd as special value to indicate this.
  791. // ******************************************************************
  792. }
  793. // Now continue and read all material indices
  794. cnt = (uint16_t)stream->GetI2();
  795. for (unsigned int i = 0; i < cnt;++i)
  796. {
  797. unsigned int fidx = (uint16_t)stream->GetI2();
  798. // check range
  799. if (fidx >= mMesh.mFaceMaterials.size())
  800. {
  801. DefaultLogger::get()->error("3DS: Invalid face index in face material list");
  802. }
  803. else mMesh.mFaceMaterials[fidx] = idx;
  804. }}
  805. break;
  806. };
  807. ASSIMP_3DS_END_CHUNK();
  808. // recursively continue processing this hierarchy level
  809. return ParseFaceChunk();
  810. }
  811. // ------------------------------------------------------------------------------------------------
  812. void Discreet3DSImporter::ParseMeshChunk()
  813. {
  814. ASSIMP_3DS_BEGIN_CHUNK();
  815. // Get the mesh we're currently working on
  816. D3DS::Mesh& mMesh = mScene->mMeshes.back();
  817. // get chunk type
  818. switch (chunk.Flag)
  819. {
  820. case Discreet3DS::CHUNK_VERTLIST:
  821. {
  822. // This is the list of all vertices in the current mesh
  823. int num = (int)(uint16_t)stream->GetI2();
  824. mMesh.mPositions.reserve(num);
  825. while (num-- > 0)
  826. {
  827. aiVector3D v;
  828. v.x = stream->GetF4();
  829. v.y = stream->GetF4();
  830. v.z = stream->GetF4();
  831. mMesh.mPositions.push_back(v);
  832. }}
  833. break;
  834. case Discreet3DS::CHUNK_TRMATRIX:
  835. {
  836. // This is the RLEATIVE transformation matrix of the
  837. // current mesh. However, all vertices are pretransformed
  838. mMesh.mMat.a1 = stream->GetF4();
  839. mMesh.mMat.b1 = stream->GetF4();
  840. mMesh.mMat.c1 = stream->GetF4();
  841. mMesh.mMat.a2 = stream->GetF4();
  842. mMesh.mMat.b2 = stream->GetF4();
  843. mMesh.mMat.c2 = stream->GetF4();
  844. mMesh.mMat.a3 = stream->GetF4();
  845. mMesh.mMat.b3 = stream->GetF4();
  846. mMesh.mMat.c3 = stream->GetF4();
  847. mMesh.mMat.a4 = stream->GetF4();
  848. mMesh.mMat.b4 = stream->GetF4();
  849. mMesh.mMat.c4 = stream->GetF4();
  850. // Now check whether the matrix has got a negative determinant
  851. // If yes, we need to flip all vertices' Z axis ....
  852. // This code has been taken from lib3ds
  853. if (mMesh.mMat.Determinant() < 0.0f)
  854. {
  855. // Compute the inverse of the matrix
  856. aiMatrix4x4 mInv = mMesh.mMat;
  857. mInv.Inverse();
  858. aiMatrix4x4 mMe = mMesh.mMat;
  859. mMe.c1 *= -1.0f;
  860. mMe.c2 *= -1.0f;
  861. mMe.c3 *= -1.0f;
  862. mMe.c4 *= -1.0f;
  863. mInv = mInv * mMe;
  864. // Now transform all vertices
  865. for (unsigned int i = 0; i < (unsigned int)mMesh.mPositions.size();++i)
  866. {
  867. aiVector3D a,c;
  868. a = mMesh.mPositions[i];
  869. c[0]= mInv[0][0]*a[0] + mInv[1][0]*a[1] + mInv[2][0]*a[2] + mInv[3][0];
  870. c[1]= mInv[0][1]*a[0] + mInv[1][1]*a[1] + mInv[2][1]*a[2] + mInv[3][1];
  871. c[2]= mInv[0][2]*a[0] + mInv[1][2]*a[1] + mInv[2][2]*a[2] + mInv[3][2];
  872. mMesh.mPositions[i] = c;
  873. }
  874. DefaultLogger::get()->info("3DS: Flipping mesh Z-Axis");
  875. }}
  876. break;
  877. case Discreet3DS::CHUNK_MAPLIST:
  878. {
  879. // This is the list of all UV coords in the current mesh
  880. int num = (int)(uint16_t)stream->GetI2();
  881. mMesh.mTexCoords.reserve(num);
  882. while (num-- > 0)
  883. {
  884. aiVector3D v;
  885. v.x = stream->GetF4();
  886. v.y = stream->GetF4();
  887. mMesh.mTexCoords.push_back(v);
  888. }}
  889. break;
  890. case Discreet3DS::CHUNK_FACELIST:
  891. {
  892. // This is the list of all faces in the current mesh
  893. int num = (int)(uint16_t)stream->GetI2();
  894. mMesh.mFaces.reserve(num);
  895. while (num-- > 0)
  896. {
  897. // 3DS faces are ALWAYS triangles
  898. mMesh.mFaces.push_back(D3DS::Face());
  899. D3DS::Face& sFace = mMesh.mFaces.back();
  900. sFace.mIndices[0] = (uint16_t)stream->GetI2();
  901. sFace.mIndices[1] = (uint16_t)stream->GetI2();
  902. sFace.mIndices[2] = (uint16_t)stream->GetI2();
  903. stream->IncPtr(2); // skip edge visibility flag
  904. }
  905. // Resize the material array (0xcdcdcdcd marks the
  906. // default material; so if a face is not referenced
  907. // by a material $$DEFAULT will be assigned to it)
  908. mMesh.mFaceMaterials.resize(mMesh.mFaces.size(),0xcdcdcdcd);
  909. // Larger 3DS files could have multiple FACE chunks here
  910. chunkSize = stream->GetRemainingSizeToLimit();
  911. if (chunkSize > sizeof(Discreet3DS::Chunk))
  912. ParseFaceChunk();
  913. }
  914. break;
  915. };
  916. ASSIMP_3DS_END_CHUNK();
  917. // recursively continue processing this hierarchy level
  918. return ParseMeshChunk();
  919. }
  920. // ------------------------------------------------------------------------------------------------
  921. void Discreet3DSImporter::ParseMaterialChunk()
  922. {
  923. ASSIMP_3DS_BEGIN_CHUNK();
  924. // get chunk type
  925. switch (chunk.Flag)
  926. {
  927. case Discreet3DS::CHUNK_MAT_MATNAME:
  928. {
  929. // The material name string is already zero-terminated, but
  930. // we need to be sure ...
  931. const char* sz = (const char*)stream->GetPtr();
  932. unsigned int cnt = 0;
  933. while (stream->GetI1())++cnt;
  934. if (!cnt)
  935. {
  936. // This may not be, we use the default name instead
  937. DefaultLogger::get()->error("3DS: Empty material name");
  938. }
  939. else mScene->mMaterials.back().mName = std::string(sz,cnt);
  940. }
  941. break;
  942. case Discreet3DS::CHUNK_MAT_DIFFUSE:
  943. {
  944. // This is the diffuse material color
  945. aiColor3D* pc = &mScene->mMaterials.back().mDiffuse;
  946. ParseColorChunk(pc);
  947. if (is_qnan(pc->r))
  948. {
  949. // color chunk is invalid. Simply ignore it
  950. DefaultLogger::get()->error("3DS: Unable to read DIFFUSE chunk");
  951. pc->r = pc->g = pc->b = 1.0f;
  952. }}
  953. break;
  954. case Discreet3DS::CHUNK_MAT_SPECULAR:
  955. {
  956. // This is the specular material color
  957. aiColor3D* pc = &mScene->mMaterials.back().mSpecular;
  958. ParseColorChunk(pc);
  959. if (is_qnan(pc->r))
  960. {
  961. // color chunk is invalid. Simply ignore it
  962. DefaultLogger::get()->error("3DS: Unable to read SPECULAR chunk");
  963. pc->r = pc->g = pc->b = 1.0f;
  964. }}
  965. break;
  966. case Discreet3DS::CHUNK_MAT_AMBIENT:
  967. {
  968. // This is the ambient material color
  969. aiColor3D* pc = &mScene->mMaterials.back().mAmbient;
  970. ParseColorChunk(pc);
  971. if (is_qnan(pc->r))
  972. {
  973. // color chunk is invalid. Simply ignore it
  974. DefaultLogger::get()->error("3DS: Unable to read AMBIENT chunk");
  975. pc->r = pc->g = pc->b = 0.0f;
  976. }}
  977. break;
  978. case Discreet3DS::CHUNK_MAT_SELF_ILLUM:
  979. {
  980. // This is the emissive material color
  981. aiColor3D* pc = &mScene->mMaterials.back().mEmissive;
  982. ParseColorChunk(pc);
  983. if (is_qnan(pc->r))
  984. {
  985. // color chunk is invalid. Simply ignore it
  986. DefaultLogger::get()->error("3DS: Unable to read EMISSIVE chunk");
  987. pc->r = pc->g = pc->b = 0.0f;
  988. }}
  989. break;
  990. case Discreet3DS::CHUNK_MAT_TRANSPARENCY:
  991. {
  992. // This is the material's transparency
  993. float* pcf = &mScene->mMaterials.back().mTransparency;
  994. *pcf = ParsePercentageChunk();
  995. // NOTE: transparency, not opacity
  996. if (is_qnan(*pcf))*pcf = 1.0f;
  997. else *pcf = 1.0f - *pcf * (float)0xFFFF / 100.0f;
  998. }
  999. break;
  1000. case Discreet3DS::CHUNK_MAT_SHADING:
  1001. // This is the material shading mode
  1002. mScene->mMaterials.back().mShading = (D3DS::Discreet3DS::shadetype3ds)stream->GetI2();
  1003. break;
  1004. case Discreet3DS::CHUNK_MAT_TWO_SIDE:
  1005. // This is the two-sided flag
  1006. mScene->mMaterials.back().mTwoSided = true;
  1007. break;
  1008. case Discreet3DS::CHUNK_MAT_SHININESS:
  1009. { // This is the shininess of the material
  1010. float* pcf = &mScene->mMaterials.back().mSpecularExponent;
  1011. *pcf = ParsePercentageChunk();
  1012. if (is_qnan(*pcf))*pcf = 0.0f;
  1013. else *pcf *= (float)0xFFFF;
  1014. }
  1015. break;
  1016. case Discreet3DS::CHUNK_MAT_SHININESS_PERCENT:
  1017. { // This is the shininess strength of the material
  1018. float* pcf = &mScene->mMaterials.back().mShininessStrength;
  1019. *pcf = ParsePercentageChunk();
  1020. if (is_qnan(*pcf))*pcf = 0.0f;
  1021. else *pcf *= (float)0xffff / 100.0f;
  1022. }
  1023. break;
  1024. case Discreet3DS::CHUNK_MAT_SELF_ILPCT:
  1025. { // This is the self illumination strength of the material
  1026. float f = ParsePercentageChunk();
  1027. if (is_qnan(f))f = 0.0f;
  1028. else f *= (float)0xFFFF / 100.0f;
  1029. mScene->mMaterials.back().mEmissive = aiColor3D(f,f,f);
  1030. }
  1031. break;
  1032. // Parse texture chunks
  1033. case Discreet3DS::CHUNK_MAT_TEXTURE:
  1034. // Diffuse texture
  1035. ParseTextureChunk(&mScene->mMaterials.back().sTexDiffuse);
  1036. break;
  1037. case Discreet3DS::CHUNK_MAT_BUMPMAP:
  1038. // Height map
  1039. ParseTextureChunk(&mScene->mMaterials.back().sTexBump);
  1040. break;
  1041. case Discreet3DS::CHUNK_MAT_OPACMAP:
  1042. // Opacity texture
  1043. ParseTextureChunk(&mScene->mMaterials.back().sTexOpacity);
  1044. break;
  1045. case Discreet3DS::CHUNK_MAT_MAT_SHINMAP:
  1046. // Shininess map
  1047. ParseTextureChunk(&mScene->mMaterials.back().sTexShininess);
  1048. break;
  1049. case Discreet3DS::CHUNK_MAT_SPECMAP:
  1050. // Specular map
  1051. ParseTextureChunk(&mScene->mMaterials.back().sTexSpecular);
  1052. break;
  1053. case Discreet3DS::CHUNK_MAT_SELFIMAP:
  1054. // Self-illumination (emissive) map
  1055. ParseTextureChunk(&mScene->mMaterials.back().sTexEmissive);
  1056. break;
  1057. case Discreet3DS::CHUNK_MAT_REFLMAP:
  1058. // Reflection map - no support in Assimp
  1059. DefaultLogger::get()->warn("3DS: Found reflection map in file. This is not supported");
  1060. break;
  1061. };
  1062. ASSIMP_3DS_END_CHUNK();
  1063. // recursively continue processing this hierarchy level
  1064. return ParseMaterialChunk();
  1065. }
  1066. // ------------------------------------------------------------------------------------------------
  1067. void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture* pcOut)
  1068. {
  1069. ASSIMP_3DS_BEGIN_CHUNK();
  1070. // get chunk type
  1071. switch (chunk.Flag)
  1072. {
  1073. case Discreet3DS::CHUNK_MAPFILE:
  1074. {
  1075. // The material name string is already zero-terminated, but
  1076. // we need to be sure ...
  1077. const char* sz = (const char*)stream->GetPtr();
  1078. unsigned int cnt = 0;
  1079. while (stream->GetI1())++cnt;
  1080. pcOut->mMapName = std::string(sz,cnt);
  1081. }
  1082. break;
  1083. case Discreet3DS::CHUNK_PERCENTF:
  1084. // Manually parse the blend factor
  1085. pcOut->mTextureBlend = stream->GetF4();
  1086. break;
  1087. case Discreet3DS::CHUNK_PERCENTW:
  1088. // Manually parse the blend factor
  1089. pcOut->mTextureBlend = (float)((uint16_t)stream->GetI2()) / 100.0f;
  1090. break;
  1091. case Discreet3DS::CHUNK_MAT_MAP_USCALE:
  1092. // Texture coordinate scaling in the U direction
  1093. pcOut->mScaleU = stream->GetF4();
  1094. if (0.0f == pcOut->mScaleU)
  1095. {
  1096. DefaultLogger::get()->warn("Texture coordinate scaling in the "
  1097. "x direction is zero. Assuming 1");
  1098. pcOut->mScaleU = 1.0f;
  1099. }
  1100. break;
  1101. case Discreet3DS::CHUNK_MAT_MAP_VSCALE:
  1102. // Texture coordinate scaling in the V direction
  1103. pcOut->mScaleV = stream->GetF4();
  1104. if (0.0f == pcOut->mScaleV)
  1105. {
  1106. DefaultLogger::get()->warn("Texture coordinate scaling in the "
  1107. "y direction is zero. Assuming 1");
  1108. pcOut->mScaleV = 1.0f;
  1109. }
  1110. break;
  1111. case Discreet3DS::CHUNK_MAT_MAP_UOFFSET:
  1112. // Texture coordinate offset in the U direction
  1113. pcOut->mOffsetU = -stream->GetF4();
  1114. break;
  1115. case Discreet3DS::CHUNK_MAT_MAP_VOFFSET:
  1116. // Texture coordinate offset in the V direction
  1117. pcOut->mOffsetV = stream->GetF4();
  1118. break;
  1119. case Discreet3DS::CHUNK_MAT_MAP_ANG:
  1120. // Texture coordinate rotation, CCW in DEGREES
  1121. pcOut->mRotation = -AI_DEG_TO_RAD( stream->GetF4() );
  1122. break;
  1123. case Discreet3DS::CHUNK_MAT_MAP_TILING:
  1124. {
  1125. const uint16_t iFlags = stream->GetI2();
  1126. // Get the mapping mode (for both axes)
  1127. if (iFlags & 0x2u)
  1128. pcOut->mMapMode = aiTextureMapMode_Mirror;
  1129. else if (iFlags & 0x10u)
  1130. pcOut->mMapMode = aiTextureMapMode_Decal;
  1131. // wrapping in all remaining cases
  1132. else pcOut->mMapMode = aiTextureMapMode_Wrap;
  1133. }
  1134. break;
  1135. };
  1136. ASSIMP_3DS_END_CHUNK();
  1137. // recursively continue processing this hierarchy level
  1138. return ParseTextureChunk(pcOut);
  1139. }
  1140. // ------------------------------------------------------------------------------------------------
  1141. // Read a percentage chunk
  1142. float Discreet3DSImporter::ParsePercentageChunk()
  1143. {
  1144. Discreet3DS::Chunk chunk;
  1145. ReadChunk(&chunk);
  1146. if (Discreet3DS::CHUNK_PERCENTF == chunk.Flag)
  1147. return stream->GetF4();
  1148. else if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag)
  1149. return (float)((uint16_t)stream->GetI2()) / (float)0xFFFF;
  1150. return std::numeric_limits<float>::quiet_NaN();
  1151. }
  1152. // ------------------------------------------------------------------------------------------------
  1153. // Read a color chunk. If a percentage chunk is found instead it is read as a grayscale color
  1154. void Discreet3DSImporter::ParseColorChunk(aiColor3D* out,
  1155. bool acceptPercent)
  1156. {
  1157. ai_assert(out != NULL);
  1158. // error return value
  1159. const float qnan = std::numeric_limits<float>::quiet_NaN();
  1160. static const aiColor3D clrError = aiColor3D(qnan,qnan,qnan);
  1161. Discreet3DS::Chunk chunk;
  1162. ReadChunk(&chunk);
  1163. const unsigned int diff = chunk.Size - sizeof(Discreet3DS::Chunk);
  1164. bool bGamma = false;
  1165. // Get the type of the chunk
  1166. switch(chunk.Flag)
  1167. {
  1168. case Discreet3DS::CHUNK_LINRGBF:
  1169. bGamma = true;
  1170. case Discreet3DS::CHUNK_RGBF:
  1171. if (sizeof(float) * 3 > diff)
  1172. {
  1173. *out = clrError;
  1174. return;
  1175. }
  1176. out->r = stream->GetF4();
  1177. out->g = stream->GetF4();
  1178. out->b = stream->GetF4();
  1179. break;
  1180. case Discreet3DS::CHUNK_LINRGBB:
  1181. bGamma = true;
  1182. case Discreet3DS::CHUNK_RGBB:
  1183. if (sizeof(char) * 3 > diff)
  1184. {
  1185. *out = clrError;
  1186. return;
  1187. }
  1188. out->r = (float)(uint8_t)stream->GetI1() / 255.0f;
  1189. out->g = (float)(uint8_t)stream->GetI1() / 255.0f;
  1190. out->b = (float)(uint8_t)stream->GetI1() / 255.0f;
  1191. break;
  1192. // Percentage chunks are accepted, too.
  1193. case Discreet3DS::CHUNK_PERCENTF:
  1194. if (acceptPercent && 4 <= diff)
  1195. {
  1196. out->g = out->b = out->r = stream->GetF4();
  1197. break;
  1198. }
  1199. *out = clrError;
  1200. return;
  1201. case Discreet3DS::CHUNK_PERCENTW:
  1202. if (acceptPercent && 1 <= diff)
  1203. {
  1204. out->g = out->b = out->r = (float)(uint8_t)stream->GetI1() / 255.0f;
  1205. break;
  1206. }
  1207. *out = clrError;
  1208. return;
  1209. default:
  1210. stream->IncPtr(diff);
  1211. // Skip unknown chunks, hope this won't cause any problems.
  1212. return ParseColorChunk(out,acceptPercent);
  1213. };
  1214. }