XGLLoader.cpp 29 KB

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