3DSLoader.cpp 46 KB

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