IRRLoader.cpp 61 KB

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