IRRLoader.cpp 48 KB

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