IRRLoader.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, 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 IRRLoader.cpp
  35. * @brief Implementation of the Irr importer class
  36. */
  37. #include "assimp/Exceptional.h"
  38. #include "assimp/StringComparison.h"
  39. #ifndef ASSIMP_BUILD_NO_IRR_IMPORTER
  40. #include "IRRLoader.h"
  41. #include "Common/Importer.h"
  42. #include <assimp/GenericProperty.h>
  43. #include <assimp/MathFunctions.h>
  44. #include <assimp/ParsingUtils.h>
  45. #include <assimp/SceneCombiner.h>
  46. #include <assimp/StandardShapes.h>
  47. #include <assimp/fast_atof.h>
  48. #include <assimp/importerdesc.h>
  49. #include <assimp/material.h>
  50. #include <assimp/mesh.h>
  51. #include <assimp/postprocess.h>
  52. #include <assimp/scene.h>
  53. #include <assimp/DefaultLogger.hpp>
  54. #include <assimp/IOSystem.hpp>
  55. using namespace Assimp;
  56. static constexpr aiImporterDesc desc = {
  57. "Irrlicht Scene Reader",
  58. "",
  59. "",
  60. "http://irrlicht.sourceforge.net/",
  61. aiImporterFlags_SupportTextFlavour,
  62. 0,
  63. 0,
  64. 0,
  65. 0,
  66. "irr xml"
  67. };
  68. // ------------------------------------------------------------------------------------------------
  69. // Constructor to be privately used by Importer
  70. IRRImporter::IRRImporter() :
  71. fps(), configSpeedFlag() {
  72. // empty
  73. }
  74. // ------------------------------------------------------------------------------------------------
  75. // Destructor, private as well
  76. IRRImporter::~IRRImporter() = default;
  77. // ------------------------------------------------------------------------------------------------
  78. // Returns whether the class can handle the format of the given file.
  79. bool IRRImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  80. static const char *tokens[] = { "irr_scene" };
  81. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. const aiImporterDesc *IRRImporter::GetInfo() const {
  85. return &desc;
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. void IRRImporter::SetupProperties(const Importer *pImp) {
  89. // read the output frame rate of all node animation channels
  90. fps = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_IRR_ANIM_FPS, 100);
  91. if (fps < 10.) {
  92. ASSIMP_LOG_ERROR("IRR: Invalid FPS configuration");
  93. fps = 100;
  94. }
  95. // AI_CONFIG_FAVOUR_SPEED
  96. configSpeedFlag = (0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED, 0));
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. // Build a mesh that consists of a single squad (a side of a skybox)
  100. aiMesh *IRRImporter::BuildSingleQuadMesh(const SkyboxVertex &v1,
  101. const SkyboxVertex &v2,
  102. const SkyboxVertex &v3,
  103. const SkyboxVertex &v4) {
  104. // allocate and prepare the mesh
  105. aiMesh *out = new aiMesh();
  106. out->mPrimitiveTypes = aiPrimitiveType_POLYGON;
  107. out->mNumFaces = 1;
  108. // build the face
  109. out->mFaces = new aiFace[1];
  110. aiFace &face = out->mFaces[0];
  111. face.mNumIndices = 4;
  112. face.mIndices = new unsigned int[4];
  113. for (unsigned int i = 0; i < 4; ++i)
  114. face.mIndices[i] = i;
  115. out->mNumVertices = 4;
  116. // copy vertex positions
  117. aiVector3D *vec = out->mVertices = new aiVector3D[4];
  118. *vec++ = v1.position;
  119. *vec++ = v2.position;
  120. *vec++ = v3.position;
  121. *vec = v4.position;
  122. // copy vertex normals
  123. vec = out->mNormals = new aiVector3D[4];
  124. *vec++ = v1.normal;
  125. *vec++ = v2.normal;
  126. *vec++ = v3.normal;
  127. *vec = v4.normal;
  128. // copy texture coordinates
  129. vec = out->mTextureCoords[0] = new aiVector3D[4];
  130. *vec++ = v1.uv;
  131. *vec++ = v2.uv;
  132. *vec++ = v3.uv;
  133. *vec = v4.uv;
  134. return out;
  135. }
  136. // ------------------------------------------------------------------------------------------------
  137. void IRRImporter::BuildSkybox(std::vector<aiMesh *> &meshes, std::vector<aiMaterial *> materials) {
  138. // Update the material of the skybox - replace the name and disable shading for skyboxes.
  139. for (unsigned int i = 0; i < 6; ++i) {
  140. aiMaterial *out = (aiMaterial *)(*(materials.end() - (6 - i)));
  141. aiString s;
  142. s.length = ::ai_snprintf(s.data, AI_MAXLEN, "SkyboxSide_%u", i);
  143. out->AddProperty(&s, AI_MATKEY_NAME);
  144. int shading = aiShadingMode_NoShading;
  145. out->AddProperty(&shading, 1, AI_MATKEY_SHADING_MODEL);
  146. }
  147. // Skyboxes are much more difficult. They are represented
  148. // by six single planes with different textures, so we'll
  149. // need to build six meshes.
  150. const ai_real l = 10.0; // the size used by Irrlicht
  151. // FRONT SIDE
  152. meshes.push_back(BuildSingleQuadMesh(
  153. SkyboxVertex(-l, -l, -l, 0, 0, 1, 1.0, 1.0),
  154. SkyboxVertex(l, -l, -l, 0, 0, 1, 0.0, 1.0),
  155. SkyboxVertex(l, l, -l, 0, 0, 1, 0.0, 0.0),
  156. SkyboxVertex(-l, l, -l, 0, 0, 1, 1.0, 0.0)));
  157. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size() - 6u);
  158. // LEFT SIDE
  159. meshes.push_back(BuildSingleQuadMesh(
  160. SkyboxVertex(l, -l, -l, -1, 0, 0, 1.0, 1.0),
  161. SkyboxVertex(l, -l, l, -1, 0, 0, 0.0, 1.0),
  162. SkyboxVertex(l, l, l, -1, 0, 0, 0.0, 0.0),
  163. SkyboxVertex(l, l, -l, -1, 0, 0, 1.0, 0.0)));
  164. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size() - 5u);
  165. // BACK SIDE
  166. meshes.push_back(BuildSingleQuadMesh(
  167. SkyboxVertex(l, -l, l, 0, 0, -1, 1.0, 1.0),
  168. SkyboxVertex(-l, -l, l, 0, 0, -1, 0.0, 1.0),
  169. SkyboxVertex(-l, l, l, 0, 0, -1, 0.0, 0.0),
  170. SkyboxVertex(l, l, l, 0, 0, -1, 1.0, 0.0)));
  171. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size() - 4u);
  172. // RIGHT SIDE
  173. meshes.push_back(BuildSingleQuadMesh(
  174. SkyboxVertex(-l, -l, l, 1, 0, 0, 1.0, 1.0),
  175. SkyboxVertex(-l, -l, -l, 1, 0, 0, 0.0, 1.0),
  176. SkyboxVertex(-l, l, -l, 1, 0, 0, 0.0, 0.0),
  177. SkyboxVertex(-l, l, l, 1, 0, 0, 1.0, 0.0)));
  178. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size() - 3u);
  179. // TOP SIDE
  180. meshes.push_back(BuildSingleQuadMesh(
  181. SkyboxVertex(l, l, -l, 0, -1, 0, 1.0, 1.0),
  182. SkyboxVertex(l, l, l, 0, -1, 0, 0.0, 1.0),
  183. SkyboxVertex(-l, l, l, 0, -1, 0, 0.0, 0.0),
  184. SkyboxVertex(-l, l, -l, 0, -1, 0, 1.0, 0.0)));
  185. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size() - 2u);
  186. // BOTTOM SIDE
  187. meshes.push_back(BuildSingleQuadMesh(
  188. SkyboxVertex(l, -l, l, 0, 1, 0, 0.0, 0.0),
  189. SkyboxVertex(l, -l, -l, 0, 1, 0, 1.0, 0.0),
  190. SkyboxVertex(-l, -l, -l, 0, 1, 0, 1.0, 1.0),
  191. SkyboxVertex(-l, -l, l, 0, 1, 0, 0.0, 1.0)));
  192. meshes.back()->mMaterialIndex = static_cast<unsigned int>(materials.size() - 1u);
  193. }
  194. // ------------------------------------------------------------------------------------------------
  195. void IRRImporter::CopyMaterial(std::vector<aiMaterial *> &materials,
  196. std::vector<std::pair<aiMaterial *, unsigned int>> &inmaterials,
  197. unsigned int &defMatIdx,
  198. aiMesh *mesh) {
  199. if (inmaterials.empty()) {
  200. // Do we have a default material? If not we need to create one
  201. if (UINT_MAX == defMatIdx) {
  202. defMatIdx = (unsigned int)materials.size();
  203. // TODO: add this materials to someone?
  204. /*aiMaterial* mat = new aiMaterial();
  205. aiString s;
  206. s.Set(AI_DEFAULT_MATERIAL_NAME);
  207. mat->AddProperty(&s,AI_MATKEY_NAME);
  208. aiColor3D c(0.6f,0.6f,0.6f);
  209. mat->AddProperty(&c,1,AI_MATKEY_COLOR_DIFFUSE);*/
  210. }
  211. mesh->mMaterialIndex = defMatIdx;
  212. return;
  213. } else if (inmaterials.size() > 1) {
  214. ASSIMP_LOG_INFO("IRR: Skipping additional materials");
  215. }
  216. mesh->mMaterialIndex = (unsigned int)materials.size();
  217. materials.push_back(inmaterials[0].first);
  218. }
  219. // ------------------------------------------------------------------------------------------------
  220. inline int ClampSpline(int idx, int size) {
  221. return (idx < 0 ? size + idx : (idx >= size ? idx - size : idx));
  222. }
  223. // ------------------------------------------------------------------------------------------------
  224. inline void FindSuitableMultiple(int &angle) {
  225. if (angle < 3)
  226. angle = 3;
  227. else if (angle < 10)
  228. angle = 10;
  229. else if (angle < 20)
  230. angle = 20;
  231. else if (angle < 30)
  232. angle = 30;
  233. }
  234. // ------------------------------------------------------------------------------------------------
  235. void IRRImporter::ComputeAnimations(Node *root, aiNode *real, std::vector<aiNodeAnim *> &anims) {
  236. ai_assert(nullptr != root && nullptr != real);
  237. // XXX totally WIP - doesn't produce proper results, need to evaluate
  238. // whether there's any use for Irrlicht's proprietary scene format
  239. // outside Irrlicht ...
  240. // This also applies to the above function of FindSuitableMultiple and ClampSpline which are
  241. // solely used in this function
  242. if (root->animators.empty()) {
  243. return;
  244. }
  245. unsigned int total(0);
  246. for (std::list<Animator>::iterator it = root->animators.begin(); it != root->animators.end(); ++it) {
  247. if ((*it).type == Animator::UNKNOWN || (*it).type == Animator::OTHER) {
  248. ASSIMP_LOG_WARN("IRR: Skipping unknown or unsupported animator");
  249. continue;
  250. }
  251. ++total;
  252. }
  253. if (!total) {
  254. return;
  255. } else if (1 == total) {
  256. ASSIMP_LOG_WARN("IRR: Adding dummy nodes to simulate multiple animators");
  257. }
  258. // NOTE: 1 tick == i millisecond
  259. unsigned int cur = 0;
  260. for (std::list<Animator>::iterator it = root->animators.begin();
  261. it != root->animators.end(); ++it) {
  262. if ((*it).type == Animator::UNKNOWN || (*it).type == Animator::OTHER) continue;
  263. Animator &in = *it;
  264. aiNodeAnim *anim = new aiNodeAnim();
  265. if (cur != total - 1) {
  266. // Build a new name - a prefix instead of a suffix because it is
  267. // easier to check against
  268. anim->mNodeName.length = ::ai_snprintf(anim->mNodeName.data, AI_MAXLEN,
  269. "$INST_DUMMY_%i_%s", total - 1,
  270. (root->name.length() ? root->name.c_str() : ""));
  271. // we'll also need to insert a dummy in the node hierarchy.
  272. aiNode *dummy = new aiNode();
  273. for (unsigned int i = 0; i < real->mParent->mNumChildren; ++i)
  274. if (real->mParent->mChildren[i] == real)
  275. real->mParent->mChildren[i] = dummy;
  276. dummy->mParent = real->mParent;
  277. dummy->mName = anim->mNodeName;
  278. dummy->mNumChildren = 1;
  279. dummy->mChildren = new aiNode *[dummy->mNumChildren];
  280. dummy->mChildren[0] = real;
  281. // the transformation matrix of the dummy node is the identity
  282. real->mParent = dummy;
  283. } else
  284. anim->mNodeName.Set(root->name);
  285. ++cur;
  286. switch (in.type) {
  287. case Animator::ROTATION: {
  288. // -----------------------------------------------------
  289. // find out how long a full rotation will take
  290. // This is the least common multiple of 360.f and all
  291. // three euler angles. Although we'll surely find a
  292. // possible multiple (haha) it could be somewhat large
  293. // for our purposes. So we need to modify the angles
  294. // here in order to get good results.
  295. // -----------------------------------------------------
  296. int angles[3];
  297. angles[0] = (int)(in.direction.x * 100);
  298. angles[1] = (int)(in.direction.y * 100);
  299. angles[2] = (int)(in.direction.z * 100);
  300. angles[0] %= 360;
  301. angles[1] %= 360;
  302. angles[2] %= 360;
  303. if ((angles[0] * angles[1]) != 0 && (angles[1] * angles[2]) != 0) {
  304. FindSuitableMultiple(angles[0]);
  305. FindSuitableMultiple(angles[1]);
  306. FindSuitableMultiple(angles[2]);
  307. }
  308. int lcm = 360;
  309. if (angles[0])
  310. lcm = Math::lcm(lcm, angles[0]);
  311. if (angles[1])
  312. lcm = Math::lcm(lcm, angles[1]);
  313. if (angles[2])
  314. lcm = Math::lcm(lcm, angles[2]);
  315. if (360 == lcm)
  316. break;
  317. // find out how many time units we'll need for the finest
  318. // track (in seconds) - this defines the number of output
  319. // keys (fps * seconds)
  320. float max = 0.f;
  321. if (angles[0])
  322. max = (float)lcm / angles[0];
  323. if (angles[1])
  324. max = std::max(max, (float)lcm / angles[1]);
  325. if (angles[2])
  326. max = std::max(max, (float)lcm / angles[2]);
  327. anim->mNumRotationKeys = (unsigned int)(max * fps);
  328. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  329. // begin with a zero angle
  330. aiVector3D angle;
  331. for (unsigned int i = 0; i < anim->mNumRotationKeys; ++i) {
  332. // build the quaternion for the given euler angles
  333. aiQuatKey &q = anim->mRotationKeys[i];
  334. q.mValue = aiQuaternion(angle.x, angle.y, angle.z);
  335. q.mTime = (double)i;
  336. // increase the angle
  337. angle += in.direction;
  338. }
  339. // This animation is repeated and repeated ...
  340. anim->mPostState = anim->mPreState = aiAnimBehaviour_REPEAT;
  341. } break;
  342. case Animator::FLY_CIRCLE: {
  343. // -----------------------------------------------------
  344. // Find out how much time we'll need to perform a
  345. // full circle.
  346. // -----------------------------------------------------
  347. const double seconds = (1. / in.speed) / 1000.;
  348. const double tdelta = 1000. / fps;
  349. anim->mNumPositionKeys = (unsigned int)(fps * seconds);
  350. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  351. // from Irrlicht, what else should we do than copying it?
  352. aiVector3D vecU, vecV;
  353. if (in.direction.y) {
  354. vecV = aiVector3D(50, 0, 0) ^ in.direction;
  355. } else
  356. vecV = aiVector3D(0, 50, 00) ^ in.direction;
  357. vecV.Normalize();
  358. vecU = (vecV ^ in.direction).Normalize();
  359. // build the output keys
  360. for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) {
  361. aiVectorKey &key = anim->mPositionKeys[i];
  362. key.mTime = i * tdelta;
  363. const ai_real t = (ai_real)(in.speed * key.mTime);
  364. key.mValue = in.circleCenter + in.circleRadius * ((vecU * std::cos(t)) + (vecV * std::sin(t)));
  365. }
  366. // This animation is repeated and repeated ...
  367. anim->mPostState = anim->mPreState = aiAnimBehaviour_REPEAT;
  368. } break;
  369. case Animator::FLY_STRAIGHT: {
  370. anim->mPostState = anim->mPreState = (in.loop ? aiAnimBehaviour_REPEAT : aiAnimBehaviour_CONSTANT);
  371. const double seconds = in.timeForWay / 1000.;
  372. const double tdelta = 1000. / fps;
  373. anim->mNumPositionKeys = (unsigned int)(fps * seconds);
  374. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  375. aiVector3D diff = in.direction - in.circleCenter;
  376. const ai_real lengthOfWay = diff.Length();
  377. diff.Normalize();
  378. const double timeFactor = lengthOfWay / in.timeForWay;
  379. // build the output keys
  380. for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) {
  381. aiVectorKey &key = anim->mPositionKeys[i];
  382. key.mTime = i * tdelta;
  383. key.mValue = in.circleCenter + diff * ai_real(timeFactor * key.mTime);
  384. }
  385. } break;
  386. case Animator::FOLLOW_SPLINE: {
  387. // repeat outside the defined time range
  388. anim->mPostState = anim->mPreState = aiAnimBehaviour_REPEAT;
  389. const int size = (int)in.splineKeys.size();
  390. if (!size) {
  391. // We have no point in the spline. That's bad. Really bad.
  392. ASSIMP_LOG_WARN("IRR: Spline animators with no points defined");
  393. delete anim;
  394. anim = nullptr;
  395. break;
  396. } else if (size == 1) {
  397. // We have just one point in the spline so we don't need the full calculation
  398. anim->mNumPositionKeys = 1;
  399. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  400. anim->mPositionKeys[0].mValue = in.splineKeys[0].mValue;
  401. anim->mPositionKeys[0].mTime = 0.f;
  402. break;
  403. }
  404. unsigned int ticksPerFull = 15;
  405. anim->mNumPositionKeys = (unsigned int)(ticksPerFull * fps);
  406. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  407. for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) {
  408. aiVectorKey &key = anim->mPositionKeys[i];
  409. const ai_real dt = (i * in.speed * ai_real(0.001));
  410. const ai_real u = dt - std::floor(dt);
  411. const int idx = (int)std::floor(dt) % size;
  412. // get the 4 current points to evaluate the spline
  413. const aiVector3D &p0 = in.splineKeys[ClampSpline(idx - 1, size)].mValue;
  414. const aiVector3D &p1 = in.splineKeys[ClampSpline(idx + 0, size)].mValue;
  415. const aiVector3D &p2 = in.splineKeys[ClampSpline(idx + 1, size)].mValue;
  416. const aiVector3D &p3 = in.splineKeys[ClampSpline(idx + 2, size)].mValue;
  417. // compute polynomials
  418. const ai_real u2 = u * u;
  419. const ai_real u3 = u2 * 2;
  420. const ai_real h1 = ai_real(2.0) * u3 - ai_real(3.0) * u2 + ai_real(1.0);
  421. const ai_real h2 = ai_real(-2.0) * u3 + ai_real(3.0) * u3;
  422. const ai_real h3 = u3 - ai_real(2.0) * u3;
  423. const ai_real h4 = u3 - u2;
  424. // compute the spline tangents
  425. const aiVector3D t1 = (p2 - p0) * in.tightness;
  426. aiVector3D t2 = (p3 - p1) * in.tightness;
  427. // and use them to get the interpolated point
  428. t2 = (h1 * p1 + p2 * h2 + t1 * h3 + h4 * t2);
  429. // build a simple translation matrix from it
  430. key.mValue = t2;
  431. key.mTime = (double)i;
  432. }
  433. } break;
  434. default:
  435. // UNKNOWN , OTHER
  436. break;
  437. };
  438. if (anim) {
  439. anims.push_back(anim);
  440. ++total;
  441. }
  442. }
  443. }
  444. // ------------------------------------------------------------------------------------------------
  445. // This function is maybe more generic than we'd need it here
  446. void SetupMapping(aiMaterial *mat, aiTextureMapping mode, const aiVector3D &axis = aiVector3D(0.f, 0.f, -1.f)) {
  447. if (nullptr == mat) {
  448. return;
  449. }
  450. // Check whether there are texture properties defined - setup
  451. // the desired texture mapping mode for all of them and ignore
  452. // all UV settings we might encounter. WE HAVE NO UVS!
  453. std::vector<aiMaterialProperty *> p;
  454. p.reserve(mat->mNumProperties + 1);
  455. for (unsigned int i = 0; i < mat->mNumProperties; ++i) {
  456. aiMaterialProperty *prop = mat->mProperties[i];
  457. if (!::strcmp(prop->mKey.data, "$tex.file")) {
  458. // Setup the mapping key
  459. aiMaterialProperty *m = new aiMaterialProperty();
  460. m->mKey.Set("$tex.mapping");
  461. m->mIndex = prop->mIndex;
  462. m->mSemantic = prop->mSemantic;
  463. m->mType = aiPTI_Integer;
  464. m->mDataLength = 4;
  465. m->mData = new char[4];
  466. *((int *)m->mData) = mode;
  467. p.push_back(prop);
  468. p.push_back(m);
  469. // Setup the mapping axis
  470. if (mode == aiTextureMapping_CYLINDER || mode == aiTextureMapping_PLANE || mode == aiTextureMapping_SPHERE) {
  471. m = new aiMaterialProperty();
  472. m->mKey.Set("$tex.mapaxis");
  473. m->mIndex = prop->mIndex;
  474. m->mSemantic = prop->mSemantic;
  475. m->mType = aiPTI_Float;
  476. m->mDataLength = sizeof(aiVector3D);
  477. m->mData = new char[m->mDataLength];
  478. *((aiVector3D *)m->mData) = axis;
  479. p.push_back(m);
  480. }
  481. } else if (!::strcmp(prop->mKey.data, "$tex.uvwsrc")) {
  482. delete mat->mProperties[i];
  483. } else
  484. p.push_back(prop);
  485. }
  486. if (p.empty()) return;
  487. // rebuild the output array
  488. if (p.size() > mat->mNumAllocated) {
  489. delete[] mat->mProperties;
  490. mat->mProperties = new aiMaterialProperty *[p.size() * 2];
  491. mat->mNumAllocated = static_cast<unsigned int>(p.size() * 2);
  492. }
  493. mat->mNumProperties = (unsigned int)p.size();
  494. ::memcpy(mat->mProperties, &p[0], sizeof(void *) * mat->mNumProperties);
  495. }
  496. // ------------------------------------------------------------------------------------------------
  497. void IRRImporter::GenerateGraph(Node *root, aiNode *rootOut, aiScene *scene,
  498. BatchLoader &batch,
  499. std::vector<aiMesh *> &meshes,
  500. std::vector<aiNodeAnim *> &anims,
  501. std::vector<AttachmentInfo> &attach,
  502. std::vector<aiMaterial *> &materials,
  503. unsigned int &defMatIdx) {
  504. unsigned int oldMeshSize = (unsigned int)meshes.size();
  505. // unsigned int meshTrafoAssign = 0;
  506. // Now determine the type of the node
  507. switch (root->type) {
  508. case Node::ANIMMESH:
  509. case Node::MESH: {
  510. if (!root->meshPath.length())
  511. break;
  512. // Get the loaded mesh from the scene and add it to
  513. // the list of all scenes to be attached to the
  514. // graph we're currently building
  515. aiScene *localScene = batch.GetImport(root->id);
  516. if (!localScene) {
  517. ASSIMP_LOG_ERROR("IRR: Unable to load external file: ", root->meshPath);
  518. break;
  519. }
  520. attach.emplace_back(localScene, rootOut);
  521. // Now combine the material we've loaded for this mesh
  522. // with the real materials we got from the file. As we
  523. // don't execute any pp-steps on the file, the numbers
  524. // should be equal. If they are not, we can impossibly
  525. // do this ...
  526. if (root->materials.size() != (unsigned int)localScene->mNumMaterials) {
  527. ASSIMP_LOG_WARN("IRR: Failed to match imported materials "
  528. "with the materials found in the IRR scene file");
  529. break;
  530. }
  531. for (unsigned int i = 0; i < localScene->mNumMaterials; ++i) {
  532. // Delete the old material, we don't need it anymore
  533. delete localScene->mMaterials[i];
  534. std::pair<aiMaterial *, unsigned int> &src = root->materials[i];
  535. localScene->mMaterials[i] = src.first;
  536. }
  537. // NOTE: Each mesh should have exactly one material assigned,
  538. // but we do it in a separate loop if this behavior changes
  539. // in future.
  540. for (unsigned int i = 0; i < localScene->mNumMeshes; ++i) {
  541. // Process material flags
  542. aiMesh *mesh = localScene->mMeshes[i];
  543. // If "trans_vertex_alpha" mode is enabled, search all vertex colors
  544. // and check whether they have a common alpha value. This is quite
  545. // often the case so we can simply extract it to a shared oacity
  546. // value.
  547. std::pair<aiMaterial *, unsigned int> &src = root->materials[mesh->mMaterialIndex];
  548. aiMaterial *mat = (aiMaterial *)src.first;
  549. if (mesh->HasVertexColors(0) && src.second & AI_IRRMESH_MAT_trans_vertex_alpha) {
  550. bool bdo = true;
  551. for (unsigned int a = 1; a < mesh->mNumVertices; ++a) {
  552. if (mesh->mColors[0][a].a != mesh->mColors[0][a - 1].a) {
  553. bdo = false;
  554. break;
  555. }
  556. }
  557. if (bdo) {
  558. ASSIMP_LOG_INFO("IRR: Replacing mesh vertex alpha with common opacity");
  559. for (unsigned int a = 0; a < mesh->mNumVertices; ++a)
  560. mesh->mColors[0][a].a = 1.f;
  561. mat->AddProperty(&mesh->mColors[0][0].a, 1, AI_MATKEY_OPACITY);
  562. }
  563. }
  564. // If we have a second texture coordinate set and a second texture
  565. // (either light-map, normal-map, 2layered material) we need to
  566. // setup the correct UV index for it. The texture can either
  567. // be diffuse (light-map & 2layer) or a normal map (normal & parallax)
  568. if (mesh->HasTextureCoords(1)) {
  569. int idx = 1;
  570. if (src.second & (AI_IRRMESH_MAT_solid_2layer | AI_IRRMESH_MAT_lightmap)) {
  571. mat->AddProperty(&idx, 1, AI_MATKEY_UVWSRC_DIFFUSE(0));
  572. } else if (src.second & AI_IRRMESH_MAT_normalmap_solid) {
  573. mat->AddProperty(&idx, 1, AI_MATKEY_UVWSRC_NORMALS(0));
  574. }
  575. }
  576. }
  577. } break;
  578. case Node::LIGHT:
  579. case Node::CAMERA:
  580. // We're already finished with lights and cameras
  581. break;
  582. case Node::SPHERE: {
  583. // Generate the sphere model. Our input parameter to
  584. // the sphere generation algorithm is the number of
  585. // subdivisions of each triangle - but here we have
  586. // the number of polygons on a specific axis. Just
  587. // use some hard-coded limits to approximate this ...
  588. unsigned int mul = root->spherePolyCountX * root->spherePolyCountY;
  589. if (mul < 100)
  590. mul = 2;
  591. else if (mul < 300)
  592. mul = 3;
  593. else
  594. mul = 4;
  595. meshes.push_back(StandardShapes::MakeMesh(mul,
  596. &StandardShapes::MakeSphere));
  597. // Adjust scaling
  598. root->scaling *= root->sphereRadius / 2;
  599. // Copy one output material
  600. CopyMaterial(materials, root->materials, defMatIdx, meshes.back());
  601. // Now adjust this output material - if there is a first texture
  602. // set, setup spherical UV mapping around the Y axis.
  603. SetupMapping((aiMaterial *)materials.back(), aiTextureMapping_SPHERE);
  604. } break;
  605. case Node::CUBE: {
  606. // Generate an unit cube first
  607. meshes.push_back(StandardShapes::MakeMesh(
  608. &StandardShapes::MakeHexahedron));
  609. // Adjust scaling
  610. root->scaling *= root->sphereRadius;
  611. // Copy one output material
  612. CopyMaterial(materials, root->materials, defMatIdx, meshes.back());
  613. // Now adjust this output material - if there is a first texture
  614. // set, setup cubic UV mapping
  615. SetupMapping((aiMaterial *)materials.back(), aiTextureMapping_BOX);
  616. } break;
  617. case Node::SKYBOX: {
  618. // A sky-box is defined by six materials
  619. if (root->materials.size() < 6) {
  620. ASSIMP_LOG_ERROR("IRR: There should be six materials for a skybox");
  621. break;
  622. }
  623. // copy those materials and generate 6 meshes for our new sky-box
  624. materials.reserve(materials.size() + 6);
  625. for (unsigned int i = 0; i < 6; ++i)
  626. materials.insert(materials.end(), root->materials[i].first);
  627. BuildSkybox(meshes, materials);
  628. // *************************************************************
  629. // Skyboxes will require a different code path for rendering,
  630. // so there must be a way for the user to add special support
  631. // for IRR skyboxes. We add a 'IRR.SkyBox_' prefix to the node.
  632. // *************************************************************
  633. root->name = "IRR.SkyBox_" + root->name;
  634. ASSIMP_LOG_INFO("IRR: Loading skybox, this will "
  635. "require special handling to be displayed correctly");
  636. } break;
  637. case Node::TERRAIN: {
  638. // to support terrains, we'd need to have a texture decoder
  639. ASSIMP_LOG_ERROR("IRR: Unsupported node - TERRAIN");
  640. } break;
  641. default:
  642. // DUMMY
  643. break;
  644. };
  645. // Check whether we added a mesh (or more than one ...). In this case
  646. // we'll also need to attach it to the node
  647. if (oldMeshSize != (unsigned int)meshes.size()) {
  648. rootOut->mNumMeshes = (unsigned int)meshes.size() - oldMeshSize;
  649. rootOut->mMeshes = new unsigned int[rootOut->mNumMeshes];
  650. for (unsigned int a = 0; a < rootOut->mNumMeshes; ++a) {
  651. rootOut->mMeshes[a] = oldMeshSize + a;
  652. }
  653. }
  654. // Setup the name of this node
  655. rootOut->mName.Set(root->name);
  656. // Now compute the final local transformation matrix of the
  657. // node from the given translation, rotation and scaling values.
  658. // (the rotation is given in Euler angles, XYZ order)
  659. // std::swap((float&)root->rotation.z,(float&)root->rotation.y);
  660. rootOut->mTransformation.FromEulerAnglesXYZ(AI_DEG_TO_RAD(root->rotation));
  661. // apply scaling
  662. aiMatrix4x4 &mat = rootOut->mTransformation;
  663. mat.a1 *= root->scaling.x;
  664. mat.b1 *= root->scaling.x;
  665. mat.c1 *= root->scaling.x;
  666. mat.a2 *= root->scaling.y;
  667. mat.b2 *= root->scaling.y;
  668. mat.c2 *= root->scaling.y;
  669. mat.a3 *= root->scaling.z;
  670. mat.b3 *= root->scaling.z;
  671. mat.c3 *= root->scaling.z;
  672. // apply translation
  673. mat.a4 += root->position.x;
  674. mat.b4 += root->position.y;
  675. mat.c4 += root->position.z;
  676. // now compute animations for the node
  677. ComputeAnimations(root, rootOut, anims);
  678. // Add all children recursively. First allocate enough storage
  679. // for them, then call us again
  680. rootOut->mNumChildren = (unsigned int)root->children.size();
  681. if (rootOut->mNumChildren) {
  682. rootOut->mChildren = new aiNode *[rootOut->mNumChildren];
  683. for (unsigned int i = 0; i < rootOut->mNumChildren; ++i) {
  684. aiNode *node = rootOut->mChildren[i] = new aiNode();
  685. node->mParent = rootOut;
  686. GenerateGraph(root->children[i], node, scene, batch, meshes,
  687. anims, attach, materials, defMatIdx);
  688. }
  689. }
  690. }
  691. void IRRImporter::ParseNodeAttributes(pugi::xml_node &attributesNode, IRRImporter::Node *nd, BatchLoader &batch) {
  692. ai_assert(!ASSIMP_stricmp(attributesNode.name(), "attributes")); // Node must be <attributes>
  693. ai_assert(nd != nullptr); // dude
  694. // Big switch statement that tests for various tags inside <attributes>
  695. // and applies them to nd
  696. // I don't believe nodes have boolean attributes
  697. for (pugi::xml_node &attribute : attributesNode.children()) {
  698. if (attribute.type() != pugi::node_element) continue;
  699. if (!ASSIMP_stricmp(attribute.name(), "vector3d")) { // <vector3d />
  700. VectorProperty prop;
  701. ReadVectorProperty(prop, attribute);
  702. if (prop.name == "Position") {
  703. nd->position = prop.value;
  704. } else if (prop.name == "Rotation") {
  705. nd->rotation = prop.value;
  706. } else if (prop.name == "Scale") {
  707. nd->scaling = prop.value;
  708. } else if (Node::CAMERA == nd->type) {
  709. aiCamera *cam = cameras.back();
  710. if (prop.name == "Target") {
  711. cam->mLookAt = prop.value;
  712. } else if (prop.name == "UpVector") {
  713. cam->mUp = prop.value;
  714. }
  715. }
  716. } else if (!ASSIMP_stricmp(attribute.name(), "float")) { // <float />
  717. FloatProperty prop;
  718. ReadFloatProperty(prop, attribute);
  719. if (prop.name == "FramesPerSecond" && Node::ANIMMESH == nd->type) {
  720. nd->framesPerSecond = prop.value;
  721. } else if (Node::CAMERA == nd->type) {
  722. /* This is the vertical, not the horizontal FOV.
  723. * We need to compute the right FOV from the
  724. * screen aspect which we don't know yet.
  725. */
  726. if (prop.name == "Fovy") {
  727. cameras.back()->mHorizontalFOV = prop.value;
  728. } else if (prop.name == "Aspect") {
  729. cameras.back()->mAspect = prop.value;
  730. } else if (prop.name == "ZNear") {
  731. cameras.back()->mClipPlaneNear = prop.value;
  732. } else if (prop.name == "ZFar") {
  733. cameras.back()->mClipPlaneFar = prop.value;
  734. }
  735. } else if (Node::LIGHT == nd->type) {
  736. /* Additional light information
  737. */
  738. if (prop.name == "Attenuation") {
  739. lights.back()->mAttenuationLinear = prop.value;
  740. } else if (prop.name == "OuterCone") {
  741. lights.back()->mAngleOuterCone = AI_DEG_TO_RAD(prop.value);
  742. } else if (prop.name == "InnerCone") {
  743. lights.back()->mAngleInnerCone = AI_DEG_TO_RAD(prop.value);
  744. }
  745. }
  746. // radius of the sphere to be generated -
  747. // or alternatively, size of the cube
  748. else if ((Node::SPHERE == nd->type && prop.name == "Radius") ||
  749. (Node::CUBE == nd->type && prop.name == "Size")) {
  750. nd->sphereRadius = prop.value;
  751. }
  752. } else if (!ASSIMP_stricmp(attribute.name(), "int")) { // <int />
  753. // Only sphere nodes make use of integer attributes
  754. if (Node::SPHERE == nd->type) {
  755. IntProperty prop;
  756. ReadIntProperty(prop, attribute);
  757. if (prop.name == "PolyCountX") {
  758. nd->spherePolyCountX = prop.value;
  759. } else if (prop.name == "PolyCountY") {
  760. nd->spherePolyCountY = prop.value;
  761. }
  762. }
  763. } else if (!ASSIMP_stricmp(attribute.name(), "string") || !ASSIMP_stricmp(attribute.name(), "enum")) { // <string /> or < enum />
  764. StringProperty prop;
  765. ReadStringProperty(prop, attribute);
  766. if (prop.value.length() == 0) continue; // skip empty strings
  767. if (prop.name == "Name") {
  768. nd->name = prop.value;
  769. /* If we're either a camera or a light source
  770. * we need to update the name in the aiLight/
  771. * aiCamera structure, too.
  772. */
  773. if (Node::CAMERA == nd->type) {
  774. cameras.back()->mName.Set(prop.value);
  775. } else if (Node::LIGHT == nd->type) {
  776. lights.back()->mName.Set(prop.value);
  777. }
  778. } else if (Node::LIGHT == nd->type && "LightType" == prop.name) {
  779. if (prop.value == "Spot")
  780. lights.back()->mType = aiLightSource_SPOT;
  781. else if (prop.value == "Point")
  782. lights.back()->mType = aiLightSource_POINT;
  783. else if (prop.value == "Directional")
  784. lights.back()->mType = aiLightSource_DIRECTIONAL;
  785. else {
  786. // We won't pass the validation with aiLightSourceType_UNDEFINED,
  787. // so we remove the light and replace it with a silly dummy node
  788. delete lights.back();
  789. lights.pop_back();
  790. nd->type = Node::DUMMY;
  791. ASSIMP_LOG_ERROR("Ignoring light of unknown type: ", prop.value);
  792. }
  793. } else if ((prop.name == "Mesh" && Node::MESH == nd->type) ||
  794. Node::ANIMMESH == nd->type) {
  795. /* This is the file name of the mesh - either
  796. * animated or not. We need to make sure we setup
  797. * the correct post-processing settings here.
  798. */
  799. unsigned int pp = 0;
  800. BatchLoader::PropertyMap map;
  801. /* If the mesh is a static one remove all animations from the impor data
  802. */
  803. if (Node::ANIMMESH != nd->type) {
  804. pp |= aiProcess_RemoveComponent;
  805. SetGenericProperty<int>(map.ints, AI_CONFIG_PP_RVC_FLAGS,
  806. aiComponent_ANIMATIONS | aiComponent_BONEWEIGHTS);
  807. }
  808. /* TODO: maybe implement the protection against recursive
  809. * loading calls directly in BatchLoader? The current
  810. * implementation is not absolutely safe. A LWS and an IRR
  811. * file referencing each other *could* cause the system to
  812. * recurse forever.
  813. */
  814. const std::string extension = GetExtension(prop.value);
  815. if ("irr" == extension) {
  816. ASSIMP_LOG_ERROR("IRR: Can't load another IRR file recursively");
  817. } else {
  818. nd->id = batch.AddLoadRequest(prop.value, pp, &map);
  819. nd->meshPath = prop.value;
  820. }
  821. }
  822. }
  823. }
  824. }
  825. void IRRImporter::ParseAnimators(pugi::xml_node &animatorNode, IRRImporter::Node *nd) {
  826. Animator *curAnim = nullptr;
  827. // Make empty animator
  828. nd->animators.emplace_back();
  829. curAnim = &nd->animators.back(); // Push it back
  830. pugi::xml_node attributes = animatorNode.child("attributes");
  831. if (!attributes) {
  832. ASSIMP_LOG_WARN("Animator node does not contain attributes. ");
  833. return;
  834. }
  835. for (pugi::xml_node attrib : attributes.children()) {
  836. // XML may contain useless noes like CDATA
  837. if (!ASSIMP_stricmp(attrib.name(), "vector3d")) {
  838. VectorProperty prop;
  839. ReadVectorProperty(prop, attrib);
  840. if (curAnim->type == Animator::ROTATION && prop.name == "Rotation") {
  841. // We store the rotation euler angles in 'direction'
  842. curAnim->direction = prop.value;
  843. } else if (curAnim->type == Animator::FOLLOW_SPLINE) {
  844. // Check whether the vector follows the PointN naming scheme,
  845. // here N is the ONE-based index of the point
  846. if (prop.name.length() >= 6 && prop.name.substr(0, 5) == "Point") {
  847. // Add a new key to the list
  848. curAnim->splineKeys.emplace_back();
  849. aiVectorKey &key = curAnim->splineKeys.back();
  850. // and parse its properties
  851. key.mValue = prop.value;
  852. key.mTime = strtoul10(&prop.name[5]);
  853. }
  854. } else if (curAnim->type == Animator::FLY_CIRCLE) {
  855. if (prop.name == "Center") {
  856. curAnim->circleCenter = prop.value;
  857. } else if (prop.name == "Direction") {
  858. curAnim->direction = prop.value;
  859. // From Irrlicht's source - a workaround for backward compatibility with Irrlicht 1.1
  860. if (curAnim->direction == aiVector3D()) {
  861. curAnim->direction = aiVector3D(0.f, 1.f, 0.f);
  862. } else
  863. curAnim->direction.Normalize();
  864. }
  865. } else if (curAnim->type == Animator::FLY_STRAIGHT) {
  866. if (prop.name == "Start") {
  867. // We reuse the field here
  868. curAnim->circleCenter = prop.value;
  869. } else if (prop.name == "End") {
  870. // We reuse the field here
  871. curAnim->direction = prop.value;
  872. }
  873. }
  874. //} else if (!ASSIMP_stricmp(reader->getNodeName(), "bool")) {
  875. } else if (!ASSIMP_stricmp(attrib.name(), "bool")) {
  876. BoolProperty prop;
  877. ReadBoolProperty(prop, attrib);
  878. if (curAnim->type == Animator::FLY_CIRCLE && prop.name == "Loop") {
  879. curAnim->loop = prop.value;
  880. }
  881. //} else if (!ASSIMP_stricmp(reader->getNodeName(), "float")) {
  882. } else if (!ASSIMP_stricmp(attrib.name(), "float")) {
  883. FloatProperty prop;
  884. ReadFloatProperty(prop, attrib);
  885. // The speed property exists for several animators
  886. if (prop.name == "Speed") {
  887. curAnim->speed = prop.value;
  888. } else if (curAnim->type == Animator::FLY_CIRCLE && prop.name == "Radius") {
  889. curAnim->circleRadius = prop.value;
  890. } else if (curAnim->type == Animator::FOLLOW_SPLINE && prop.name == "Tightness") {
  891. curAnim->tightness = prop.value;
  892. }
  893. //} else if (!ASSIMP_stricmp(reader->getNodeName(), "int")) {
  894. } else if (!ASSIMP_stricmp(attrib.name(), "int")) {
  895. IntProperty prop;
  896. ReadIntProperty(prop, attrib);
  897. if (curAnim->type == Animator::FLY_STRAIGHT && prop.name == "TimeForWay") {
  898. curAnim->timeForWay = prop.value;
  899. }
  900. //} else if (!ASSIMP_stricmp(reader->getNodeName(), "string") || !ASSIMP_stricmp(reader->getNodeName(), "enum")) {
  901. } else if (!ASSIMP_stricmp(attrib.name(), "string") || !ASSIMP_stricmp(attrib.name(), "enum")) {
  902. StringProperty prop;
  903. ReadStringProperty(prop, attrib);
  904. if (prop.name == "Type") {
  905. // type of the animator
  906. if (prop.value == "rotation") {
  907. curAnim->type = Animator::ROTATION;
  908. } else if (prop.value == "flyCircle") {
  909. curAnim->type = Animator::FLY_CIRCLE;
  910. } else if (prop.value == "flyStraight") {
  911. curAnim->type = Animator::FLY_CIRCLE;
  912. } else if (prop.value == "followSpline") {
  913. curAnim->type = Animator::FOLLOW_SPLINE;
  914. } else {
  915. ASSIMP_LOG_WARN("IRR: Ignoring unknown animator: ", prop.value);
  916. curAnim->type = Animator::UNKNOWN;
  917. }
  918. }
  919. }
  920. }
  921. }
  922. IRRImporter::Node *IRRImporter::ParseNode(pugi::xml_node &node, BatchLoader &batch) {
  923. // Parse <node> tags.
  924. // <node> tags have various types
  925. // <node> tags can contain <attribute>, <material>
  926. // they can also contain other <node> tags, (and can reference other files as well?)
  927. // ***********************************************************************
  928. /* What we're going to do with the node depends
  929. * on its type:
  930. *
  931. * "mesh" - Load a mesh from an external file
  932. * "cube" - Generate a cube
  933. * "skybox" - Generate a skybox
  934. * "light" - A light source
  935. * "sphere" - Generate a sphere mesh
  936. * "animatedMesh" - Load an animated mesh from an external file
  937. * and join its animation channels with ours.
  938. * "empty" - A dummy node
  939. * "camera" - A camera
  940. * "terrain" - a terrain node (data comes from a heightmap)
  941. * "billboard", ""
  942. *
  943. * Each of these nodes can be animated and all can have multiple
  944. * materials assigned (except lights, cameras and dummies, of course).
  945. * Said materials and animators are all collected at the bottom
  946. */
  947. // ***********************************************************************
  948. Node *nd;
  949. pugi::xml_attribute nodeTypeAttrib = node.attribute("type");
  950. if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "mesh") || !ASSIMP_stricmp(nodeTypeAttrib.value(), "octTree")) {
  951. // OctTree's and meshes are treated equally
  952. nd = new Node(Node::MESH);
  953. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "cube")) {
  954. nd = new Node(Node::CUBE);
  955. guessedMeshCnt += 1; // Cube is only one mesh
  956. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "skybox")) {
  957. nd = new Node(Node::SKYBOX);
  958. guessedMeshCnt += 6; // Skybox is a box, with 6 meshes?
  959. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "camera")) {
  960. nd = new Node(Node::CAMERA);
  961. // Setup a temporary name for the camera
  962. aiCamera *cam = new aiCamera();
  963. cam->mName.Set(nd->name);
  964. cameras.push_back(cam);
  965. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "light")) {
  966. nd = new Node(Node::LIGHT);
  967. // Setup a temporary name for the light
  968. aiLight *cam = new aiLight();
  969. cam->mName.Set(nd->name);
  970. lights.push_back(cam);
  971. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "sphere")) {
  972. nd = new Node(Node::SPHERE);
  973. guessedMeshCnt += 1;
  974. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "animatedMesh")) {
  975. nd = new Node(Node::ANIMMESH);
  976. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "empty")) {
  977. nd = new Node(Node::DUMMY);
  978. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "terrain")) {
  979. nd = new Node(Node::TERRAIN);
  980. } else if (!ASSIMP_stricmp(nodeTypeAttrib.value(), "billBoard")) {
  981. // We don't support billboards, so ignore them
  982. ASSIMP_LOG_ERROR("IRR: Billboards are not supported by Assimp");
  983. nd = new Node(Node::DUMMY);
  984. } else {
  985. ASSIMP_LOG_WARN("IRR: Found unknown node: ", nodeTypeAttrib.value());
  986. /* We skip the contents of nodes we don't know.
  987. * We parse the transformation and all animators
  988. * and skip the rest.
  989. */
  990. nd = new Node(Node::DUMMY);
  991. }
  992. // TODO: consolidate all into one loop
  993. for (pugi::xml_node subNode : node.children()) {
  994. // Collect node attributes first
  995. if (!ASSIMP_stricmp(subNode.name(), "attributes")) {
  996. ParseNodeAttributes(subNode, nd, batch); // Parse attributes into this node
  997. } else if (!ASSIMP_stricmp(subNode.name(), "animators")) {
  998. // Then parse any animators
  999. // All animators should contain an <attributes> tag
  1000. // This is an animation path - add a new animator
  1001. // to the list.
  1002. ParseAnimators(subNode, nd); // Function modifies nd's animator vector
  1003. guessedAnimCnt += 1;
  1004. }
  1005. // Then parse any materials
  1006. // Materials are available to almost all node types
  1007. if (nd->type != Node::DUMMY) {
  1008. if (!ASSIMP_stricmp(subNode.name(), "materials")) {
  1009. // Parse material description directly
  1010. // Each material should contain an <attributes> node
  1011. // with everything specified
  1012. nd->materials.emplace_back();
  1013. std::pair<aiMaterial *, unsigned int> &p = nd->materials.back();
  1014. p.first = ParseMaterial(subNode, p.second);
  1015. guessedMatCnt += 1;
  1016. }
  1017. }
  1018. }
  1019. // Then parse any child nodes
  1020. // Attach the newly created node to the scene-graph
  1021. for (pugi::xml_node child : node.children()) {
  1022. if (!ASSIMP_stricmp(child.name(), "node")) { // Is a child node
  1023. Node *childNd = ParseNode(child, batch); // Repeat this function for all children
  1024. nd->children.push_back(childNd);
  1025. };
  1026. }
  1027. // Return fully specified node
  1028. return nd;
  1029. }
  1030. // ------------------------------------------------------------------------------------------------
  1031. // Imports the given file into the given scene structure.
  1032. void IRRImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  1033. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile));
  1034. // Check whether we can read from the file
  1035. if (file == nullptr) {
  1036. throw DeadlyImportError("Failed to open IRR file ", pFile);
  1037. }
  1038. // Construct the irrXML parser
  1039. XmlParser st;
  1040. if (!st.parse(file.get())) {
  1041. throw DeadlyImportError("XML parse error while loading IRR file ", pFile);
  1042. }
  1043. pugi::xml_node documentRoot = st.getRootNode();
  1044. // The root node of the scene
  1045. Node *root = new Node(Node::DUMMY);
  1046. root->parent = nullptr;
  1047. root->name = "<IRRSceneRoot>";
  1048. // Batch loader used to load external models
  1049. BatchLoader batch(pIOHandler);
  1050. // batch.SetBasePath(pFile);
  1051. cameras.reserve(1); // Probably only one camera in entire scene
  1052. lights.reserve(5);
  1053. this->guessedAnimCnt = 0;
  1054. this->guessedMeshCnt = 0;
  1055. this->guessedMatCnt = 0;
  1056. // Parse the XML
  1057. // Find the scene root from document root.
  1058. const pugi::xml_node &sceneRoot = documentRoot.child("irr_scene");
  1059. if (!sceneRoot) {
  1060. delete root;
  1061. throw new DeadlyImportError("IRR: <irr_scene> not found in file");
  1062. }
  1063. for (pugi::xml_node &child : sceneRoot.children()) {
  1064. // XML elements are either nodes, animators, attributes, or materials
  1065. if (!ASSIMP_stricmp(child.name(), "node")) {
  1066. // Recursive collect subtree children
  1067. Node *nd = ParseNode(child, batch);
  1068. // Attach to root
  1069. root->children.push_back(nd);
  1070. }
  1071. }
  1072. // Now iterate through all cameras and compute their final (horizontal) FOV
  1073. for (aiCamera *cam : cameras) {
  1074. // screen aspect could be missing
  1075. if (cam->mAspect) {
  1076. cam->mHorizontalFOV *= cam->mAspect;
  1077. } else {
  1078. ASSIMP_LOG_WARN("IRR: Camera aspect is not given, can't compute horizontal FOV");
  1079. }
  1080. }
  1081. batch.LoadAll();
  1082. // Allocate a temporary scene data structure
  1083. aiScene *tempScene = new aiScene();
  1084. tempScene->mRootNode = new aiNode();
  1085. tempScene->mRootNode->mName.Set("<IRRRoot>");
  1086. // Copy the cameras to the output array
  1087. if (!cameras.empty()) {
  1088. tempScene->mNumCameras = (unsigned int)cameras.size();
  1089. tempScene->mCameras = new aiCamera *[tempScene->mNumCameras];
  1090. ::memcpy(tempScene->mCameras, &cameras[0], sizeof(void *) * tempScene->mNumCameras);
  1091. }
  1092. // Copy the light sources to the output array
  1093. if (!lights.empty()) {
  1094. tempScene->mNumLights = (unsigned int)lights.size();
  1095. tempScene->mLights = new aiLight *[tempScene->mNumLights];
  1096. ::memcpy(tempScene->mLights, &lights[0], sizeof(void *) * tempScene->mNumLights);
  1097. }
  1098. // temporary data
  1099. std::vector<aiNodeAnim *> anims;
  1100. std::vector<aiMaterial *> materials;
  1101. std::vector<AttachmentInfo> attach;
  1102. std::vector<aiMesh *> meshes;
  1103. // try to guess how much storage we'll need
  1104. anims.reserve(guessedAnimCnt + (guessedAnimCnt >> 2));
  1105. meshes.reserve(guessedMeshCnt + (guessedMeshCnt >> 2));
  1106. materials.reserve(guessedMatCnt + (guessedMatCnt >> 2));
  1107. // Now process our scene-graph recursively: generate final
  1108. // meshes and generate animation channels for all nodes.
  1109. unsigned int defMatIdx = UINT_MAX;
  1110. GenerateGraph(root, tempScene->mRootNode, tempScene,
  1111. batch, meshes, anims, attach, materials, defMatIdx);
  1112. if (!anims.empty()) {
  1113. tempScene->mNumAnimations = 1;
  1114. tempScene->mAnimations = new aiAnimation *[tempScene->mNumAnimations];
  1115. aiAnimation *an = tempScene->mAnimations[0] = new aiAnimation();
  1116. // ***********************************************************
  1117. // This is only the global animation channel of the scene.
  1118. // If there are animated models, they will have separate
  1119. // animation channels in the scene. To display IRR scenes
  1120. // correctly, users will need to combine the global anim
  1121. // channel with all the local animations they want to play
  1122. // ***********************************************************
  1123. an->mName.Set("Irr_GlobalAnimChannel");
  1124. // copy all node animation channels to the global channel
  1125. an->mNumChannels = (unsigned int)anims.size();
  1126. an->mChannels = new aiNodeAnim *[an->mNumChannels];
  1127. ::memcpy(an->mChannels, &anims[0], sizeof(void *) * an->mNumChannels);
  1128. }
  1129. if (!meshes.empty()) {
  1130. // copy all meshes to the temporary scene
  1131. tempScene->mNumMeshes = (unsigned int)meshes.size();
  1132. tempScene->mMeshes = new aiMesh *[tempScene->mNumMeshes];
  1133. ::memcpy(tempScene->mMeshes, &meshes[0], tempScene->mNumMeshes * sizeof(void *));
  1134. }
  1135. // Copy all materials to the output array
  1136. if (!materials.empty()) {
  1137. tempScene->mNumMaterials = (unsigned int)materials.size();
  1138. tempScene->mMaterials = new aiMaterial *[tempScene->mNumMaterials];
  1139. ::memcpy(tempScene->mMaterials, &materials[0], sizeof(void *) * tempScene->mNumMaterials);
  1140. }
  1141. // Now merge all sub scenes and attach them to the correct
  1142. // attachment points in the scenegraph.
  1143. SceneCombiner::MergeScenes(&pScene, tempScene, attach,
  1144. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES | (!configSpeedFlag ? (AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY | AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES) :
  1145. 0));
  1146. // If we have no meshes | no materials now set the INCOMPLETE
  1147. // scene flag. This is necessary if we failed to load all
  1148. // models from external files
  1149. if (!pScene->mNumMeshes || !pScene->mNumMaterials) {
  1150. ASSIMP_LOG_WARN("IRR: No meshes loaded, setting AI_SCENE_FLAGS_INCOMPLETE");
  1151. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  1152. }
  1153. // Finished ... everything destructs automatically and all
  1154. // temporary scenes have already been deleted by MergeScenes()
  1155. delete root;
  1156. }
  1157. #endif // !! ASSIMP_BUILD_NO_IRR_IMPORTER