IRRLoader.cpp 51 KB

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