IRRLoader.cpp 48 KB

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