IRRLoader.cpp 61 KB

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