IRRLoader.cpp 61 KB

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