IRRLoader.cpp 58 KB

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