IRRLoader.cpp 48 KB

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