3DSLoader.cpp 42 KB

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