IRRLoader.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the Irr importer class */
  35. #include "AssimpPCH.h"
  36. #include "IRRLoader.h"
  37. #include "ParsingUtils.h"
  38. #include "fast_atof.h"
  39. #include "GenericProperty.h"
  40. #include "SceneCombiner.h"
  41. #include "StandardShapes.h"
  42. using namespace Assimp;
  43. // ------------------------------------------------------------------------------------------------
  44. // Constructor to be privately used by Importer
  45. IRRImporter::IRRImporter()
  46. {
  47. // nothing to do here
  48. }
  49. // ------------------------------------------------------------------------------------------------
  50. // Destructor, private as well
  51. IRRImporter::~IRRImporter()
  52. {
  53. // nothing to do here
  54. }
  55. // ------------------------------------------------------------------------------------------------
  56. // Returns whether the class can handle the format of the given file.
  57. bool IRRImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  58. {
  59. /* NOTE: A simple check for the file extension is not enough
  60. * here. Irrmesh and irr are easy, but xml is too generic
  61. * and could be collada, too. So we need to open the file and
  62. * search for typical tokens.
  63. */
  64. std::string::size_type pos = pFile.find_last_of('.');
  65. // no file extension - can't read
  66. if( pos == std::string::npos)
  67. return false;
  68. std::string extension = pFile.substr( pos);
  69. for (std::string::iterator i = extension.begin(); i != extension.end();++i)
  70. *i = ::tolower(*i);
  71. if (extension == ".irr")return true;
  72. else if (extension == ".xml")
  73. {
  74. /* If CanRead() is called to check whether the loader
  75. * supports a specific file extension in general we
  76. * must return true here.
  77. */
  78. if (!pIOHandler)return true;
  79. const char* tokens[] = {"irr_scene"};
  80. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  81. }
  82. return false;
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. // Imports the given file into the given scene structure.
  86. void IRRImporter::InternReadFile( const std::string& pFile,
  87. aiScene* pScene, IOSystem* pIOHandler)
  88. {
  89. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  90. // Check whether we can read from the file
  91. if( file.get() == NULL)
  92. throw new ImportErrorException( "Failed to open IRR file " + pFile + "");
  93. // Construct the irrXML parser
  94. CIrrXML_IOStreamReader st(file.get());
  95. reader = createIrrXMLReader((IFileReadCallBack*) &st);
  96. // The root node of the scene
  97. Node* root = new Node(Node::DUMMY);
  98. root->parent = NULL;
  99. // Current node parent
  100. Node* curParent = root;
  101. // Scenegraph node we're currently working on
  102. Node* curNode = NULL;
  103. // List of output cameras
  104. std::vector<aiCamera*> cameras;
  105. // List of output lights
  106. std::vector<aiLight*> lights;
  107. BatchLoader batch(pIOHandler);
  108. cameras.reserve(5);
  109. lights.reserve(5);
  110. bool inMaterials = false, inAnimator = false;
  111. unsigned int guessedAnimCnt = 0, guessedMeshCnt = 0;
  112. // Parse the XML file
  113. while (reader->read())
  114. {
  115. switch (reader->getNodeType())
  116. {
  117. case EXN_ELEMENT:
  118. if (!ASSIMP_stricmp(reader->getNodeName(),"node"))
  119. {
  120. /* What we're going to do with the node depends
  121. * on its type:
  122. *
  123. * "mesh" - Load a mesh from an external file
  124. * "cube" - Generate a cube
  125. * "skybox" - Generate a skybox
  126. * "light" - A light source
  127. * "sphere" - Generate a sphere mesh
  128. * "animatedMesh" - Load an animated mesh from an external file
  129. * and join its animation channels with ours.
  130. * "empty" - A dummy node
  131. * "camera" - A camera
  132. *
  133. * Each of these nodes can be animated.
  134. */
  135. const char* sz = reader->getAttributeValueSafe("type");
  136. Node* nd;
  137. if (!ASSIMP_stricmp(sz,"mesh"))
  138. {
  139. nd = new Node(Node::MESH);
  140. }
  141. else if (!ASSIMP_stricmp(sz,"cube"))
  142. {
  143. nd = new Node(Node::CUBE);
  144. ++guessedMeshCnt;
  145. // meshes.push_back(StandardShapes::MakeMesh(&StandardShapes::MakeHexahedron));
  146. }
  147. else if (!ASSIMP_stricmp(sz,"skybox"))
  148. {
  149. nd = new Node(Node::SKYBOX);
  150. ++guessedMeshCnt;
  151. }
  152. else if (!ASSIMP_stricmp(sz,"camera"))
  153. {
  154. nd = new Node(Node::CAMERA);
  155. // Setup a temporary name for the camera
  156. aiCamera* cam = new aiCamera();
  157. cam->mName.Set( nd->name );
  158. cameras.push_back(cam);
  159. }
  160. else if (!ASSIMP_stricmp(sz,"light"))
  161. {
  162. nd = new Node(Node::LIGHT);
  163. // Setup a temporary name for the light
  164. aiLight* cam = new aiLight();
  165. cam->mName.Set( nd->name );
  166. lights.push_back(cam);
  167. }
  168. else if (!ASSIMP_stricmp(sz,"sphere"))
  169. {
  170. nd = new Node(Node::SPHERE);
  171. ++guessedMeshCnt;
  172. }
  173. else if (!ASSIMP_stricmp(sz,"animatedMesh"))
  174. {
  175. nd = new Node(Node::ANIMMESH);
  176. }
  177. else if (!ASSIMP_stricmp(sz,"empty"))
  178. {
  179. nd = new Node(Node::DUMMY);
  180. }
  181. else
  182. {
  183. DefaultLogger::get()->warn("IRR: Found unknown node: " + std::string(sz));
  184. /* We skip the contents of nodes we don't know.
  185. * We parse the transformation and all animators
  186. * and skip the rest.
  187. */
  188. nd = new Node(Node::DUMMY);
  189. }
  190. /* Attach the newly created node to the scenegraph
  191. */
  192. curNode = nd;
  193. nd->parent = curParent;
  194. curParent->children.push_back(nd);
  195. }
  196. else if (!ASSIMP_stricmp(reader->getNodeName(),"materials"))
  197. {
  198. inMaterials = true;
  199. }
  200. else if (!ASSIMP_stricmp(reader->getNodeName(),"animators"))
  201. {
  202. inAnimator = true;
  203. }
  204. else if (!ASSIMP_stricmp(reader->getNodeName(),"attributes"))
  205. {
  206. /* We should have a valid node here
  207. */
  208. if (!curNode)
  209. {
  210. DefaultLogger::get()->error("IRR: Encountered <attributes> element, but "
  211. "there is no node active");
  212. continue;
  213. }
  214. Animator* curAnim = NULL;
  215. if (inMaterials && curNode->type == Node::ANIMMESH ||
  216. curNode->type == Node::MESH )
  217. {
  218. /* This is a material description - parse it!
  219. */
  220. curNode->materials.push_back(std::pair< aiMaterial*, unsigned int > () );
  221. std::pair< aiMaterial*, unsigned int >& p = curNode->materials.back();
  222. p.first = ParseMaterial(p.second);
  223. continue;
  224. }
  225. else if (inAnimator)
  226. {
  227. /* This is an animation path - add a new animator
  228. * to the list.
  229. */
  230. curNode->animators.push_back(Animator());
  231. curAnim = & curNode->animators.back();
  232. ++guessedAnimCnt;
  233. }
  234. /* Parse all elements in the attributes block
  235. * and process them.
  236. */
  237. while (reader->read())
  238. {
  239. if (reader->getNodeType() == EXN_ELEMENT)
  240. {
  241. if (!ASSIMP_stricmp(reader->getNodeName(),"vector3d"))
  242. {
  243. VectorProperty prop;
  244. ReadVectorProperty(prop);
  245. // Convert to our coordinate system
  246. std::swap( (float&)prop.value.z, (float&)prop.value.y );
  247. prop.value.y *= -1.f;
  248. if (inAnimator)
  249. {
  250. if (curAnim->type == Animator::ROTATION && prop.name == "Rotation")
  251. {
  252. // We store the rotation euler angles in 'direction'
  253. curAnim->direction = prop.value;
  254. }
  255. else if (curAnim->type == Animator::FOLLOW_SPLINE)
  256. {
  257. // Check whether the vector follows the PointN naming scheme,
  258. // here N is the ONE-based index of the point
  259. if (prop.name.length() >= 6 && prop.name.substr(0,5) == "Point")
  260. {
  261. // Add a new key to the list
  262. curAnim->splineKeys.push_back(aiVectorKey());
  263. aiVectorKey& key = curAnim->splineKeys.back();
  264. // and parse its properties
  265. key.mValue = prop.value;
  266. key.mTime = strtol10(&prop.name.c_str()[5]);
  267. }
  268. }
  269. else if (curAnim->type == Animator::FLY_CIRCLE)
  270. {
  271. if (prop.name == "Center")
  272. {
  273. curAnim->circleCenter = prop.value;
  274. }
  275. else if (prop.name == "Direction")
  276. {
  277. curAnim->direction = prop.value;
  278. }
  279. }
  280. else if (curAnim->type == Animator::FLY_STRAIGHT)
  281. {
  282. if (prop.name == "Start")
  283. {
  284. // We reuse the field here
  285. curAnim->circleCenter = prop.value;
  286. }
  287. else if (prop.name == "End")
  288. {
  289. // We reuse the field here
  290. curAnim->direction = prop.value;
  291. }
  292. }
  293. }
  294. else
  295. {
  296. if (prop.name == "Position")
  297. {
  298. curNode->position = prop.value;
  299. }
  300. else if (prop.name == "Rotation")
  301. {
  302. curNode->rotation = prop.value;
  303. }
  304. else if (prop.name == "Scale")
  305. {
  306. curNode->scaling = prop.value;
  307. }
  308. else if (Node::CAMERA == curNode->type)
  309. {
  310. aiCamera* cam = cameras.back();
  311. if (prop.name == "Target")
  312. {
  313. cam->mLookAt = prop.value;
  314. }
  315. else if (prop.name == "UpVector")
  316. {
  317. cam->mUp = prop.value;
  318. }
  319. }
  320. }
  321. }
  322. else if (!ASSIMP_stricmp(reader->getNodeName(),"bool"))
  323. {
  324. BoolProperty prop;
  325. ReadBoolProperty(prop);
  326. if (inAnimator && curAnim->type == Animator::FLY_CIRCLE && prop.name == "Loop")
  327. {
  328. curAnim->loop = prop.value;
  329. }
  330. }
  331. else if (!ASSIMP_stricmp(reader->getNodeName(),"float"))
  332. {
  333. FloatProperty prop;
  334. ReadFloatProperty(prop);
  335. if (inAnimator)
  336. {
  337. // The speed property exists for several animators
  338. if (prop.name == "Speed")
  339. {
  340. curAnim->speed = prop.value;
  341. }
  342. else if (curAnim->type == Animator::FLY_CIRCLE && prop.name == "Radius")
  343. {
  344. curAnim->circleRadius = prop.value;
  345. }
  346. }
  347. else
  348. {
  349. if (prop.name == "FramesPerSecond" &&
  350. Node::ANIMMESH == curNode->type)
  351. {
  352. curNode->framesPerSecond = prop.value;
  353. }
  354. else if (Node::CAMERA == curNode->type)
  355. {
  356. /* This is the vertical, not the horizontal FOV.
  357. * We need to compute the right FOV from the
  358. * screen aspect which we don't know yet.
  359. */
  360. if (prop.name == "Fovy")
  361. {
  362. cameras.back()->mHorizontalFOV = prop.value;
  363. }
  364. else if (prop.name == "Aspect")
  365. {
  366. cameras.back()->mAspect = prop.value;
  367. }
  368. else if (prop.name == "ZNear")
  369. {
  370. cameras.back()->mClipPlaneNear = prop.value;
  371. }
  372. else if (prop.name == "ZFar")
  373. {
  374. cameras.back()->mClipPlaneFar = prop.value;
  375. }
  376. }
  377. else if (Node::LIGHT == curNode->type)
  378. {
  379. /* Additional light information
  380. */
  381. if (prop.name == "Attenuation")
  382. {
  383. lights.back()->mAttenuationLinear = prop.value;
  384. }
  385. else if (prop.name == "OuterCone")
  386. {
  387. lights.back()->mAngleOuterCone = AI_DEG_TO_RAD( prop.value );
  388. }
  389. else if (prop.name == "InnerCone")
  390. {
  391. lights.back()->mAngleInnerCone = AI_DEG_TO_RAD( prop.value );
  392. }
  393. }
  394. // radius of the sphere to be generated
  395. else if (Node::SPHERE == curNode->type)
  396. {
  397. if (prop.name == "Radius")
  398. {
  399. curNode->sphereRadius = prop.value;
  400. }
  401. }
  402. }
  403. }
  404. else if (!ASSIMP_stricmp(reader->getNodeName(),"int"))
  405. {
  406. IntProperty prop;
  407. ReadIntProperty(prop);
  408. if (inAnimator)
  409. {
  410. if (curAnim->type == Animator::FLY_STRAIGHT && prop.name == "TimeForWay")
  411. {
  412. curAnim->timeForWay = prop.value;
  413. }
  414. }
  415. else
  416. {
  417. // sphere polgon numbers in each direction
  418. if (Node::SPHERE == curNode->type)
  419. {
  420. if (prop.name == "PolyCountX")
  421. {
  422. curNode->spherePolyCountX = prop.value;
  423. }
  424. else if (prop.name == "PolyCountY")
  425. {
  426. curNode->spherePolyCountY = prop.value;
  427. }
  428. }
  429. }
  430. }
  431. else if (!ASSIMP_stricmp(reader->getNodeName(),"string") ||
  432. !ASSIMP_stricmp(reader->getNodeName(),"enum"))
  433. {
  434. StringProperty prop;
  435. ReadStringProperty(prop);
  436. if (prop.value.length())
  437. {
  438. if (prop.name == "Name")
  439. {
  440. curNode->name = prop.value;
  441. /* If we're either a camera or a light source
  442. * we need to update the name in the aiLight/
  443. * aiCamera structure, too.
  444. */
  445. if (Node::CAMERA == curNode->type)
  446. {
  447. cameras.back()->mName.Set(prop.value);
  448. }
  449. else if (Node::LIGHT == curNode->type)
  450. {
  451. lights.back()->mName.Set(prop.value);
  452. }
  453. }
  454. else if (Node::LIGHT == curNode->type && "LightType" == prop.name)
  455. {
  456. }
  457. else if (prop.name == "Mesh" && Node::MESH == curNode->type ||
  458. Node::ANIMMESH == curNode->type)
  459. {
  460. /* This is the file name of the mesh - either
  461. * animated or not. We need to make sure we setup
  462. * the correct postprocessing settings here.
  463. */
  464. unsigned int pp = 0;
  465. BatchLoader::PropertyMap map;
  466. /* If the mesh is a static one remove all animations
  467. */
  468. if (Node::ANIMMESH != curNode->type)
  469. {
  470. pp |= aiProcess_RemoveComponent;
  471. SetGenericProperty<int>(map.ints,AI_CONFIG_PP_RVC_FLAGS,
  472. aiComponent_ANIMATIONS | aiComponent_BONEWEIGHTS);
  473. }
  474. batch.AddLoadRequest(prop.value,pp,&map);
  475. }
  476. }
  477. }
  478. }
  479. else if (reader->getNodeType() == EXN_ELEMENT_END &&
  480. !ASSIMP_stricmp(reader->getNodeName(),"attributes"))
  481. {
  482. break;
  483. }
  484. }
  485. }
  486. break;
  487. case EXN_ELEMENT_END:
  488. // If we reached the end of a node, we need to continue processing its parent
  489. if (!ASSIMP_stricmp(reader->getNodeName(),"node"))
  490. {
  491. if (!curNode)
  492. {
  493. // currently is no node set. We need to go
  494. // back in the node hierarchy
  495. curParent = curParent->parent;
  496. if (!curParent)
  497. {
  498. curParent = root;
  499. DefaultLogger::get()->error("IRR: Too many closing <node> elements");
  500. }
  501. }
  502. else curNode = NULL;
  503. }
  504. // clear all flags
  505. else if (!ASSIMP_stricmp(reader->getNodeName(),"materials"))
  506. {
  507. inMaterials = false;
  508. }
  509. else if (!ASSIMP_stricmp(reader->getNodeName(),"animators"))
  510. {
  511. inAnimator = false;
  512. }
  513. break;
  514. default:
  515. // GCC complains that not all enumeration values are handled
  516. break;
  517. }
  518. }
  519. /* Now iterate through all cameras and compute their final (horizontal) FOV
  520. */
  521. for (std::vector<aiCamera*>::iterator it = cameras.begin(), end = cameras.end();
  522. it != end; ++it)
  523. {
  524. aiCamera* cam = *it;
  525. if (cam->mAspect) // screen aspect could be missing
  526. {
  527. cam->mHorizontalFOV *= cam->mAspect;
  528. }
  529. else DefaultLogger::get()->warn("IRR: Camera aspect is not given, can't compute horizontal FOV");
  530. }
  531. /* Allocate a tempoary scene data structure
  532. */
  533. aiScene* tempScene = new aiScene();
  534. tempScene->mRootNode = new aiNode();
  535. tempScene->mRootNode->mName.Set("<IRRRoot>");
  536. /* Copy the cameras to the output array
  537. */
  538. tempScene->mNumCameras = (unsigned int)cameras.size();
  539. tempScene->mCameras = new aiCamera*[tempScene->mNumCameras];
  540. ::memcpy(tempScene->mCameras,&cameras[0],sizeof(void*)*tempScene->mNumCameras);
  541. /* Copy the light sources to the output array
  542. */
  543. tempScene->mNumLights = (unsigned int)lights.size();
  544. tempScene->mLights = new aiLight*[tempScene->mNumLights];
  545. ::memcpy(tempScene->mLights,&lights[0],sizeof(void*)*tempScene->mNumLights);
  546. // temporary data
  547. std::vector< aiNodeAnim*> anims;
  548. std::vector< AttachmentInfo > attach;
  549. std::vector<aiMesh*> meshes;
  550. anims.reserve(guessedAnimCnt + (guessedAnimCnt >> 2));
  551. meshes.reserve(guessedMeshCnt + (guessedMeshCnt >> 2));
  552. /* Now process our scenegraph recursively: generate final
  553. * meshes and generate animation channels for all nodes.
  554. */
  555. // GenerateGraph(root,tempScene->mRootNode, tempScene,
  556. // batch, meshes, anims, attach);
  557. if (!anims.empty())
  558. {
  559. tempScene->mNumAnimations = 1;
  560. tempScene->mAnimations = new aiAnimation*[tempScene->mNumAnimations];
  561. aiAnimation* an = tempScene->mAnimations[0] = new aiAnimation();
  562. // ***********************************************************
  563. // This is only the global animation channel of the scene.
  564. // If there are animated models, they will have separate
  565. // animation channels in the scene. To display IRR scenes
  566. // correctly, users will need to combine the global anim
  567. // channel with all the local animations they want to play
  568. // ***********************************************************
  569. an->mName.Set("Irr_GlobalAnimChannel");
  570. // copy all node animation channels to the global channel
  571. an->mNumChannels = (unsigned int)anims.size();
  572. an->mChannels = new aiNodeAnim*[an->mNumChannels];
  573. ::memcpy(an->mChannels, & anims [0], sizeof(void*)*an->mNumChannels);
  574. }
  575. if (meshes.empty())
  576. {
  577. // There are no meshes in the scene - the scene is incomplete
  578. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  579. DefaultLogger::get()->info("IRR: No Meshes loaded, setting AI_SCENE_FLAGS_INCOMPLETE flag");
  580. }
  581. /* Now merge all sub scenes and attach them to the correct
  582. * attachment points in the scenegraph.
  583. */
  584. SceneCombiner::MergeScenes(pScene,tempScene,attach);
  585. }