XGLLoader.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2023, 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 "Common/Compression.h"
  38. #include <assimp/ParsingUtils.h>
  39. #include <assimp/fast_atof.h>
  40. #include <assimp/MemoryIOWrapper.h>
  41. #include <assimp/StreamReader.h>
  42. #include <assimp/importerdesc.h>
  43. #include <assimp/mesh.h>
  44. #include <assimp/scene.h>
  45. #include <memory>
  46. #include <utility>
  47. namespace Assimp {
  48. static constexpr uint32_t ErrorId = ~0u;
  49. template <>
  50. const char *LogFunctions<XGLImporter>::Prefix() {
  51. return "XGL: ";
  52. }
  53. static constexpr aiImporterDesc desc = {
  54. "XGL Importer", "", "", "",
  55. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportCompressedFlavour,
  56. 0, 0, 0, 0, "xgl zgl"};
  57. // ------------------------------------------------------------------------------------------------
  58. XGLImporter::XGLImporter() : mXmlParser(nullptr), m_scene(nullptr) {
  59. // empty
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. XGLImporter::~XGLImporter() {
  63. clear();
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. bool XGLImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  67. static const char *tokens[] = { "<world>", "<World>", "<WORLD>" };
  68. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. const aiImporterDesc *XGLImporter::GetInfo() const {
  72. return &desc;
  73. }
  74. // ------------------------------------------------------------------------------------------------
  75. void XGLImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  76. clear();
  77. #ifndef ASSIMP_BUILD_NO_COMPRESSED_XGL
  78. std::vector<char> uncompressed;
  79. #endif
  80. m_scene = pScene;
  81. std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile, "rb"));
  82. // check whether we can read from the file
  83. if (stream == nullptr) {
  84. throw DeadlyImportError("Failed to open XGL/ZGL file " + pFile);
  85. }
  86. // see if its compressed, if so uncompress it
  87. if (GetExtension(pFile) == "zgl") {
  88. #ifdef ASSIMP_BUILD_NO_COMPRESSED_XGL
  89. ThrowException("Cannot read ZGL file since Assimp was built without compression support");
  90. #else
  91. std::unique_ptr<StreamReaderLE> raw_reader(new StreamReaderLE(stream));
  92. Compression compression;
  93. size_t total = 0l;
  94. if (compression.open(Compression::Format::Binary, Compression::FlushMode::NoFlush, -Compression::MaxWBits)) {
  95. // skip two extra bytes, zgl files do carry a crc16 upfront (I think)
  96. raw_reader->IncPtr(2);
  97. total = compression.decompress((unsigned char *)raw_reader->GetPtr(), raw_reader->GetRemainingSize(), uncompressed);
  98. compression.close();
  99. }
  100. // replace the input stream with a memory stream
  101. stream = std::make_shared<MemoryIOStream>(reinterpret_cast<uint8_t *>(uncompressed.data()), total);
  102. #endif
  103. }
  104. // parse the XML file
  105. mXmlParser = new XmlParser;
  106. if (!mXmlParser->parse(stream.get())) {
  107. throw DeadlyImportError("XML parse error while loading XGL file ", pFile);
  108. }
  109. TempScope scope;
  110. XmlNode *worldNode = mXmlParser->findNode("WORLD");
  111. if (nullptr != worldNode) {
  112. ReadWorld(*worldNode, scope);
  113. }
  114. std::vector<aiMesh *> &meshes = scope.meshes_linear;
  115. std::vector<aiMaterial *> &materials = scope.materials_linear;
  116. if (meshes.empty() || materials.empty()) {
  117. ThrowException("failed to extract data from XGL file, no meshes loaded");
  118. }
  119. // copy meshes
  120. m_scene->mNumMeshes = static_cast<unsigned int>(meshes.size());
  121. m_scene->mMeshes = new aiMesh *[m_scene->mNumMeshes]();
  122. std::copy(meshes.begin(), meshes.end(), m_scene->mMeshes);
  123. // copy materials
  124. m_scene->mNumMaterials = static_cast<unsigned int>(materials.size());
  125. m_scene->mMaterials = new aiMaterial *[m_scene->mNumMaterials]();
  126. std::copy(materials.begin(), materials.end(), m_scene->mMaterials);
  127. if (scope.light) {
  128. m_scene->mNumLights = 1;
  129. m_scene->mLights = new aiLight *[1];
  130. m_scene->mLights[0] = scope.light;
  131. scope.light->mName = m_scene->mRootNode->mName;
  132. }
  133. scope.dismiss();
  134. }
  135. // ------------------------------------------------------------------------------------------------
  136. void XGLImporter::clear() {
  137. delete mXmlParser;
  138. mXmlParser = nullptr;
  139. }
  140. // ------------------------------------------------------------------------------------------------
  141. void XGLImporter::ReadWorld(XmlNode &node, TempScope &scope) {
  142. for (XmlNode &currentNode : node.children()) {
  143. const std::string &s = ai_stdStrToLower(currentNode.name());
  144. // XXX right now we'd skip <lighting> if it comes after
  145. // <object> or <mesh>
  146. if (s == "lighting") {
  147. ReadLighting(currentNode, scope);
  148. } else if (s == "object" || s == "mesh" || s == "mat") {
  149. break;
  150. }
  151. }
  152. aiNode *const nd = ReadObject(node, scope);
  153. if (nd == nullptr) {
  154. ThrowException("failure reading <world>");
  155. }
  156. if (nd->mName.length == 0) {
  157. nd->mName.Set("WORLD");
  158. }
  159. m_scene->mRootNode = nd;
  160. }
  161. // ------------------------------------------------------------------------------------------------
  162. void XGLImporter::ReadLighting(XmlNode &node, TempScope &scope) {
  163. const std::string &s = ai_stdStrToLower(node.name());
  164. if (s == "directionallight") {
  165. scope.light = ReadDirectionalLight(node);
  166. } else if (s == "ambient") {
  167. LogWarn("ignoring <ambient> tag");
  168. } else if (s == "spheremap") {
  169. LogWarn("ignoring <spheremap> tag");
  170. }
  171. }
  172. // ------------------------------------------------------------------------------------------------
  173. aiLight *XGLImporter::ReadDirectionalLight(XmlNode &node) {
  174. std::unique_ptr<aiLight> l(new aiLight());
  175. l->mType = aiLightSource_DIRECTIONAL;
  176. find_node_by_name_predicate predicate("directionallight");
  177. XmlNode child = node.find_child(std::move(predicate));
  178. if (child.empty()) {
  179. return nullptr;
  180. }
  181. const std::string &s = ai_stdStrToLower(child.name());
  182. if (s == "direction") {
  183. l->mDirection = ReadVec3(child);
  184. } else if (s == "diffuse") {
  185. l->mColorDiffuse = ReadCol3(child);
  186. } else if (s == "specular") {
  187. l->mColorSpecular = ReadCol3(child);
  188. }
  189. return l.release();
  190. }
  191. // ------------------------------------------------------------------------------------------------
  192. aiNode *XGLImporter::ReadObject(XmlNode &node, TempScope &scope) {
  193. aiNode *nd = new aiNode;
  194. std::vector<aiNode *> children;
  195. std::vector<unsigned int> meshes;
  196. try {
  197. for (XmlNode &child : node.children()) {
  198. const std::string &s = ai_stdStrToLower(child.name());
  199. if (s == "mesh") {
  200. const size_t prev = scope.meshes_linear.size();
  201. if (ReadMesh(child, scope)) {
  202. const size_t newc = scope.meshes_linear.size();
  203. for (size_t i = 0; i < newc - prev; ++i) {
  204. meshes.push_back(static_cast<unsigned int>(i + prev));
  205. }
  206. }
  207. } else if (s == "mat") {
  208. const uint32_t matId = ReadMaterial(child, scope);
  209. if (matId == ErrorId) {
  210. ThrowException("Invalid material id detected.");
  211. }
  212. } else if (s == "object") {
  213. children.push_back(ReadObject(child, scope));
  214. } else if (s == "objectref") {
  215. // XXX
  216. } else if (s == "meshref") {
  217. const unsigned int id = static_cast<unsigned int>(ReadIndexFromText(child));
  218. std::multimap<unsigned int, aiMesh *>::iterator it = scope.meshes.find(id), end = scope.meshes.end();
  219. if (it == end) {
  220. ThrowException("<meshref> index out of range");
  221. }
  222. for (; it != end && (*it).first == id; ++it) {
  223. // ok, this is n^2 and should get optimized one day
  224. aiMesh *const m = it->second;
  225. unsigned int i = 0, mcount = static_cast<unsigned int>(scope.meshes_linear.size());
  226. for (; i < mcount; ++i) {
  227. if (scope.meshes_linear[i] == m) {
  228. meshes.push_back(i);
  229. break;
  230. }
  231. }
  232. ai_assert(i < mcount);
  233. }
  234. } else if (s == "transform") {
  235. nd->mTransformation = ReadTrafo(child);
  236. }
  237. }
  238. } catch (...) {
  239. for (aiNode *ch : children) {
  240. delete ch;
  241. }
  242. throw;
  243. }
  244. // FIX: since we used std::multimap<> to keep meshes by id, mesh order now depends on the behaviour
  245. // of the multimap implementation with respect to the ordering of entries with same values.
  246. // C++11 gives the guarantee that it uses insertion order, before it is implementation-specific.
  247. // Sort by material id to always guarantee a deterministic result.
  248. std::sort(meshes.begin(), meshes.end(), SortMeshByMaterialId(scope));
  249. // link meshes to node
  250. nd->mNumMeshes = static_cast<unsigned int>(meshes.size());
  251. if (0 != nd->mNumMeshes) {
  252. nd->mMeshes = new unsigned int[nd->mNumMeshes]();
  253. for (unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  254. nd->mMeshes[i] = meshes[i];
  255. }
  256. }
  257. // link children to parent
  258. nd->mNumChildren = static_cast<unsigned int>(children.size());
  259. if (nd->mNumChildren) {
  260. nd->mChildren = new aiNode *[nd->mNumChildren]();
  261. for (unsigned int i = 0; i < nd->mNumChildren; ++i) {
  262. nd->mChildren[i] = children[i];
  263. children[i]->mParent = nd;
  264. }
  265. }
  266. return nd;
  267. }
  268. // ------------------------------------------------------------------------------------------------
  269. aiMatrix4x4 XGLImporter::ReadTrafo(XmlNode &node) {
  270. aiVector3D forward, up, right, position;
  271. float scale = 1.0f;
  272. aiMatrix4x4 m;
  273. XmlNode child = node.child("TRANSFORM");
  274. if (child.empty()) {
  275. return m;
  276. }
  277. for (XmlNode &sub_child : child.children()) {
  278. const std::string &s = ai_stdStrToLower(sub_child.name());
  279. if (s == "forward") {
  280. forward = ReadVec3(sub_child);
  281. } else if (s == "up") {
  282. up = ReadVec3(sub_child);
  283. } else if (s == "position") {
  284. position = ReadVec3(sub_child);
  285. }
  286. if (s == "scale") {
  287. scale = ReadFloat(sub_child);
  288. if (scale < 0.f) {
  289. // this is wrong, but we can leave the value and pass it to the caller
  290. LogError("found negative scaling in <transform>, ignoring");
  291. }
  292. }
  293. }
  294. if (forward.SquareLength() < 1e-4 || up.SquareLength() < 1e-4) {
  295. LogError("A direction vector in <transform> is zero, ignoring trafo");
  296. return m;
  297. }
  298. forward.Normalize();
  299. up.Normalize();
  300. right = forward ^ up;
  301. if (std::fabs(up * forward) > 1e-4) {
  302. // this is definitely wrong - a degenerate coordinate space ruins everything
  303. // so substitute identity transform.
  304. LogError("<forward> and <up> vectors in <transform> are skewing, ignoring trafo");
  305. return m;
  306. }
  307. right *= scale;
  308. up *= scale;
  309. forward *= scale;
  310. m.a1 = right.x;
  311. m.b1 = right.y;
  312. m.c1 = right.z;
  313. m.a2 = up.x;
  314. m.b2 = up.y;
  315. m.c2 = up.z;
  316. m.a3 = forward.x;
  317. m.b3 = forward.y;
  318. m.c3 = forward.z;
  319. m.a4 = position.x;
  320. m.b4 = position.y;
  321. m.c4 = position.z;
  322. return m;
  323. }
  324. // ------------------------------------------------------------------------------------------------
  325. aiMesh *XGLImporter::ToOutputMesh(const TempMaterialMesh &m) {
  326. std::unique_ptr<aiMesh> mesh(new aiMesh());
  327. mesh->mNumVertices = static_cast<unsigned int>(m.positions.size());
  328. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  329. std::copy(m.positions.begin(), m.positions.end(), mesh->mVertices);
  330. if (!m.normals.empty()) {
  331. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  332. std::copy(m.normals.begin(), m.normals.end(), mesh->mNormals);
  333. }
  334. if (!m.uvs.empty()) {
  335. mesh->mNumUVComponents[0] = 2;
  336. mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  337. for (unsigned int i = 0; i < mesh->mNumVertices; ++i) {
  338. mesh->mTextureCoords[0][i] = aiVector3D(m.uvs[i].x, m.uvs[i].y, 0.f);
  339. }
  340. }
  341. mesh->mNumFaces = static_cast<unsigned int>(m.vcounts.size());
  342. mesh->mFaces = new aiFace[m.vcounts.size()];
  343. unsigned int idx = 0;
  344. for (unsigned int i = 0; i < mesh->mNumFaces; ++i) {
  345. aiFace &f = mesh->mFaces[i];
  346. f.mNumIndices = m.vcounts[i];
  347. f.mIndices = new unsigned int[f.mNumIndices];
  348. for (unsigned int c = 0; c < f.mNumIndices; ++c) {
  349. f.mIndices[c] = idx++;
  350. }
  351. }
  352. ai_assert(idx == mesh->mNumVertices);
  353. mesh->mPrimitiveTypes = m.pflags;
  354. mesh->mMaterialIndex = m.matid;
  355. return mesh.release();
  356. }
  357. // ------------------------------------------------------------------------------------------------
  358. inline static unsigned int generateMeshId(unsigned int meshId, bool nor, bool uv) {
  359. unsigned int currentMeshId = meshId | ((nor ? 1 : 0) << 31) | ((uv ? 1 : 0) << 30);
  360. return currentMeshId;
  361. }
  362. // ------------------------------------------------------------------------------------------------
  363. bool XGLImporter::ReadMesh(XmlNode &node, TempScope &scope) {
  364. TempMesh t;
  365. uint32_t matId = 99999;
  366. bool mesh_created = false;
  367. std::map<unsigned int, TempMaterialMesh> bymat;
  368. const unsigned int mesh_id = ReadIDAttr(node);
  369. for (XmlNode &child : node.children()) {
  370. const std::string &s = ai_stdStrToLower(child.name());
  371. if (s == "mat") {
  372. matId = ReadMaterial(child, scope);
  373. } else if (s == "p") {
  374. pugi::xml_attribute attr = child.attribute("ID");
  375. if (attr.empty()) {
  376. LogWarn("no ID attribute on <p>, ignoring");
  377. } else {
  378. int id = attr.as_int();
  379. t.points[id] = ReadVec3(child);
  380. }
  381. } else if (s == "n") {
  382. pugi::xml_attribute attr = child.attribute("ID");
  383. if (attr.empty()) {
  384. LogWarn("no ID attribute on <n>, ignoring");
  385. } else {
  386. int id = attr.as_int();
  387. t.normals[id] = ReadVec3(child);
  388. }
  389. } else if (s == "tc") {
  390. pugi::xml_attribute attr = child.attribute("ID");
  391. if (attr.empty()) {
  392. LogWarn("no ID attribute on <tc>, ignoring");
  393. } else {
  394. int id = attr.as_int();
  395. t.uvs[id] = ReadVec2(child);
  396. }
  397. } else if (s == "f" || s == "l" || s == "p") {
  398. const unsigned int vcount = s == "f" ? 3 : (s == "l" ? 2 : 1);
  399. unsigned int meshId = ErrorId;
  400. TempFace tempFace[3] = {};
  401. bool has[3] = { false };
  402. meshId = ReadVertices(child, t, tempFace, has, meshId, scope);
  403. if (meshId == ErrorId) {
  404. ThrowException("missing material index");
  405. }
  406. bool nor = false, uv = false;
  407. for (unsigned int i = 0; i < vcount; ++i) {
  408. if (!has[i]) {
  409. ThrowException("missing face vertex data");
  410. }
  411. nor = nor || tempFace[i].has_normal;
  412. uv = uv || tempFace[i].has_uv;
  413. }
  414. if (meshId >= (1 << 30)) {
  415. LogWarn("material indices exhausted, this may cause errors in the output");
  416. }
  417. const unsigned int currentMeshId = generateMeshId(meshId, nor, uv);
  418. // Generate the temp mesh
  419. TempMaterialMesh &mesh = bymat[currentMeshId];
  420. mesh.matid = meshId;
  421. mesh_created = true;
  422. for (unsigned int i = 0; i < vcount; ++i) {
  423. mesh.positions.push_back(tempFace[i].pos);
  424. if (nor) {
  425. mesh.normals.push_back(tempFace[i].normal);
  426. }
  427. if (uv) {
  428. mesh.uvs.push_back(tempFace[i].uv);
  429. }
  430. mesh.pflags |= 1 << (vcount - 1);
  431. }
  432. mesh.vcounts.push_back(vcount);
  433. }
  434. }
  435. if (!mesh_created) {
  436. TempMaterialMesh &mesh = bymat[mesh_id];
  437. mesh.matid = matId;
  438. }
  439. // finally extract output meshes and add them to the scope
  440. AppendOutputMeshes(bymat, scope, mesh_id);
  441. // no id == not a reference, insert this mesh right *here*
  442. return mesh_id == ErrorId;
  443. }
  444. // ----------------------------------------------------------------------------------------------
  445. void XGLImporter::AppendOutputMeshes(std::map<unsigned int, TempMaterialMesh> bymat, TempScope &scope,
  446. const unsigned int mesh_id) {
  447. using pairt = std::pair<const unsigned int, TempMaterialMesh>;
  448. for (const pairt &p : bymat) {
  449. aiMesh *const m = ToOutputMesh(p.second);
  450. scope.meshes_linear.push_back(m);
  451. // if this is a definition, keep it on the stack
  452. if (mesh_id != ErrorId) {
  453. scope.meshes.insert(std::pair<unsigned int, aiMesh *>(mesh_id, m));
  454. }
  455. }
  456. }
  457. // ----------------------------------------------------------------------------------------------
  458. unsigned int XGLImporter::ReadVertices(XmlNode &child, TempMesh t, TempFace *tf, bool *has, unsigned int mid, TempScope &scope) {
  459. for (XmlNode &sub_child : child.children()) {
  460. const std::string &scn = ai_stdStrToLower(sub_child.name());
  461. if (scn == "fv1" || scn == "lv1" || scn == "pv1") {
  462. ReadFaceVertex(sub_child, t, tf[0]);
  463. has[0] = true;
  464. } else if (scn == "fv2" || scn == "lv2") {
  465. ReadFaceVertex(sub_child, t, tf[1]);
  466. has[1] = true;
  467. } else if (scn == "fv3") {
  468. ReadFaceVertex(sub_child, t, tf[2]);
  469. has[2] = true;
  470. } else if (scn == "mat") {
  471. if (mid != ErrorId) {
  472. LogWarn("only one material tag allowed per <f>");
  473. }
  474. mid = ResolveMaterialRef(sub_child, scope);
  475. } else if (scn == "matref") {
  476. if (mid != ErrorId) {
  477. LogWarn("only one material tag allowed per <f>");
  478. }
  479. mid = ResolveMaterialRef(sub_child, scope);
  480. }
  481. }
  482. return mid;
  483. }
  484. // ----------------------------------------------------------------------------------------------
  485. unsigned int XGLImporter::ResolveMaterialRef(XmlNode &node, TempScope &scope) {
  486. const std::string &s = node.name();
  487. if (s == "mat") {
  488. ReadMaterial(node, scope);
  489. return static_cast<unsigned int>(scope.materials_linear.size() - 1);
  490. }
  491. const int id = ReadIndexFromText(node);
  492. auto it = scope.materials.find(id), end = scope.materials.end();
  493. if (it == end) {
  494. ThrowException("<matref> index out of range");
  495. }
  496. // ok, this is n^2 and should get optimized one day
  497. aiMaterial *const m = it->second;
  498. unsigned int i = 0, mcount = static_cast<unsigned int>(scope.materials_linear.size());
  499. for (; i < mcount; ++i) {
  500. if (scope.materials_linear[i] == m) {
  501. return i;
  502. }
  503. }
  504. ai_assert(false);
  505. return 0;
  506. }
  507. // ------------------------------------------------------------------------------------------------
  508. unsigned int XGLImporter::ReadMaterial(XmlNode &node, TempScope &scope) {
  509. const unsigned int mat_id = ReadIDAttr(node);
  510. auto *mat = new aiMaterial;
  511. for (XmlNode &child : node.children()) {
  512. const std::string &s = ai_stdStrToLower(child.name());
  513. if (s == "amb") {
  514. const aiColor3D c = ReadCol3(child);
  515. mat->AddProperty(&c, 1, AI_MATKEY_COLOR_AMBIENT);
  516. } else if (s == "diff") {
  517. const aiColor3D c = ReadCol3(child);
  518. mat->AddProperty(&c, 1, AI_MATKEY_COLOR_DIFFUSE);
  519. } else if (s == "spec") {
  520. const aiColor3D c = ReadCol3(child);
  521. mat->AddProperty(&c, 1, AI_MATKEY_COLOR_SPECULAR);
  522. } else if (s == "emiss") {
  523. const aiColor3D c = ReadCol3(child);
  524. mat->AddProperty(&c, 1, AI_MATKEY_COLOR_EMISSIVE);
  525. } else if (s == "alpha") {
  526. const float f = ReadFloat(child);
  527. mat->AddProperty(&f, 1, AI_MATKEY_OPACITY);
  528. } else if (s == "shine") {
  529. const float f = ReadFloat(child);
  530. mat->AddProperty(&f, 1, AI_MATKEY_SHININESS);
  531. }
  532. }
  533. scope.materials[mat_id] = mat;
  534. scope.materials_linear.push_back(mat);
  535. return mat_id;
  536. }
  537. // ----------------------------------------------------------------------------------------------
  538. void XGLImporter::ReadFaceVertex(XmlNode &node, const TempMesh &t, TempFace &out) {
  539. bool havep = false;
  540. for (XmlNode &child : node.children()) {
  541. const std::string &s = ai_stdStrToLower(child.name());
  542. if (s == "pref") {
  543. const unsigned int id = ReadIndexFromText(child);
  544. std::map<unsigned int, aiVector3D>::const_iterator it = t.points.find(id);
  545. if (it == t.points.end()) {
  546. ThrowException("point index out of range");
  547. }
  548. out.pos = (*it).second;
  549. havep = true;
  550. } else if (s == "nref") {
  551. const unsigned int id = ReadIndexFromText(child);
  552. std::map<unsigned int, aiVector3D>::const_iterator it = t.normals.find(id);
  553. if (it == t.normals.end()) {
  554. ThrowException("normal index out of range");
  555. }
  556. out.normal = (*it).second;
  557. out.has_normal = true;
  558. } else if (s == "tcref") {
  559. const unsigned int id = ReadIndexFromText(child);
  560. std::map<unsigned int, aiVector2D>::const_iterator it = t.uvs.find(id);
  561. if (it == t.uvs.end()) {
  562. ThrowException("uv index out of range");
  563. }
  564. out.uv = (*it).second;
  565. out.has_uv = true;
  566. } else if (s == "p") {
  567. out.pos = ReadVec3(child);
  568. } else if (s == "n") {
  569. out.normal = ReadVec3(child);
  570. } else if (s == "tc") {
  571. out.uv = ReadVec2(child);
  572. }
  573. }
  574. if (!havep) {
  575. ThrowException("missing <pref> in <fvN> element");
  576. }
  577. }
  578. // ------------------------------------------------------------------------------------------------
  579. unsigned int XGLImporter::ReadIDAttr(XmlNode &node) {
  580. for (pugi::xml_attribute attr : node.attributes()) {
  581. if (!ASSIMP_stricmp(attr.name(), "id")) {
  582. return attr.as_int();
  583. }
  584. }
  585. return ErrorId;
  586. }
  587. // ------------------------------------------------------------------------------------------------
  588. float XGLImporter::ReadFloat(XmlNode &node) {
  589. std::string v;
  590. XmlParser::getValueAsString(node, v);
  591. const char *s = v.c_str(), *se;
  592. if (!SkipSpaces(&s)) {
  593. LogError("unexpected EOL, failed to parse index element");
  594. return 0.f;
  595. }
  596. float t;
  597. se = fast_atoreal_move(s, t);
  598. if (se == s) {
  599. LogError("failed to read float text");
  600. return 0.f;
  601. }
  602. return t;
  603. }
  604. // ------------------------------------------------------------------------------------------------
  605. unsigned int XGLImporter::ReadIndexFromText(XmlNode &node) {
  606. std::string v;
  607. XmlParser::getValueAsString(node, v);
  608. const char *s = v.c_str();
  609. if (!SkipSpaces(&s)) {
  610. LogError("unexpected EOL, failed to parse index element");
  611. return ErrorId;
  612. }
  613. const char *se = nullptr;
  614. const unsigned int t = strtoul10(s, &se);
  615. if (se == s) {
  616. LogError("failed to read index");
  617. return ErrorId;
  618. }
  619. return t;
  620. }
  621. // ------------------------------------------------------------------------------------------------
  622. aiVector2D XGLImporter::ReadVec2(XmlNode &node) {
  623. aiVector2D vec;
  624. std::string val;
  625. XmlParser::getValueAsString(node, val);
  626. const char *s = val.c_str();
  627. ai_real v[2] = {};
  628. for (int i = 0; i < 2; ++i) {
  629. if (!SkipSpaces(&s)) {
  630. LogError("unexpected EOL, failed to parse vec2");
  631. return vec;
  632. }
  633. v[i] = fast_atof(&s);
  634. SkipSpaces(&s);
  635. if (i != 1 && *s != ',') {
  636. LogError("expected comma, failed to parse vec2");
  637. return vec;
  638. }
  639. ++s;
  640. }
  641. vec.x = v[0];
  642. vec.y = v[1];
  643. return vec;
  644. }
  645. // ------------------------------------------------------------------------------------------------
  646. aiVector3D XGLImporter::ReadVec3(XmlNode &node) {
  647. aiVector3D vec;
  648. std::string v;
  649. XmlParser::getValueAsString(node, v);
  650. const char *s = v.c_str();
  651. for (int i = 0; i < 3; ++i) {
  652. if (!SkipSpaces(&s)) {
  653. LogError("unexpected EOL, failed to parse vec3");
  654. return vec;
  655. }
  656. vec[i] = fast_atof(&s);
  657. SkipSpaces(&s);
  658. if (i != 2 && *s != ',') {
  659. LogError("expected comma, failed to parse vec3");
  660. return vec;
  661. }
  662. ++s;
  663. }
  664. return vec;
  665. }
  666. // ------------------------------------------------------------------------------------------------
  667. aiColor3D XGLImporter::ReadCol3(XmlNode &node) {
  668. const aiVector3D &v = ReadVec3(node);
  669. 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) {
  670. LogWarn("color values out of range, ignoring");
  671. }
  672. return aiColor3D(v.x, v.y, v.z);
  673. }
  674. } // namespace Assimp
  675. #endif // ASSIMP_BUILD_NO_XGL_IMPORTER