You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

948 lines
25 KiB

  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 Implementation of the XGL/ZGL importer class */
  35. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_XGL_IMPORTER
  37. #include "XGLLoader.h"
  38. #include "ParsingUtils.h"
  39. #include "fast_atof.h"
  40. #include "StreamReader.h"
  41. #include "MemoryIOWrapper.h"
  42. using namespace Assimp;
  43. using namespace irr;
  44. using namespace irr::io;
  45. // zlib is needed for compressed XGL files
  46. #ifndef ASSIMP_BUILD_NO_COMPRESSED_XGL
  47. # ifdef ASSIMP_BUILD_NO_OWN_ZLIB
  48. # include <zlib.h>
  49. # else
  50. # include "../contrib/zlib/zlib.h"
  51. # endif
  52. #endif
  53. // scopeguard for a malloc'ed buffer
  54. struct free_it
  55. {
  56. free_it(void* free) : free(free) {}
  57. ~free_it() {
  58. ::free(this->free);
  59. }
  60. void* free;
  61. };
  62. namespace Assimp { // this has to be in here because LogFunctions is in ::Assimp
  63. template<> const std::string LogFunctions<XGLImporter>::log_prefix = "XGL: ";
  64. }
  65. static const aiImporterDesc desc = {
  66. "XGL Importer",
  67. "",
  68. "",
  69. "",
  70. aiImporterFlags_SupportTextFlavour,
  71. 0,
  72. 0,
  73. 0,
  74. 0,
  75. "xgl zgl"
  76. };
  77. // ------------------------------------------------------------------------------------------------
  78. // Constructor to be privately used by Importer
  79. XGLImporter::XGLImporter()
  80. {}
  81. // ------------------------------------------------------------------------------------------------
  82. // Destructor, private as well
  83. XGLImporter::~XGLImporter()
  84. {}
  85. // ------------------------------------------------------------------------------------------------
  86. // Returns whether the class can handle the format of the given file.
  87. bool XGLImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  88. {
  89. /* NOTE: A simple check for the file extension is not enough
  90. * here. XGL and ZGL are ok, but xml is too generic
  91. * and might be collada as well. So open the file and
  92. * look for typical signal tokens.
  93. */
  94. const std::string extension = GetExtension(pFile);
  95. if (extension == "xgl" || extension == "zgl") {
  96. return true;
  97. }
  98. else if (extension == "xml" || checkSig) {
  99. ai_assert(pIOHandler != NULL);
  100. const char* tokens[] = {"<world>","<World>","<WORLD>"};
  101. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,3);
  102. }
  103. return false;
  104. }
  105. // ------------------------------------------------------------------------------------------------
  106. // Get a list of all file extensions which are handled by this class
  107. const aiImporterDesc* XGLImporter::GetInfo () const
  108. {
  109. return &desc;
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Imports the given file into the given scene structure.
  113. void XGLImporter::InternReadFile( const std::string& pFile,
  114. aiScene* pScene, IOSystem* pIOHandler)
  115. {
  116. #ifndef ASSIMP_BUILD_NO_COMPRESSED_XGL
  117. Bytef* dest = NULL;
  118. free_it free_it_really(dest);
  119. #endif
  120. scene = pScene;
  121. boost::shared_ptr<IOStream> stream( pIOHandler->Open( pFile, "rb"));
  122. // check whether we can read from the file
  123. if( stream.get() == NULL) {
  124. throw DeadlyImportError( "Failed to open XGL/ZGL file " + pFile + "");
  125. }
  126. // see if its compressed, if so uncompress it
  127. if (GetExtension(pFile) == "zgl") {
  128. #ifdef ASSIMP_BUILD_NO_COMPRESSED_XGL
  129. ThrowException("Cannot read ZGL file since Assimp was built without compression support");
  130. #else
  131. boost::scoped_ptr<StreamReaderLE> raw_reader(new StreamReaderLE(stream));
  132. // build a zlib stream
  133. z_stream zstream;
  134. zstream.opaque = Z_NULL;
  135. zstream.zalloc = Z_NULL;
  136. zstream.zfree = Z_NULL;
  137. zstream.data_type = Z_BINARY;
  138. // raw decompression without a zlib or gzip header
  139. inflateInit2(&zstream, -MAX_WBITS);
  140. // skip two extra bytes, zgl files do carry a crc16 upfront (I think)
  141. raw_reader->IncPtr(2);
  142. zstream.next_in = reinterpret_cast<Bytef*>( raw_reader->GetPtr() );
  143. zstream.avail_in = raw_reader->GetRemainingSize();
  144. size_t total = 0l;
  145. // and decompress the data .... do 1k chunks in the hope that we won't kill the stack
  146. #define MYBLOCK 1024
  147. Bytef block[MYBLOCK];
  148. int ret;
  149. do {
  150. zstream.avail_out = MYBLOCK;
  151. zstream.next_out = block;
  152. ret = inflate(&zstream, Z_NO_FLUSH);
  153. if (ret != Z_STREAM_END && ret != Z_OK) {
  154. ThrowException("Failure decompressing this file using gzip, seemingly it is NOT a compressed .XGL file");
  155. }
  156. const size_t have = MYBLOCK - zstream.avail_out;
  157. total += have;
  158. dest = reinterpret_cast<Bytef*>( realloc(dest,total) );
  159. memcpy(dest + total - have,block,have);
  160. }
  161. while (ret != Z_STREAM_END);
  162. // terminate zlib
  163. inflateEnd(&zstream);
  164. // replace the input stream with a memory stream
  165. stream.reset(new MemoryIOStream(reinterpret_cast<uint8_t*>(dest),total));
  166. #endif
  167. }
  168. // construct the irrXML parser
  169. CIrrXML_IOStreamReader st(stream.get());
  170. boost::scoped_ptr<IrrXMLReader> read( createIrrXMLReader((IFileReadCallBack*) &st) );
  171. reader = read.get();
  172. // parse the XML file
  173. TempScope scope;
  174. while (ReadElement()) {
  175. if (!ASSIMP_stricmp(reader->getNodeName(),"world")) {
  176. ReadWorld(scope);
  177. }
  178. }
  179. std::vector<aiMesh*>& meshes = scope.meshes_linear;
  180. std::vector<aiMaterial*>& materials = scope.materials_linear;
  181. if(!meshes.size() || !materials.size()) {
  182. ThrowException("failed to extract data from XGL file, no meshes loaded");
  183. }
  184. // copy meshes
  185. scene->mNumMeshes = static_cast<unsigned int>(meshes.size());
  186. scene->mMeshes = new aiMesh*[scene->mNumMeshes]();
  187. std::copy(meshes.begin(),meshes.end(),scene->mMeshes);
  188. // copy materials
  189. scene->mNumMaterials = static_cast<unsigned int>(materials.size());
  190. scene->mMaterials = new aiMaterial*[scene->mNumMaterials]();
  191. std::copy(materials.begin(),materials.end(),scene->mMaterials);
  192. if (scope.light) {
  193. scene->mNumLights = 1;
  194. scene->mLights = new aiLight*[1];
  195. scene->mLights[0] = scope.light;
  196. scope.light->mName = scene->mRootNode->mName;
  197. }
  198. scope.dismiss();
  199. }
  200. // ------------------------------------------------------------------------------------------------
  201. bool XGLImporter::ReadElement()
  202. {
  203. while(reader->read()) {
  204. if (reader->getNodeType() == EXN_ELEMENT) {
  205. return true;
  206. }
  207. }
  208. return false;
  209. }
  210. // ------------------------------------------------------------------------------------------------
  211. bool XGLImporter::ReadElementUpToClosing(const char* closetag)
  212. {
  213. while(reader->read()) {
  214. if (reader->getNodeType() == EXN_ELEMENT) {
  215. return true;
  216. }
  217. else if (reader->getNodeType() == EXN_ELEMENT_END && !ASSIMP_stricmp(reader->getNodeName(),closetag)) {
  218. return false;
  219. }
  220. }
  221. LogError("unexpected EOF, expected closing <" + std::string(closetag) + "> tag");
  222. return false;
  223. }
  224. // ------------------------------------------------------------------------------------------------
  225. bool XGLImporter::SkipToText()
  226. {
  227. while(reader->read()) {
  228. if (reader->getNodeType() == EXN_TEXT) {
  229. return true;
  230. }
  231. else if (reader->getNodeType() == EXN_ELEMENT || reader->getNodeType() == EXN_ELEMENT_END) {
  232. ThrowException("expected text contents but found another element (or element end)");
  233. }
  234. }
  235. return false;
  236. }
  237. // ------------------------------------------------------------------------------------------------
  238. std::string XGLImporter::GetElementName()
  239. {
  240. const char* s = reader->getNodeName();
  241. size_t len = strlen(s);
  242. std::string ret;
  243. ret.resize(len);
  244. std::transform(s,s+len,ret.begin(),::tolower);
  245. return ret;
  246. }
  247. // ------------------------------------------------------------------------------------------------
  248. void XGLImporter::ReadWorld(TempScope& scope)
  249. {
  250. while (ReadElementUpToClosing("world")) {
  251. const std::string& s = GetElementName();
  252. // XXX right now we'd skip <lighting> if it comes after
  253. // <object> or <mesh>
  254. if (s == "lighting") {
  255. ReadLighting(scope);
  256. }
  257. else if (s == "object" || s == "mesh" || s == "mat") {
  258. break;
  259. }
  260. }
  261. aiNode* const nd = ReadObject(scope,true,"world");
  262. if(!nd) {
  263. ThrowException("failure reading <world>");
  264. }
  265. if(!nd->mName.length) {
  266. nd->mName.Set("WORLD");
  267. }
  268. scene->mRootNode = nd;
  269. }
  270. // ------------------------------------------------------------------------------------------------
  271. void XGLImporter::ReadLighting(TempScope& scope)
  272. {
  273. while (ReadElementUpToClosing("lighting")) {
  274. const std::string& s = GetElementName();
  275. if (s == "directionallight") {
  276. scope.light = ReadDirectionalLight();
  277. }
  278. else if (s == "ambient") {
  279. LogWarn("ignoring <ambient> tag");
  280. }
  281. else if (s == "spheremap") {
  282. LogWarn("ignoring <spheremap> tag");
  283. }
  284. }
  285. }
  286. // ------------------------------------------------------------------------------------------------
  287. aiLight* XGLImporter::ReadDirectionalLight()
  288. {
  289. ScopeGuard<aiLight> l(new aiLight());
  290. l->mType = aiLightSource_DIRECTIONAL;
  291. while (ReadElementUpToClosing("directionallight")) {
  292. const std::string& s = GetElementName();
  293. if (s == "direction") {
  294. l->mDirection = ReadVec3();
  295. }
  296. else if (s == "diffuse") {
  297. l->mColorDiffuse = ReadCol3();
  298. }
  299. else if (s == "specular") {
  300. l->mColorSpecular = ReadCol3();
  301. }
  302. }
  303. return l.dismiss();
  304. }
  305. // ------------------------------------------------------------------------------------------------
  306. aiNode* XGLImporter::ReadObject(TempScope& scope, bool skipFirst, const char* closetag)
  307. {
  308. ScopeGuard<aiNode> nd(new aiNode());
  309. std::vector<aiNode*> children;
  310. std::vector<unsigned int> meshes;
  311. try {
  312. while (skipFirst || ReadElementUpToClosing(closetag)) {
  313. skipFirst = false;
  314. const std::string& s = GetElementName();
  315. if (s == "mesh") {
  316. const size_t prev = scope.meshes_linear.size();
  317. if(ReadMesh(scope)) {
  318. const size_t newc = scope.meshes_linear.size();
  319. for(size_t i = 0; i < newc-prev; ++i) {
  320. meshes.push_back(static_cast<unsigned int>(i+prev));
  321. }
  322. }
  323. }
  324. else if (s == "mat") {
  325. ReadMaterial(scope);
  326. }
  327. else if (s == "object") {
  328. children.push_back(ReadObject(scope));
  329. }
  330. else if (s == "objectref") {
  331. // XXX
  332. }
  333. else if (s == "meshref") {
  334. const unsigned int id = static_cast<unsigned int>( ReadIndexFromText() );
  335. std::multimap<unsigned int, aiMesh*>::iterator it = scope.meshes.find(id), end = scope.meshes.end();
  336. if (it == end) {
  337. ThrowException("<meshref> index out of range");
  338. }
  339. for(; it != end && (*it).first == id; ++it) {
  340. // ok, this is n^2 and should get optimized one day
  341. aiMesh* const m = (*it).second;
  342. unsigned int i = 0, mcount = static_cast<unsigned int>(scope.meshes_linear.size());
  343. for(; i < mcount; ++i) {
  344. if (scope.meshes_linear[i] == m) {
  345. meshes.push_back(i);
  346. break;
  347. }
  348. }
  349. ai_assert(i < mcount);
  350. }
  351. }
  352. else if (s == "transform") {
  353. nd->mTransformation = ReadTrafo();
  354. }
  355. }
  356. } catch(...) {
  357. BOOST_FOREACH(aiNode* ch, children) {
  358. delete ch;
  359. }
  360. throw;
  361. }
  362. // link meshes to node
  363. nd->mNumMeshes = static_cast<unsigned int>(meshes.size());
  364. if (nd->mNumMeshes) {
  365. nd->mMeshes = new unsigned int[nd->mNumMeshes]();
  366. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  367. nd->mMeshes[i] = meshes[i];
  368. }
  369. }
  370. // link children to parent
  371. nd->mNumChildren = static_cast<unsigned int>(children.size());
  372. if (nd->mNumChildren) {
  373. nd->mChildren = new aiNode*[nd->mNumChildren]();
  374. for(unsigned int i = 0; i < nd->mNumChildren; ++i) {
  375. nd->mChildren[i] = children[i];
  376. children[i]->mParent = nd;
  377. }
  378. }
  379. return nd.dismiss();
  380. }
  381. // ------------------------------------------------------------------------------------------------
  382. aiMatrix4x4 XGLImporter::ReadTrafo()
  383. {
  384. aiVector3D forward, up, right, position;
  385. float scale = 1.0f;
  386. while (ReadElementUpToClosing("transform")) {
  387. const std::string& s = GetElementName();
  388. if (s == "forward") {
  389. forward = ReadVec3();
  390. }
  391. else if (s == "up") {
  392. up = ReadVec3();
  393. }
  394. else if (s == "position") {
  395. position = ReadVec3();
  396. }
  397. if (s == "scale") {
  398. scale = ReadFloat();
  399. if(scale < 0.f) {
  400. // this is wrong, but we can leave the value and pass it to the caller
  401. LogError("found negative scaling in <transform>, ignoring");
  402. }
  403. }
  404. }
  405. aiMatrix4x4 m;
  406. if(forward.SquareLength() < 1e-4 || up.SquareLength() < 1e-4) {
  407. LogError("A direction vector in <transform> is zero, ignoring trafo");
  408. return m;
  409. }
  410. forward.Normalize();
  411. up.Normalize();
  412. right = forward ^ up;
  413. if (fabs(up * forward) > 1e-4) {
  414. // this is definitely wrong - a degenerate coordinate space ruins everything
  415. // so subtitute identity transform.
  416. LogError("<forward> and <up> vectors in <transform> are skewing, ignoring trafo");
  417. return m;
  418. }
  419. right *= scale;
  420. up *= scale;
  421. forward *= scale;
  422. m.a1 = right.x;
  423. m.b1 = right.y;
  424. m.c1 = right.z;
  425. m.a2 = up.x;
  426. m.b2 = up.y;
  427. m.c2 = up.z;
  428. m.a3 = forward.x;
  429. m.b3 = forward.y;
  430. m.c3 = forward.z;
  431. m.a4 = position.x;
  432. m.b4 = position.y;
  433. m.c4 = position.z;
  434. return m;
  435. }
  436. // ------------------------------------------------------------------------------------------------
  437. aiMesh* XGLImporter::ToOutputMesh(const TempMaterialMesh& m)
  438. {
  439. ScopeGuard<aiMesh> mesh(new aiMesh());
  440. mesh->mNumVertices = static_cast<unsigned int>(m.positions.size());
  441. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  442. std::copy(m.positions.begin(),m.positions.end(),mesh->mVertices);
  443. if(m.normals.size()) {
  444. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  445. std::copy(m.normals.begin(),m.normals.end(),mesh->mNormals);
  446. }
  447. if(m.uvs.size()) {
  448. mesh->mNumUVComponents[0] = 2;
  449. mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  450. for(unsigned int i = 0; i < mesh->mNumVertices; ++i) {
  451. mesh->mTextureCoords[0][i] = aiVector3D(m.uvs[i].x,m.uvs[i].y,0.f);
  452. }
  453. }
  454. mesh->mNumFaces = static_cast<unsigned int>(m.vcounts.size());
  455. mesh->mFaces = new aiFace[m.vcounts.size()];
  456. unsigned int idx = 0;
  457. for(unsigned int i = 0; i < mesh->mNumFaces; ++i) {
  458. aiFace& f = mesh->mFaces[i];
  459. f.mNumIndices = m.vcounts[i];
  460. f.mIndices = new unsigned int[f.mNumIndices];
  461. for(unsigned int c = 0; c < f.mNumIndices; ++c) {
  462. f.mIndices[c] = idx++;
  463. }
  464. }
  465. ai_assert(idx == mesh->mNumVertices);
  466. mesh->mPrimitiveTypes = m.pflags;
  467. mesh->mMaterialIndex = m.matid;
  468. return mesh.dismiss();
  469. }
  470. // ------------------------------------------------------------------------------------------------
  471. bool XGLImporter::ReadMesh(TempScope& scope)
  472. {
  473. TempMesh t;
  474. std::map<unsigned int, TempMaterialMesh> bymat;
  475. const unsigned int mesh_id = ReadIDAttr();
  476. while (ReadElementUpToClosing("mesh")) {
  477. const std::string& s = GetElementName();
  478. if (s == "mat") {
  479. ReadMaterial(scope);
  480. }
  481. else if (s == "p") {
  482. if (!reader->getAttributeValue("ID")) {
  483. LogWarn("no ID attribute on <p>, ignoring");
  484. }
  485. else {
  486. int id = reader->getAttributeValueAsInt("ID");
  487. t.points[id] = ReadVec3();
  488. }
  489. }
  490. else if (s == "n") {
  491. if (!reader->getAttributeValue("ID")) {
  492. LogWarn("no ID attribute on <n>, ignoring");
  493. }
  494. else {
  495. int id = reader->getAttributeValueAsInt("ID");
  496. t.normals[id] = ReadVec3();
  497. }
  498. }
  499. else if (s == "tc") {
  500. if (!reader->getAttributeValue("ID")) {
  501. LogWarn("no ID attribute on <tc>, ignoring");
  502. }
  503. else {
  504. int id = reader->getAttributeValueAsInt("ID");
  505. t.uvs[id] = ReadVec2();
  506. }
  507. }
  508. else if (s == "f" || s == "l" || s == "p") {
  509. const unsigned int vcount = s == "f" ? 3 : (s == "l" ? 2 : 1);
  510. unsigned int mid = ~0u;
  511. TempFace tf[3];
  512. bool has[3] = {0};
  513. while (ReadElementUpToClosing(s.c_str())) {
  514. const std::string& s = GetElementName();
  515. if (s == "fv1" || s == "lv1" || s == "pv1") {
  516. ReadFaceVertex(t,tf[0]);
  517. has[0] = true;
  518. }
  519. else if (s == "fv2" || s == "lv2") {
  520. ReadFaceVertex(t,tf[1]);
  521. has[1] = true;
  522. }
  523. else if (s == "fv3") {
  524. ReadFaceVertex(t,tf[2]);
  525. has[2] = true;
  526. }
  527. else if (s == "mat") {
  528. if (mid != ~0u) {
  529. LogWarn("only one material tag allowed per <f>");
  530. }
  531. mid = ResolveMaterialRef(scope);
  532. }
  533. else if (s == "matref") {
  534. if (mid != ~0u) {
  535. LogWarn("only one material tag allowed per <f>");
  536. }
  537. mid = ResolveMaterialRef(scope);
  538. }
  539. }
  540. if (mid == ~0u) {
  541. ThrowException("missing material index");
  542. }
  543. bool nor = false;
  544. bool uv = false;
  545. for(unsigned int i = 0; i < vcount; ++i) {
  546. if (!has[i]) {
  547. ThrowException("missing face vertex data");
  548. }
  549. nor = nor || tf[i].has_normal;
  550. uv = uv || tf[i].has_uv;
  551. }
  552. if (mid >= (1<<30)) {
  553. LogWarn("material indices exhausted, this may cause errors in the output");
  554. }
  555. unsigned int meshId = mid | ((nor?1:0)<<31) | ((uv?1:0)<<30);
  556. TempMaterialMesh& mesh = bymat[meshId];
  557. mesh.matid = mid;
  558. for(unsigned int i = 0; i < vcount; ++i) {
  559. mesh.positions.push_back(tf[i].pos);
  560. if(nor) {
  561. mesh.normals.push_back(tf[i].normal);
  562. }
  563. if(uv) {
  564. mesh.uvs.push_back(tf[i].uv);
  565. }
  566. mesh.pflags |= 1 << (vcount-1);
  567. }
  568. mesh.vcounts.push_back(vcount);
  569. }
  570. }
  571. // finally extract output meshes and add them to the scope
  572. typedef std::pair<unsigned int, TempMaterialMesh> pairt;
  573. BOOST_FOREACH(const pairt& p, bymat) {
  574. aiMesh* const m = ToOutputMesh(p.second);
  575. scope.meshes_linear.push_back(m);
  576. // if this is a definition, keep it on the stack
  577. if(mesh_id != ~0u) {
  578. scope.meshes.insert(std::pair<unsigned int, aiMesh*>(mesh_id,m));
  579. }
  580. }
  581. // no id == not a reference, insert this mesh right *here*
  582. return mesh_id == ~0u;
  583. }
  584. // ----------------------------------------------------------------------------------------------
  585. unsigned int XGLImporter::ResolveMaterialRef(TempScope& scope)
  586. {
  587. const std::string& s = GetElementName();
  588. if (s == "mat") {
  589. ReadMaterial(scope);
  590. return scope.materials_linear.size()-1;
  591. }
  592. const int id = ReadIndexFromText();
  593. std::map<unsigned int, aiMaterial*>::iterator it = scope.materials.find(id), end = scope.materials.end();
  594. if (it == end) {
  595. ThrowException("<matref> index out of range");
  596. }
  597. // ok, this is n^2 and should get optimized one day
  598. aiMaterial* const m = (*it).second;
  599. unsigned int i = 0, mcount = static_cast<unsigned int>(scope.materials_linear.size());
  600. for(; i < mcount; ++i) {
  601. if (scope.materials_linear[i] == m) {
  602. return i;
  603. }
  604. }
  605. ai_assert(false);
  606. return 0;
  607. }
  608. // ------------------------------------------------------------------------------------------------
  609. void XGLImporter::ReadMaterial(TempScope& scope)
  610. {
  611. const unsigned int mat_id = ReadIDAttr();
  612. ScopeGuard<aiMaterial> mat(new aiMaterial());
  613. while (ReadElementUpToClosing("mat")) {
  614. const std::string& s = GetElementName();
  615. if (s == "amb") {
  616. const aiColor3D c = ReadCol3();
  617. mat->AddProperty(&c,1,AI_MATKEY_COLOR_AMBIENT);
  618. }
  619. else if (s == "diff") {
  620. const aiColor3D c = ReadCol3();
  621. mat->AddProperty(&c,1,AI_MATKEY_COLOR_DIFFUSE);
  622. }
  623. else if (s == "spec") {
  624. const aiColor3D c = ReadCol3();
  625. mat->AddProperty(&c,1,AI_MATKEY_COLOR_SPECULAR);
  626. }
  627. else if (s == "emiss") {
  628. const aiColor3D c = ReadCol3();
  629. mat->AddProperty(&c,1,AI_MATKEY_COLOR_EMISSIVE);
  630. }
  631. else if (s == "alpha") {
  632. const float f = ReadFloat();
  633. mat->AddProperty(&f,1,AI_MATKEY_OPACITY);
  634. }
  635. else if (s == "shine") {
  636. const float f = ReadFloat();
  637. mat->AddProperty(&f,1,AI_MATKEY_SHININESS);
  638. }
  639. }
  640. scope.materials[mat_id] = mat;
  641. scope.materials_linear.push_back(mat.dismiss());
  642. }
  643. // ----------------------------------------------------------------------------------------------
  644. void XGLImporter::ReadFaceVertex(const TempMesh& t, TempFace& out)
  645. {
  646. const std::string& end = GetElementName();
  647. bool havep = false;
  648. while (ReadElementUpToClosing(end.c_str())) {
  649. const std::string& s = GetElementName();
  650. if (s == "pref") {
  651. const unsigned int id = ReadIndexFromText();
  652. std::map<unsigned int, aiVector3D>::const_iterator it = t.points.find(id);
  653. if (it == t.points.end()) {
  654. ThrowException("point index out of range");
  655. }
  656. out.pos = (*it).second;
  657. havep = true;
  658. }
  659. else if (s == "nref") {
  660. const unsigned int id = ReadIndexFromText();
  661. std::map<unsigned int, aiVector3D>::const_iterator it = t.normals.find(id);
  662. if (it == t.normals.end()) {
  663. ThrowException("normal index out of range");
  664. }
  665. out.normal = (*it).second;
  666. out.has_normal = true;
  667. }
  668. else if (s == "tcref") {
  669. const unsigned int id = ReadIndexFromText();
  670. std::map<unsigned int, aiVector2D>::const_iterator it = t.uvs.find(id);
  671. if (it == t.uvs.end()) {
  672. ThrowException("uv index out of range");
  673. }
  674. out.uv = (*it).second;
  675. out.has_uv = true;
  676. }
  677. else if (s == "p") {
  678. out.pos = ReadVec3();
  679. }
  680. else if (s == "n") {
  681. out.normal = ReadVec3();
  682. }
  683. else if (s == "tc") {
  684. out.uv = ReadVec2();
  685. }
  686. }
  687. if (!havep) {
  688. ThrowException("missing <pref> in <fvN> element");
  689. }
  690. }
  691. // ------------------------------------------------------------------------------------------------
  692. unsigned int XGLImporter::ReadIDAttr()
  693. {
  694. for(int i = 0, e = reader->getAttributeCount(); i < e; ++i) {
  695. if(!ASSIMP_stricmp(reader->getAttributeName(i),"id")) {
  696. return reader->getAttributeValueAsInt(i);
  697. }
  698. }
  699. return ~0u;
  700. }
  701. // ------------------------------------------------------------------------------------------------
  702. float XGLImporter::ReadFloat()
  703. {
  704. if(!SkipToText()) {
  705. LogError("unexpected EOF reading float element contents");
  706. return 0.f;
  707. }
  708. const char* s = reader->getNodeData(), *se;
  709. if(!SkipSpaces(&s)) {
  710. LogError("unexpected EOL, failed to parse float");
  711. return 0.f;
  712. }
  713. float t;
  714. se = fast_atoreal_move(s,t);
  715. if (se == s) {
  716. LogError("failed to read float text");
  717. return 0.f;
  718. }
  719. return t;
  720. }
  721. // ------------------------------------------------------------------------------------------------
  722. unsigned int XGLImporter::ReadIndexFromText()
  723. {
  724. if(!SkipToText()) {
  725. LogError("unexpected EOF reading index element contents");
  726. return ~0u;
  727. }
  728. const char* s = reader->getNodeData(), *se;
  729. if(!SkipSpaces(&s)) {
  730. LogError("unexpected EOL, failed to parse index element");
  731. return ~0u;
  732. }
  733. const unsigned int t = strtoul10(s,&se);
  734. if (se == s) {
  735. LogError("failed to read index");
  736. return ~0u;
  737. }
  738. return t;
  739. }
  740. // ------------------------------------------------------------------------------------------------
  741. aiVector2D XGLImporter::ReadVec2()
  742. {
  743. aiVector2D vec;
  744. if(!SkipToText()) {
  745. LogError("unexpected EOF reading vec2 contents");
  746. return vec;
  747. }
  748. const char* s = reader->getNodeData();
  749. for(int i = 0; i < 2; ++i) {
  750. if(!SkipSpaces(&s)) {
  751. LogError("unexpected EOL, failed to parse vec2");
  752. return vec;
  753. }
  754. vec[i] = fast_atof(&s);
  755. SkipSpaces(&s);
  756. if (i != 1 && *s != ',') {
  757. LogError("expected comma, failed to parse vec2");
  758. return vec;
  759. }
  760. ++s;
  761. }
  762. return vec;
  763. }
  764. // ------------------------------------------------------------------------------------------------
  765. aiVector3D XGLImporter::ReadVec3()
  766. {
  767. aiVector3D vec;
  768. if(!SkipToText()) {
  769. LogError("unexpected EOF reading vec3 contents");
  770. return vec;
  771. }
  772. const char* s = reader->getNodeData();
  773. for(int i = 0; i < 3; ++i) {
  774. if(!SkipSpaces(&s)) {
  775. LogError("unexpected EOL, failed to parse vec3");
  776. return vec;
  777. }
  778. vec[i] = fast_atof(&s);
  779. SkipSpaces(&s);
  780. if (i != 2 && *s != ',') {
  781. LogError("expected comma, failed to parse vec3");
  782. return vec;
  783. }
  784. ++s;
  785. }
  786. return vec;
  787. }
  788. // ------------------------------------------------------------------------------------------------
  789. aiColor3D XGLImporter::ReadCol3()
  790. {
  791. const aiVector3D& v = ReadVec3();
  792. if (v.x < 0.f || v.x > 1.0f || v.y < 0.f || v.y > 1.0f || v.z < 0.f || v.z > 1.0f) {
  793. LogWarn("color values out of range, ignoring");
  794. }
  795. return aiColor3D(v.x,v.y,v.z);
  796. }
  797. #endif