OgreImporter.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file OgreImporter.cpp
  34. * @brief Implementation of the Ogre XML (.mesh.xml) loader.
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  38. #include <vector>
  39. #include <sstream>
  40. using namespace std;
  41. //#include "boost/format.hpp"
  42. //#include "boost/foreach.hpp"
  43. //using namespace boost;
  44. #include "TinyFormatter.h"
  45. #include "OgreImporter.hpp"
  46. #include "irrXMLWrapper.h"
  47. namespace Assimp
  48. {
  49. namespace Ogre
  50. {
  51. bool OgreImporter::CanRead(const std::string &pFile, Assimp::IOSystem *pIOHandler, bool checkSig) const
  52. {
  53. if(!checkSig)//Check File Extension
  54. {
  55. std::string extension("mesh.xml");
  56. int l=extension.length();
  57. return pFile.substr(pFile.length()-l, l)==extension;
  58. }
  59. else//Check file Header
  60. {
  61. const char* tokens[] = {"<mesh>"};
  62. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
  63. }
  64. }
  65. void OgreImporter::InternReadFile(const std::string &pFile, aiScene *pScene, Assimp::IOSystem *pIOHandler)
  66. {
  67. m_CurrentFilename=pFile;
  68. m_CurrentIOHandler=pIOHandler;
  69. m_CurrentScene=pScene;
  70. //Open the File:
  71. boost::scoped_ptr<IOStream> file(pIOHandler->Open(pFile));
  72. if( file.get() == NULL)
  73. throw DeadlyImportError("Failed to open file "+pFile+".");
  74. //Read the Mesh File:
  75. boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper( new CIrrXML_IOStreamReader( file.get()));
  76. XmlReader* MeshFile = irr::io::createIrrXMLReader(mIOWrapper.get());
  77. if(!MeshFile)//parse the xml file
  78. throw DeadlyImportError("Failed to create XML Reader for "+pFile);
  79. DefaultLogger::get()->debug("Mesh File opened");
  80. //Read root Node:
  81. if(!(XmlRead(MeshFile) && string(MeshFile->getNodeName())=="mesh"))
  82. {
  83. throw DeadlyImportError("Root Node is not <mesh>! "+pFile+" "+MeshFile->getNodeName());
  84. }
  85. //Go to the submeshs:
  86. if(!(XmlRead(MeshFile) && string(MeshFile->getNodeName())=="submeshes"))
  87. {
  88. throw DeadlyImportError("No <submeshes> node in <mesh> node! "+pFile);
  89. }
  90. //-------------------Read the submeshs and materials:-----------------------
  91. std::list<boost::shared_ptr<SubMesh> > SubMeshes;
  92. vector<aiMaterial*> Materials;
  93. XmlRead(MeshFile);
  94. while(MeshFile->getNodeName()==string("submesh"))
  95. {
  96. SubMesh* theSubMesh=new SubMesh();
  97. theSubMesh->MaterialName=GetAttribute<string>(MeshFile, "material");
  98. DefaultLogger::get()->debug("Loading Submehs with Material: "+theSubMesh->MaterialName);
  99. ReadSubMesh(*theSubMesh, MeshFile);
  100. //just a index in a array, we add a mesh in each loop cycle, so we get indicies like 0, 1, 2 ... n;
  101. //so it is important to do this before pushing the mesh in the vector!
  102. theSubMesh->MaterialIndex=SubMeshes.size();
  103. SubMeshes.push_back(boost::shared_ptr<SubMesh>(theSubMesh));
  104. //Load the Material:
  105. aiMaterial* MeshMat=LoadMaterial(theSubMesh->MaterialName);
  106. //Set the Material:
  107. Materials.push_back(MeshMat);
  108. }
  109. if(SubMeshes.empty())
  110. throw DeadlyImportError("no submesh loaded!");
  111. if(SubMeshes.size()!=Materials.size())
  112. throw DeadlyImportError("materialcount doesn't match mesh count!");
  113. //____________________________________________________________
  114. //----------------Load the skeleton: -------------------------------
  115. vector<Bone> Bones;
  116. vector<Animation> Animations;
  117. if(MeshFile->getNodeName()==string("skeletonlink"))
  118. {
  119. string SkeletonFile=GetAttribute<string>(MeshFile, "name");
  120. LoadSkeleton(SkeletonFile, Bones, Animations);
  121. }
  122. else
  123. {
  124. DefaultLogger::get()->warn("No skeleton file will be loaded");
  125. DefaultLogger::get()->warn(MeshFile->getNodeName());
  126. }
  127. //__________________________________________________________________
  128. //----------------- Now fill the Assimp scene ---------------------------
  129. //put the aiMaterials in the scene:
  130. m_CurrentScene->mMaterials=new aiMaterial*[Materials.size()];
  131. m_CurrentScene->mNumMaterials=Materials.size();
  132. for(unsigned int i=0; i<Materials.size(); ++i)
  133. m_CurrentScene->mMaterials[i]=Materials[i];
  134. //create the aiMehs...
  135. vector<aiMesh*> aiMeshes;
  136. BOOST_FOREACH(boost::shared_ptr<SubMesh> theSubMesh, SubMeshes)
  137. {
  138. aiMeshes.push_back(CreateAssimpSubMesh(*theSubMesh, Bones));
  139. }
  140. //... and put them in the scene:
  141. m_CurrentScene->mNumMeshes=aiMeshes.size();
  142. m_CurrentScene->mMeshes=new aiMesh*[aiMeshes.size()];
  143. memcpy(m_CurrentScene->mMeshes, &(aiMeshes[0]), sizeof(aiMeshes[0])*aiMeshes.size());
  144. //Create the root node
  145. m_CurrentScene->mRootNode=new aiNode("root");
  146. //link the meshs with the root node:
  147. m_CurrentScene->mRootNode->mMeshes=new unsigned int[SubMeshes.size()];
  148. m_CurrentScene->mRootNode->mNumMeshes=SubMeshes.size();
  149. for(unsigned int i=0; i<SubMeshes.size(); ++i)
  150. m_CurrentScene->mRootNode->mMeshes[i]=i;
  151. CreateAssimpSkeleton(Bones, Animations);
  152. PutAnimationsInScene(Bones, Animations);
  153. //___________________________________________________________
  154. }
  155. void OgreImporter::GetExtensionList(std::set<std::string>& extensions)
  156. {
  157. extensions.insert("mesh.xml");
  158. }
  159. void OgreImporter::SetupProperties(const Importer* pImp)
  160. {
  161. m_MaterialLibFilename=pImp->GetPropertyString(AI_CONFIG_IMPORT_OGRE_MATERIAL_FILE, "Scene.material");
  162. }
  163. void OgreImporter::ReadSubMesh(SubMesh &theSubMesh, XmlReader *Reader)
  164. {
  165. XmlRead(Reader);
  166. //TODO: maybe we have alsways just 1 faces and 1 geometry and always in this order. this loop will only work correct, when the order
  167. //of faces and geometry changed, and not if we have more than one of one
  168. while(Reader->getNodeName()==string("faces") || string(Reader->getNodeName())=="geometry" || Reader->getNodeName()==string("boneassignments"))
  169. {
  170. if(string(Reader->getNodeName())=="faces")//Read the face list
  171. {
  172. //some info logging:
  173. unsigned int NumFaces=GetAttribute<int>(Reader, "count");
  174. ostringstream ss; ss <<"Submesh has " << NumFaces << " Faces.";
  175. DefaultLogger::get()->debug(ss.str());
  176. while(XmlRead(Reader) && Reader->getNodeName()==string("face"))
  177. {
  178. Face NewFace;
  179. NewFace.VertexIndices[0]=GetAttribute<int>(Reader, "v1");
  180. NewFace.VertexIndices[1]=GetAttribute<int>(Reader, "v2");
  181. NewFace.VertexIndices[2]=GetAttribute<int>(Reader, "v3");
  182. if(Reader->getAttributeValue("v4"))//this should be supported in the future
  183. {
  184. throw DeadlyImportError("Submesh has quads, only traingles are supported!");
  185. }
  186. theSubMesh.FaceList.push_back(NewFace);
  187. }
  188. }//end of faces
  189. else if(string(Reader->getNodeName())=="geometry")//Read the vertexdata
  190. {
  191. //some info logging:
  192. unsigned int NumVertices=GetAttribute<int>(Reader, "vertexcount");
  193. ostringstream ss; ss<<"VertexCount: " << NumVertices;
  194. DefaultLogger::get()->debug(ss.str());
  195. //General Informations about vertices
  196. XmlRead(Reader);
  197. while(Reader->getNodeName()==string("vertexbuffer"))
  198. {
  199. ReadVertexBuffer(theSubMesh, Reader, NumVertices);
  200. }
  201. //some error checking on the loaded data
  202. if(!theSubMesh.HasPositions)
  203. throw DeadlyImportError("No positions could be loaded!");
  204. if(theSubMesh.HasNormals && theSubMesh.Normals.size() != NumVertices)
  205. throw DeadlyImportError("Wrong Number of Normals loaded!");
  206. if(theSubMesh.HasTangents && theSubMesh.Tangents.size() != NumVertices)
  207. throw DeadlyImportError("Wrong Number of Tangents loaded!");
  208. if(theSubMesh.NumUvs==1 && theSubMesh.Uvs.size() != NumVertices)
  209. throw DeadlyImportError("Wrong Number of Uvs loaded!");
  210. }//end of "geometry
  211. else if(string(Reader->getNodeName())=="boneassignments")
  212. {
  213. theSubMesh.Weights.resize(theSubMesh.Positions.size());
  214. while(XmlRead(Reader) && Reader->getNodeName()==string("vertexboneassignment"))
  215. {
  216. Weight NewWeight;
  217. unsigned int VertexId=GetAttribute<int>(Reader, "vertexindex");
  218. NewWeight.BoneId=GetAttribute<int>(Reader, "boneindex");
  219. NewWeight.Value=GetAttribute<float>(Reader, "weight");
  220. theSubMesh.BonesUsed=max(theSubMesh.BonesUsed, NewWeight.BoneId+1);//calculate the number of bones used (this is the highest id +1 becuase bone ids start at 0)
  221. theSubMesh.Weights[VertexId].push_back(NewWeight);
  222. //XmlRead(Reader);//Once i had this line, and than i got only every second boneassignment, but my first test models had even boneassignment counts, so i thougt, everything would work. And yes, i HATE irrXML!!!
  223. }
  224. }//end of boneassignments
  225. }
  226. DefaultLogger::get()->debug((Formatter::format(),
  227. "Positionen: ",theSubMesh.Positions.size(),
  228. " Normale: ",theSubMesh.Normals.size(),
  229. " TexCoords: ",theSubMesh.Uvs.size(),
  230. " Tantents: ",theSubMesh.Tangents.size()
  231. ));
  232. DefaultLogger::get()->warn(Reader->getNodeName());
  233. //---------------Make all Vertexes unique: (this is required by assimp)-----------------------
  234. vector<Face> UniqueFaceList(theSubMesh.FaceList.size());
  235. unsigned int UniqueVertexCount=theSubMesh.FaceList.size()*3;//*3 because each face consists of 3 vertexes, because we only support triangles^^
  236. vector<aiVector3D> UniquePositions(UniqueVertexCount);
  237. vector<aiVector3D> UniqueNormals(UniqueVertexCount);
  238. vector<aiVector3D> UniqueTangents(UniqueVertexCount);
  239. vector<aiVector3D> UniqueUvs(UniqueVertexCount);
  240. vector< vector<Weight> > UniqueWeights((theSubMesh.Weights.size() ? UniqueVertexCount : 0));
  241. for(unsigned int i=0; i<theSubMesh.FaceList.size(); ++i)
  242. {
  243. //We precalculate the index vlaues her, because we need them in all vertex attributes
  244. unsigned int Vertex1=theSubMesh.FaceList[i].VertexIndices[0];
  245. unsigned int Vertex2=theSubMesh.FaceList[i].VertexIndices[1];
  246. unsigned int Vertex3=theSubMesh.FaceList[i].VertexIndices[2];
  247. UniquePositions[3*i+0]=theSubMesh.Positions[Vertex1];
  248. UniquePositions[3*i+1]=theSubMesh.Positions[Vertex2];
  249. UniquePositions[3*i+2]=theSubMesh.Positions[Vertex3];
  250. if(theSubMesh.HasNormals)
  251. {
  252. UniqueNormals[3*i+0]=theSubMesh.Normals[Vertex1];
  253. UniqueNormals[3*i+1]=theSubMesh.Normals[Vertex2];
  254. UniqueNormals[3*i+2]=theSubMesh.Normals[Vertex3];
  255. }
  256. if(theSubMesh.HasTangents)
  257. {
  258. UniqueTangents[3*i+0]=theSubMesh.Tangents[Vertex1];
  259. UniqueTangents[3*i+1]=theSubMesh.Tangents[Vertex2];
  260. UniqueTangents[3*i+2]=theSubMesh.Tangents[Vertex3];
  261. }
  262. if(1==theSubMesh.NumUvs)
  263. {
  264. UniqueUvs[3*i+0]=theSubMesh.Uvs[Vertex1];
  265. UniqueUvs[3*i+1]=theSubMesh.Uvs[Vertex2];
  266. UniqueUvs[3*i+2]=theSubMesh.Uvs[Vertex3];
  267. }
  268. if(theSubMesh.Weights.size())
  269. {
  270. UniqueWeights[3*i+0]=theSubMesh.Weights[Vertex1];
  271. UniqueWeights[3*i+1]=theSubMesh.Weights[Vertex2];
  272. UniqueWeights[3*i+2]=theSubMesh.Weights[Vertex3];
  273. }
  274. //The indexvalues a just continuous numbers (0, 1, 2, 3, 4, 5, 6...)
  275. UniqueFaceList[i].VertexIndices[0]=3*i+0;
  276. UniqueFaceList[i].VertexIndices[1]=3*i+1;
  277. UniqueFaceList[i].VertexIndices[2]=3*i+2;
  278. }
  279. //_________________________________________________________________________________________
  280. //now we have the unique datas, but want them in the SubMesh, so we swap all the containers:
  281. //if we don't have one of them, we just swap empty containers, so everything is ok
  282. theSubMesh.FaceList.swap(UniqueFaceList);
  283. theSubMesh.Positions.swap(UniquePositions);
  284. theSubMesh.Normals.swap(UniqueNormals);
  285. theSubMesh.Tangents.swap(UniqueTangents);
  286. theSubMesh.Uvs.swap(UniqueUvs);
  287. theSubMesh.Weights.swap(UniqueWeights);
  288. //------------- normalize weights -----------------------------
  289. //The Blender exporter doesn't care about whether the sum of all boneweights for a single vertex equals 1 or not,
  290. //so we have to make this sure:
  291. for(unsigned int VertexId=0; VertexId<theSubMesh.Weights.size(); ++VertexId)//iterate over all vertices
  292. {
  293. float WeightSum=0.0f;
  294. for(unsigned int BoneId=0; BoneId<theSubMesh.Weights[VertexId].size(); ++BoneId)//iterate over all bones
  295. {
  296. WeightSum+=theSubMesh.Weights[VertexId][BoneId].Value;
  297. }
  298. //check if the sum is too far away from 1
  299. if(WeightSum<1.0f-0.05f || WeightSum>1.0f+0.05f)
  300. {
  301. //normalize all weights:
  302. for(unsigned int BoneId=0; BoneId<theSubMesh.Weights[VertexId].size(); ++BoneId)//iterate over all bones
  303. {
  304. theSubMesh.Weights[VertexId][BoneId].Value/=WeightSum;
  305. }
  306. }
  307. }
  308. //_________________________________________________________
  309. }
  310. void OgreImporter::ReadVertexBuffer(SubMesh &theSubMesh, XmlReader *Reader, unsigned int NumVertices)
  311. {
  312. DefaultLogger::get()->debug("new Vertex Buffer");
  313. bool ReadPositions=false;
  314. bool ReadNormals=false;
  315. bool ReadTangents=false;
  316. bool ReadUvs=false;
  317. //-------------------- check, what we need to read: --------------------------------
  318. if(Reader->getAttributeValue("positions") && GetAttribute<bool>(Reader, "positions"))
  319. {
  320. ReadPositions=theSubMesh.HasPositions=true;
  321. theSubMesh.Positions.reserve(NumVertices);
  322. DefaultLogger::get()->debug("reading positions");
  323. }
  324. if(Reader->getAttributeValue("normals") && GetAttribute<bool>(Reader, "normals"))
  325. {
  326. ReadNormals=theSubMesh.HasNormals=true;
  327. theSubMesh.Normals.reserve(NumVertices);
  328. DefaultLogger::get()->debug("reading positions");
  329. }
  330. if(Reader->getAttributeValue("tangents") && GetAttribute<bool>(Reader, "tangents"))
  331. {
  332. ReadTangents=theSubMesh.HasTangents=true;
  333. theSubMesh.Tangents.reserve(NumVertices);
  334. DefaultLogger::get()->debug("reading positions");
  335. }
  336. //we can have 1 or 0 uv channels, and if the mesh has no uvs, it also doesn't have the attribute
  337. if(!Reader->getAttributeValue("texture_coords"))
  338. theSubMesh.NumUvs=0;
  339. else
  340. {
  341. ReadUvs=!!(theSubMesh.NumUvs=GetAttribute<int>(Reader, "texture_coords"));
  342. theSubMesh.Uvs.reserve(NumVertices);
  343. DefaultLogger::get()->debug("reading texture coords");
  344. }
  345. if(theSubMesh.NumUvs>1)
  346. {
  347. DefaultLogger::get()->warn("too many texcoords (just 1 supported!), just the first texcoords will be loaded!");
  348. theSubMesh.NumUvs=1;
  349. }
  350. //___________________________________________________________________
  351. //check if we will load anything
  352. if(!(ReadPositions || ReadNormals || ReadTangents || ReadUvs))
  353. DefaultLogger::get()->warn("vertexbuffer seams to be empty!");
  354. //read all the vertices:
  355. XmlRead(Reader);
  356. /*it might happen, that we have more than one attribute per vertex (they are not splitted to different buffers)
  357. so the break condition is a bit tricky (well, IrrXML just sucks :( )*/
  358. while(Reader->getNodeName()==string("vertex")
  359. ||Reader->getNodeName()==string("position")
  360. ||Reader->getNodeName()==string("normal")
  361. ||Reader->getNodeName()==string("tangent")
  362. ||Reader->getNodeName()==string("texcoord"))
  363. {
  364. if(Reader->getNodeName()==string("vertex"))
  365. XmlRead(Reader);//Read an attribute tag
  366. //Position
  367. if(ReadPositions && Reader->getNodeName()==string("position"))
  368. {
  369. aiVector3D NewPos;
  370. NewPos.x=GetAttribute<float>(Reader, "x");
  371. NewPos.y=GetAttribute<float>(Reader, "y");
  372. NewPos.z=GetAttribute<float>(Reader, "z");
  373. theSubMesh.Positions.push_back(NewPos);
  374. }
  375. //Normal
  376. else if(ReadNormals && Reader->getNodeName()==string("normal"))
  377. {
  378. aiVector3D NewNormal;
  379. NewNormal.x=GetAttribute<float>(Reader, "x");
  380. NewNormal.y=GetAttribute<float>(Reader, "y");
  381. NewNormal.z=GetAttribute<float>(Reader, "z");
  382. theSubMesh.Normals.push_back(NewNormal);
  383. }
  384. //Tangent
  385. else if(ReadTangents && Reader->getNodeName()==string("tangent"))
  386. {
  387. aiVector3D NewTangent;
  388. NewTangent.x=GetAttribute<float>(Reader, "x");
  389. NewTangent.y=GetAttribute<float>(Reader, "y");
  390. NewTangent.z=GetAttribute<float>(Reader, "z");
  391. theSubMesh.Tangents.push_back(NewTangent);
  392. }
  393. //Uv:
  394. else if(ReadUvs && Reader->getNodeName()==string("texcoord"))
  395. {
  396. aiVector3D NewUv;
  397. NewUv.x=GetAttribute<float>(Reader, "u");
  398. NewUv.y=GetAttribute<float>(Reader, "v")*(-1)+1;//flip the uv vertikal, blender exports them so!
  399. theSubMesh.Uvs.push_back(NewUv);
  400. //skip all the following texcoords:
  401. while(Reader->getNodeName()==string("texcoord"))
  402. XmlRead(Reader);
  403. continue;//don't read another line at the end of the loop
  404. }
  405. //Attribute could not be read
  406. else
  407. {
  408. DefaultLogger::get()->warn(string("Attribute was not read: ")+Reader->getNodeName());
  409. }
  410. XmlRead(Reader);//Read the Vertex tag
  411. }
  412. }
  413. aiMesh* OgreImporter::CreateAssimpSubMesh(const SubMesh& theSubMesh, const vector<Bone>& Bones) const
  414. {
  415. const aiScene* const m_CurrentScene=this->m_CurrentScene;//make sure, that we can access but not change the scene
  416. (void)m_CurrentScene;
  417. aiMesh* NewAiMesh=new aiMesh();
  418. //Positions
  419. NewAiMesh->mVertices=new aiVector3D[theSubMesh.Positions.size()];
  420. memcpy(NewAiMesh->mVertices, &theSubMesh.Positions[0], theSubMesh.Positions.size()*sizeof(aiVector3D));
  421. NewAiMesh->mNumVertices=theSubMesh.Positions.size();
  422. //Normals
  423. if(theSubMesh.HasNormals)
  424. {
  425. NewAiMesh->mNormals=new aiVector3D[theSubMesh.Normals.size()];
  426. memcpy(NewAiMesh->mNormals, &theSubMesh.Normals[0], theSubMesh.Normals.size()*sizeof(aiVector3D));
  427. }
  428. //until we have support for bitangents, no tangents will be written
  429. /*
  430. //Tangents
  431. if(theSubMesh.HasTangents)
  432. {
  433. NewAiMesh->mTangents=new aiVector3D[theSubMesh.Tangents.size()];
  434. memcpy(NewAiMesh->mTangents, &theSubMesh.Tangents[0], theSubMesh.Tangents.size()*sizeof(aiVector3D));
  435. }
  436. */
  437. //Uvs
  438. if(0!=theSubMesh.NumUvs)
  439. {
  440. NewAiMesh->mNumUVComponents[0]=2;
  441. NewAiMesh->mTextureCoords[0]= new aiVector3D[theSubMesh.Uvs.size()];
  442. memcpy(NewAiMesh->mTextureCoords[0], &theSubMesh.Uvs[0], theSubMesh.Uvs.size()*sizeof(aiVector3D));
  443. }
  444. //---------------------------------------- Bones --------------------------------------------
  445. //Copy the weights in in Bone-Vertices Struktur
  446. //(we have them in a Vertex-Bones Structur, this is much easier for making them unique, which is required by assimp
  447. vector< vector<aiVertexWeight> > aiWeights(theSubMesh.BonesUsed);//now the outer list are the bones, and the inner vector the vertices
  448. for(unsigned int VertexId=0; VertexId<theSubMesh.Weights.size(); ++VertexId)//iterate over all vertices
  449. {
  450. for(unsigned int BoneId=0; BoneId<theSubMesh.Weights[VertexId].size(); ++BoneId)//iterate over all bones
  451. {
  452. aiVertexWeight NewWeight;
  453. NewWeight.mVertexId=VertexId;//the current Vertex, we can't use the Id form the submehs weights, because they are bone id's
  454. NewWeight.mWeight=theSubMesh.Weights[VertexId][BoneId].Value;
  455. aiWeights[theSubMesh.Weights[VertexId][BoneId].BoneId].push_back(NewWeight);
  456. }
  457. }
  458. vector<aiBone*> aiBones;
  459. aiBones.reserve(theSubMesh.BonesUsed);//the vector might be smaller, because there might be empty bones (bones that are not attached to any vertex)
  460. //create all the bones and fill them with informations
  461. for(unsigned int i=0; i<theSubMesh.BonesUsed; ++i)
  462. {
  463. if(aiWeights[i].size()>0)
  464. {
  465. aiBone* NewBone=new aiBone();
  466. NewBone->mNumWeights=aiWeights[i].size();
  467. NewBone->mWeights=new aiVertexWeight[aiWeights[i].size()];
  468. memcpy(NewBone->mWeights, &(aiWeights[i][0]), sizeof(aiVertexWeight)*aiWeights[i].size());
  469. NewBone->mName=Bones[i].Name;//The bone list should be sorted after its id's, this was done in LoadSkeleton
  470. NewBone->mOffsetMatrix=Bones[i].BoneToWorldSpace;
  471. aiBones.push_back(NewBone);
  472. }
  473. }
  474. NewAiMesh->mNumBones=aiBones.size();
  475. // mBones must be NULL if mNumBones is non 0 or the validation fails.
  476. if (aiBones.size()) {
  477. NewAiMesh->mBones=new aiBone* [aiBones.size()];
  478. memcpy(NewAiMesh->mBones, &(aiBones[0]), aiBones.size()*sizeof(aiBone*));
  479. }
  480. //______________________________________________________________________________________________________
  481. //Faces
  482. NewAiMesh->mFaces=new aiFace[theSubMesh.FaceList.size()];
  483. for(unsigned int i=0; i<theSubMesh.FaceList.size(); ++i)
  484. {
  485. NewAiMesh->mFaces[i].mNumIndices=3;
  486. NewAiMesh->mFaces[i].mIndices=new unsigned int[3];
  487. NewAiMesh->mFaces[i].mIndices[0]=theSubMesh.FaceList[i].VertexIndices[0];
  488. NewAiMesh->mFaces[i].mIndices[1]=theSubMesh.FaceList[i].VertexIndices[1];
  489. NewAiMesh->mFaces[i].mIndices[2]=theSubMesh.FaceList[i].VertexIndices[2];
  490. }
  491. NewAiMesh->mNumFaces=theSubMesh.FaceList.size();
  492. //Link the material:
  493. NewAiMesh->mMaterialIndex=theSubMesh.MaterialIndex;//the index is set by the function who called ReadSubMesh
  494. return NewAiMesh;
  495. }
  496. void OgreImporter::LoadSkeleton(std::string FileName, vector<Bone> &Bones, vector<Animation> &Animations) const
  497. {
  498. const aiScene* const m_CurrentScene=this->m_CurrentScene;//make sure, that we can access but not change the scene
  499. (void)m_CurrentScene;
  500. //most likely the skeleton file will only end with .skeleton
  501. //But this is a xml reader, so we need: .skeleton.xml
  502. FileName+=".xml";
  503. DefaultLogger::get()->debug(string("Loading Skeleton: ")+FileName);
  504. //Open the File:
  505. boost::scoped_ptr<IOStream> File(m_CurrentIOHandler->Open(FileName));
  506. if(NULL==File.get())
  507. throw DeadlyImportError("Failed to open skeleton file "+FileName+".");
  508. //Read the Mesh File:
  509. boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(File.get()));
  510. XmlReader* SkeletonFile = irr::io::createIrrXMLReader(mIOWrapper.get());
  511. if(!SkeletonFile)
  512. throw DeadlyImportError(string("Failed to create XML Reader for ")+FileName);
  513. //Quick note: Whoever read this should know this one thing: irrXml fucking sucks!!!
  514. XmlRead(SkeletonFile);
  515. if(string("skeleton")!=SkeletonFile->getNodeName())
  516. throw DeadlyImportError("No <skeleton> node in SkeletonFile: "+FileName);
  517. //------------------------------------load bones-----------------------------------------
  518. XmlRead(SkeletonFile);
  519. if(string("bones")!=SkeletonFile->getNodeName())
  520. throw DeadlyImportError("No bones node in skeleton "+FileName);
  521. XmlRead(SkeletonFile);
  522. while(string("bone")==SkeletonFile->getNodeName())
  523. {
  524. //TODO: Maybe we can have bone ids for the errrors, but normaly, they should never appear, so what....
  525. //read a new bone:
  526. Bone NewBone;
  527. NewBone.Id=GetAttribute<int>(SkeletonFile, "id");
  528. NewBone.Name=GetAttribute<string>(SkeletonFile, "name");
  529. //load the position:
  530. XmlRead(SkeletonFile);
  531. if(string("position")!=SkeletonFile->getNodeName())
  532. throw DeadlyImportError("Position is not first node in Bone!");
  533. NewBone.Position.x=GetAttribute<float>(SkeletonFile, "x");
  534. NewBone.Position.y=GetAttribute<float>(SkeletonFile, "y");
  535. NewBone.Position.z=GetAttribute<float>(SkeletonFile, "z");
  536. //Rotation:
  537. XmlRead(SkeletonFile);
  538. if(string("rotation")!=SkeletonFile->getNodeName())
  539. throw DeadlyImportError("Rotation is not the second node in Bone!");
  540. NewBone.RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  541. XmlRead(SkeletonFile);
  542. if(string("axis")!=SkeletonFile->getNodeName())
  543. throw DeadlyImportError("No axis specified for bone rotation!");
  544. NewBone.RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  545. NewBone.RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  546. NewBone.RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  547. //append the newly loaded bone to the bone list
  548. Bones.push_back(NewBone);
  549. //Proceed to the next bone:
  550. XmlRead(SkeletonFile);
  551. }
  552. //The bones in the file a not neccesarly ordered by there id's so we do it now:
  553. std::sort(Bones.begin(), Bones.end());
  554. //now the id of each bone should be equal to its position in the vector:
  555. //so we do a simple check:
  556. {
  557. bool IdsOk=true;
  558. for(int i=0; i<static_cast<signed int>(Bones.size()); ++i)//i is signed, because all Id's are also signed!
  559. {
  560. if(Bones[i].Id!=i)
  561. IdsOk=false;
  562. }
  563. if(!IdsOk)
  564. throw DeadlyImportError("Bone Ids are not valid!"+FileName);
  565. }
  566. DefaultLogger::get()->debug((Formatter::format(),"Number of bones: ",Bones.size()));
  567. //________________________________________________________________________________
  568. //----------------------------load bonehierarchy--------------------------------
  569. if(string("bonehierarchy")!=SkeletonFile->getNodeName())
  570. throw DeadlyImportError("no bonehierarchy node in "+FileName);
  571. DefaultLogger::get()->debug("loading bonehierarchy...");
  572. XmlRead(SkeletonFile);
  573. while(string("boneparent")==SkeletonFile->getNodeName())
  574. {
  575. string Child, Parent;
  576. Child=GetAttribute<string>(SkeletonFile, "bone");
  577. Parent=GetAttribute<string>(SkeletonFile, "parent");
  578. unsigned int ChildId, ParentId;
  579. ChildId=find(Bones.begin(), Bones.end(), Child)->Id;
  580. ParentId=find(Bones.begin(), Bones.end(), Parent)->Id;
  581. Bones[ChildId].ParentId=ParentId;
  582. Bones[ParentId].Children.push_back(ChildId);
  583. XmlRead(SkeletonFile);//i once forget this line, which led to an endless loop, did i mentioned, that irrxml sucks??
  584. }
  585. //_____________________________________________________________________________
  586. //--------- Calculate the WorldToBoneSpace Matrix recursivly for all bones: ------------------
  587. BOOST_FOREACH(Bone theBone, Bones)
  588. {
  589. if(-1==theBone.ParentId) //the bone is a root bone
  590. {
  591. theBone.CalculateBoneToWorldSpaceMatrix(Bones);
  592. }
  593. }
  594. //_______________________________________________________________________
  595. //---------------------------load animations-----------------------------
  596. if(string("animations")==SkeletonFile->getNodeName())//animations are optional values
  597. {
  598. DefaultLogger::get()->debug("Loading Animations");
  599. XmlRead(SkeletonFile);
  600. while(string("animation")==SkeletonFile->getNodeName())
  601. {
  602. Animation NewAnimation;
  603. NewAnimation.Name=GetAttribute<string>(SkeletonFile, "name");
  604. NewAnimation.Length=GetAttribute<float>(SkeletonFile, "length");
  605. //Load all Tracks
  606. XmlRead(SkeletonFile);
  607. if(string("tracks")!=SkeletonFile->getNodeName())
  608. throw DeadlyImportError("no tracks node in animation");
  609. XmlRead(SkeletonFile);
  610. while(string("track")==SkeletonFile->getNodeName())
  611. {
  612. Track NewTrack;
  613. NewTrack.BoneName=GetAttribute<string>(SkeletonFile, "bone");
  614. //Load all keyframes;
  615. XmlRead(SkeletonFile);
  616. if(string("keyframes")!=SkeletonFile->getNodeName())
  617. throw DeadlyImportError("no keyframes node!");
  618. XmlRead(SkeletonFile);
  619. while(string("keyframe")==SkeletonFile->getNodeName())
  620. {
  621. Keyframe NewKeyframe;
  622. NewKeyframe.Time=GetAttribute<float>(SkeletonFile, "time");
  623. //loop over the attributes:
  624. while(true)
  625. {
  626. XmlRead(SkeletonFile);
  627. //If any property doesn't show up, it will keep its initialization value
  628. //Position:
  629. if(string("translate")==SkeletonFile->getNodeName())
  630. {
  631. NewKeyframe.Position.x=GetAttribute<float>(SkeletonFile, "x");
  632. NewKeyframe.Position.y=GetAttribute<float>(SkeletonFile, "y");
  633. NewKeyframe.Position.z=GetAttribute<float>(SkeletonFile, "z");
  634. }
  635. //Rotation:
  636. else if(string("rotate")!=SkeletonFile->getNodeName())
  637. {
  638. float RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  639. aiVector3D RotationAxis;
  640. XmlRead(SkeletonFile);
  641. if(string("axis")!=SkeletonFile->getNodeName())
  642. throw DeadlyImportError("No axis for keyframe rotation!");
  643. RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  644. RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  645. RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  646. NewKeyframe.Rotation=aiQuaternion(RotationAxis, RotationAngle);
  647. }
  648. //Scaling:
  649. else if(string("scale")==SkeletonFile->getNodeName())
  650. {
  651. NewKeyframe.Scaling.x=GetAttribute<float>(SkeletonFile, "x");
  652. NewKeyframe.Scaling.y=GetAttribute<float>(SkeletonFile, "y");
  653. NewKeyframe.Scaling.z=GetAttribute<float>(SkeletonFile, "z");
  654. }
  655. //we suppose, that we read all attributes and this is a new keyframe or the end of the animation
  656. else
  657. break;
  658. }
  659. NewTrack.Keyframes.push_back(NewKeyframe);
  660. XmlRead(SkeletonFile);
  661. }
  662. NewAnimation.Tracks.push_back(NewTrack);
  663. }
  664. Animations.push_back(NewAnimation);
  665. }
  666. }
  667. //_____________________________________________________________________________
  668. }
  669. void OgreImporter::CreateAssimpSkeleton(const std::vector<Bone> &Bones, const std::vector<Animation> &/*Animations*/)
  670. {
  671. if(!m_CurrentScene->mRootNode)
  672. throw DeadlyImportError("No root node exists!!");
  673. if(0!=m_CurrentScene->mRootNode->mNumChildren)
  674. throw DeadlyImportError("Root Node already has childnodes!");
  675. //Createt the assimp bone hierarchy
  676. DefaultLogger::get()->debug("Root Bones");
  677. vector<aiNode*> RootBoneNodes;
  678. BOOST_FOREACH(Bone theBone, Bones)
  679. {
  680. if(-1==theBone.ParentId) //the bone is a root bone
  681. {
  682. DefaultLogger::get()->debug(theBone.Name);
  683. RootBoneNodes.push_back(CreateAiNodeFromBone(theBone.Id, Bones, m_CurrentScene->mRootNode));//which will recursily add all other nodes
  684. }
  685. }
  686. if (RootBoneNodes.size()) {
  687. m_CurrentScene->mRootNode->mNumChildren=RootBoneNodes.size();
  688. m_CurrentScene->mRootNode->mChildren=new aiNode*[RootBoneNodes.size()];
  689. memcpy(m_CurrentScene->mRootNode->mChildren, &RootBoneNodes[0], sizeof(aiNode*)*RootBoneNodes.size());
  690. }
  691. }
  692. void OgreImporter::PutAnimationsInScene(const std::vector<Bone> &Bones, const std::vector<Animation> &Animations)
  693. {
  694. //-----------------Create the Assimp Animations --------------------
  695. if(Animations.size()>0)//Maybe the model had only a skeleton and no animations. (If it also has no skeleton, this function would'nt have been called
  696. {
  697. m_CurrentScene->mNumAnimations=Animations.size();
  698. m_CurrentScene->mAnimations=new aiAnimation*[Animations.size()];
  699. for(unsigned int i=0; i<Animations.size(); ++i)//create all animations
  700. {
  701. aiAnimation* NewAnimation=new aiAnimation();
  702. NewAnimation->mName=Animations[i].Name;
  703. NewAnimation->mDuration=Animations[i].Length;
  704. NewAnimation->mTicksPerSecond=1.0f;
  705. //Create all tracks in this animation
  706. NewAnimation->mNumChannels=Animations[i].Tracks.size();
  707. NewAnimation->mChannels=new aiNodeAnim*[Animations[i].Tracks.size()];
  708. for(unsigned int j=0; j<Animations[i].Tracks.size(); ++j)
  709. {
  710. aiNodeAnim* NewNodeAnim=new aiNodeAnim();
  711. NewNodeAnim->mNodeName=Animations[i].Tracks[j].BoneName;
  712. //we need this, to acces the bones default pose, which we need to make keys absolute
  713. vector<Bone>::const_iterator CurBone=find(Bones.begin(), Bones.end(), NewNodeAnim->mNodeName);
  714. aiMatrix4x4 t0, t1;
  715. aiMatrix4x4 DefBonePose=//The default bone pose doesnt have a scaling value
  716. aiMatrix4x4::Rotation(CurBone->RotationAngle, CurBone->RotationAxis, t0)
  717. * aiMatrix4x4::Translation(CurBone->Position, t1);
  718. //Create the keyframe arrays...
  719. unsigned int KeyframeCount=Animations[i].Tracks[j].Keyframes.size();
  720. NewNodeAnim->mNumPositionKeys=KeyframeCount;
  721. NewNodeAnim->mPositionKeys=new aiVectorKey[KeyframeCount];
  722. NewNodeAnim->mNumRotationKeys=KeyframeCount;
  723. NewNodeAnim->mRotationKeys=new aiQuatKey[KeyframeCount];
  724. NewNodeAnim->mNumScalingKeys=KeyframeCount;
  725. NewNodeAnim->mScalingKeys=new aiVectorKey[KeyframeCount];
  726. //...and fill them
  727. for(unsigned int k=0; k<KeyframeCount; ++k)
  728. {
  729. aiMatrix4x4 t2, t3;
  730. //Create a matrix to transfrom a vector from the bones default pose to the bone bones in this animation key
  731. aiMatrix4x4 PoseToKey=aiMatrix4x4::Scaling(Animations[i].Tracks[j].Keyframes[k].Scaling, t2) //scale
  732. * aiMatrix4x4(Animations[i].Tracks[j].Keyframes[k].Rotation.GetMatrix()) //rot
  733. * aiMatrix4x4::Translation(Animations[i].Tracks[j].Keyframes[k].Position, t3); //pos
  734. //calculate the complete transformation from world space to bone space
  735. aiMatrix4x4 CompleteTransform=DefBonePose * PoseToKey;
  736. aiVector3D Pos;
  737. aiQuaternion Rot;
  738. aiVector3D Scale;
  739. CompleteTransform.Decompose(Scale, Rot, Pos);
  740. NewNodeAnim->mPositionKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  741. NewNodeAnim->mPositionKeys[k].mValue=Pos;
  742. NewNodeAnim->mRotationKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  743. NewNodeAnim->mRotationKeys[k].mValue=Rot;
  744. NewNodeAnim->mScalingKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  745. NewNodeAnim->mScalingKeys[k].mValue=Scale;
  746. }
  747. NewAnimation->mChannels[j]=NewNodeAnim;
  748. }
  749. m_CurrentScene->mAnimations[i]=NewAnimation;
  750. }
  751. }
  752. //TODO: Auf nicht vorhandene Animationskeys achten!
  753. //#pragma warning (s.o.)
  754. //__________________________________________________________________
  755. }
  756. aiNode* OgreImporter::CreateAiNodeFromBone(int BoneId, const std::vector<Bone> &Bones, aiNode* ParentNode)
  757. {
  758. //----Create the node for this bone and set its values-----
  759. aiNode* NewNode=new aiNode(Bones[BoneId].Name);
  760. NewNode->mParent=ParentNode;
  761. aiMatrix4x4 t0,t1;
  762. //create a matrix from the transformation values of the ogre bone
  763. NewNode->mTransformation=aiMatrix4x4::Rotation(Bones[BoneId].RotationAngle, Bones[BoneId].RotationAxis, t1)
  764. * aiMatrix4x4::Translation(Bones[BoneId].Position, t0)
  765. ;
  766. //__________________________________________________________
  767. //---------- recursivly create all children Nodes: ----------
  768. NewNode->mNumChildren=Bones[BoneId].Children.size();
  769. NewNode->mChildren=new aiNode*[Bones[BoneId].Children.size()];
  770. for(unsigned int i=0; i<Bones[BoneId].Children.size(); ++i)
  771. {
  772. NewNode->mChildren[i]=CreateAiNodeFromBone(Bones[BoneId].Children[i], Bones, NewNode);
  773. }
  774. //____________________________________________________
  775. return NewNode;
  776. }
  777. void Bone::CalculateBoneToWorldSpaceMatrix(vector<Bone> &Bones)
  778. {
  779. //Calculate the matrix for this bone:
  780. aiMatrix4x4 t0,t1;
  781. aiMatrix4x4 Transf=aiMatrix4x4::Translation(-Position, t0)
  782. * aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1)
  783. ;
  784. if(-1==ParentId)
  785. {
  786. BoneToWorldSpace=Transf;
  787. }
  788. else
  789. {
  790. BoneToWorldSpace=Transf*Bones[ParentId].BoneToWorldSpace;
  791. }
  792. //and recursivly for all children:
  793. BOOST_FOREACH(int theChildren, Children)
  794. {
  795. Bones[theChildren].CalculateBoneToWorldSpaceMatrix(Bones);
  796. }
  797. }
  798. }//namespace Ogre
  799. }//namespace Assimp
  800. #endif // !! ASSIMP_BUILD_NO_OGRE_IMPORTER