IRRLoader.cpp 55 KB

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