Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

1194 рядки
29 KiB

  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. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  34. #include "OgreStructs.h"
  35. #include "TinyFormatter.h"
  36. namespace Assimp
  37. {
  38. namespace Ogre
  39. {
  40. // VertexElement
  41. VertexElement::VertexElement() :
  42. index(0),
  43. source(0),
  44. offset(0),
  45. type(VET_FLOAT1),
  46. semantic(VES_POSITION)
  47. {
  48. }
  49. size_t VertexElement::Size() const
  50. {
  51. return TypeSize(type);
  52. }
  53. size_t VertexElement::ComponentCount() const
  54. {
  55. return ComponentCount(type);
  56. }
  57. size_t VertexElement::ComponentCount(Type type)
  58. {
  59. switch(type)
  60. {
  61. case VET_COLOUR:
  62. case VET_COLOUR_ABGR:
  63. case VET_COLOUR_ARGB:
  64. case VET_FLOAT1:
  65. case VET_DOUBLE1:
  66. case VET_SHORT1:
  67. case VET_USHORT1:
  68. case VET_INT1:
  69. case VET_UINT1:
  70. return 1;
  71. case VET_FLOAT2:
  72. case VET_DOUBLE2:
  73. case VET_SHORT2:
  74. case VET_USHORT2:
  75. case VET_INT2:
  76. case VET_UINT2:
  77. return 2;
  78. case VET_FLOAT3:
  79. case VET_DOUBLE3:
  80. case VET_SHORT3:
  81. case VET_USHORT3:
  82. case VET_INT3:
  83. case VET_UINT3:
  84. return 3;
  85. case VET_FLOAT4:
  86. case VET_DOUBLE4:
  87. case VET_SHORT4:
  88. case VET_USHORT4:
  89. case VET_INT4:
  90. case VET_UINT4:
  91. case VET_UBYTE4:
  92. return 4;
  93. }
  94. return 0;
  95. }
  96. size_t VertexElement::TypeSize(Type type)
  97. {
  98. switch(type)
  99. {
  100. case VET_COLOUR:
  101. case VET_COLOUR_ABGR:
  102. case VET_COLOUR_ARGB:
  103. return sizeof(unsigned int);
  104. case VET_FLOAT1:
  105. return sizeof(float);
  106. case VET_FLOAT2:
  107. return sizeof(float)*2;
  108. case VET_FLOAT3:
  109. return sizeof(float)*3;
  110. case VET_FLOAT4:
  111. return sizeof(float)*4;
  112. case VET_DOUBLE1:
  113. return sizeof(double);
  114. case VET_DOUBLE2:
  115. return sizeof(double)*2;
  116. case VET_DOUBLE3:
  117. return sizeof(double)*3;
  118. case VET_DOUBLE4:
  119. return sizeof(double)*4;
  120. case VET_SHORT1:
  121. return sizeof(short);
  122. case VET_SHORT2:
  123. return sizeof(short)*2;
  124. case VET_SHORT3:
  125. return sizeof(short)*3;
  126. case VET_SHORT4:
  127. return sizeof(short)*4;
  128. case VET_USHORT1:
  129. return sizeof(unsigned short);
  130. case VET_USHORT2:
  131. return sizeof(unsigned short)*2;
  132. case VET_USHORT3:
  133. return sizeof(unsigned short)*3;
  134. case VET_USHORT4:
  135. return sizeof(unsigned short)*4;
  136. case VET_INT1:
  137. return sizeof(int);
  138. case VET_INT2:
  139. return sizeof(int)*2;
  140. case VET_INT3:
  141. return sizeof(int)*3;
  142. case VET_INT4:
  143. return sizeof(int)*4;
  144. case VET_UINT1:
  145. return sizeof(unsigned int);
  146. case VET_UINT2:
  147. return sizeof(unsigned int)*2;
  148. case VET_UINT3:
  149. return sizeof(unsigned int)*3;
  150. case VET_UINT4:
  151. return sizeof(unsigned int)*4;
  152. case VET_UBYTE4:
  153. return sizeof(unsigned char)*4;
  154. }
  155. return 0;
  156. }
  157. std::string VertexElement::TypeToString()
  158. {
  159. return TypeToString(type);
  160. }
  161. std::string VertexElement::TypeToString(Type type)
  162. {
  163. switch(type)
  164. {
  165. case VET_COLOUR: return "COLOUR";
  166. case VET_COLOUR_ABGR: return "COLOUR_ABGR";
  167. case VET_COLOUR_ARGB: return "COLOUR_ARGB";
  168. case VET_FLOAT1: return "FLOAT1";
  169. case VET_FLOAT2: return "FLOAT2";
  170. case VET_FLOAT3: return "FLOAT3";
  171. case VET_FLOAT4: return "FLOAT4";
  172. case VET_DOUBLE1: return "DOUBLE1";
  173. case VET_DOUBLE2: return "DOUBLE2";
  174. case VET_DOUBLE3: return "DOUBLE3";
  175. case VET_DOUBLE4: return "DOUBLE4";
  176. case VET_SHORT1: return "SHORT1";
  177. case VET_SHORT2: return "SHORT2";
  178. case VET_SHORT3: return "SHORT3";
  179. case VET_SHORT4: return "SHORT4";
  180. case VET_USHORT1: return "USHORT1";
  181. case VET_USHORT2: return "USHORT2";
  182. case VET_USHORT3: return "USHORT3";
  183. case VET_USHORT4: return "USHORT4";
  184. case VET_INT1: return "INT1";
  185. case VET_INT2: return "INT2";
  186. case VET_INT3: return "INT3";
  187. case VET_INT4: return "INT4";
  188. case VET_UINT1: return "UINT1";
  189. case VET_UINT2: return "UINT2";
  190. case VET_UINT3: return "UINT3";
  191. case VET_UINT4: return "UINT4";
  192. case VET_UBYTE4: return "UBYTE4";
  193. }
  194. return "Uknown_VertexElement::Type";
  195. }
  196. std::string VertexElement::SemanticToString()
  197. {
  198. return SemanticToString(semantic);
  199. }
  200. std::string VertexElement::SemanticToString(Semantic semantic)
  201. {
  202. switch(semantic)
  203. {
  204. case VES_POSITION: return "POSITION";
  205. case VES_BLEND_WEIGHTS: return "BLEND_WEIGHTS";
  206. case VES_BLEND_INDICES: return "BLEND_INDICES";
  207. case VES_NORMAL: return "NORMAL";
  208. case VES_DIFFUSE: return "DIFFUSE";
  209. case VES_SPECULAR: return "SPECULAR";
  210. case VES_TEXTURE_COORDINATES: return "TEXTURE_COORDINATES";
  211. case VES_BINORMAL: return "BINORMAL";
  212. case VES_TANGENT: return "TANGENT";
  213. }
  214. return "Uknown_VertexElement::Semantic";
  215. }
  216. // IVertexData
  217. IVertexData::IVertexData() :
  218. count(0)
  219. {
  220. }
  221. bool IVertexData::HasBoneAssignments() const
  222. {
  223. return !boneAssignments.empty();
  224. }
  225. void IVertexData::AddVertexMapping(uint32_t oldIndex, uint32_t newIndex)
  226. {
  227. BoneAssignmentsForVertex(oldIndex, newIndex, boneAssignmentsMap[newIndex]);
  228. vertexIndexMapping[oldIndex].push_back(newIndex);
  229. }
  230. void IVertexData::BoneAssignmentsForVertex(uint32_t currentIndex, uint32_t newIndex, VertexBoneAssignmentList &dest) const
  231. {
  232. for (VertexBoneAssignmentList::const_iterator iter=boneAssignments.begin(), end=boneAssignments.end();
  233. iter!=end; ++iter)
  234. {
  235. if (iter->vertexIndex == currentIndex)
  236. {
  237. VertexBoneAssignment a = (*iter);
  238. a.vertexIndex = newIndex;
  239. dest.push_back(a);
  240. }
  241. }
  242. }
  243. AssimpVertexBoneWeightList IVertexData::AssimpBoneWeights(size_t vertices)
  244. {
  245. AssimpVertexBoneWeightList weights;
  246. for(size_t vi=0; vi<vertices; ++vi)
  247. {
  248. VertexBoneAssignmentList &vertexWeights = boneAssignmentsMap[vi];
  249. for (VertexBoneAssignmentList::const_iterator iter=vertexWeights.begin(), end=vertexWeights.end();
  250. iter!=end; ++iter)
  251. {
  252. std::vector<aiVertexWeight> &boneWeights = weights[iter->boneIndex];
  253. boneWeights.push_back(aiVertexWeight(vi, iter->weight));
  254. }
  255. }
  256. return weights;
  257. }
  258. std::set<uint16_t> IVertexData::ReferencedBonesByWeights() const
  259. {
  260. std::set<uint16_t> referenced;
  261. for (VertexBoneAssignmentList::const_iterator iter=boneAssignments.begin(), end=boneAssignments.end();
  262. iter!=end; ++iter)
  263. {
  264. referenced.insert(iter->boneIndex);
  265. }
  266. return referenced;
  267. }
  268. // VertexData
  269. VertexData::VertexData()
  270. {
  271. }
  272. VertexData::~VertexData()
  273. {
  274. Reset();
  275. }
  276. void VertexData::Reset()
  277. {
  278. // Releases shared ptr memory streams.
  279. vertexBindings.clear();
  280. vertexElements.clear();
  281. }
  282. uint32_t VertexData::VertexSize(uint16_t source) const
  283. {
  284. uint32_t size = 0;
  285. for(VertexElementList::const_iterator iter=vertexElements.begin(), end=vertexElements.end(); iter != end; ++iter)
  286. {
  287. if (iter->source == source)
  288. size += iter->Size();
  289. }
  290. return size;
  291. }
  292. MemoryStream *VertexData::VertexBuffer(uint16_t source)
  293. {
  294. if (vertexBindings.find(source) != vertexBindings.end())
  295. return vertexBindings[source].get();
  296. return 0;
  297. }
  298. VertexElement *VertexData::GetVertexElement(VertexElement::Semantic semantic, uint16_t index)
  299. {
  300. for(VertexElementList::iterator iter=vertexElements.begin(), end=vertexElements.end(); iter != end; ++iter)
  301. {
  302. VertexElement &element = (*iter);
  303. if (element.semantic == semantic && element.index == index)
  304. return &element;
  305. }
  306. return 0;
  307. }
  308. // VertexDataXml
  309. VertexDataXml::VertexDataXml()
  310. {
  311. }
  312. bool VertexDataXml::HasPositions() const
  313. {
  314. return !positions.empty();
  315. }
  316. bool VertexDataXml::HasNormals() const
  317. {
  318. return !normals.empty();
  319. }
  320. bool VertexDataXml::HasTangents() const
  321. {
  322. return !tangents.empty();
  323. }
  324. bool VertexDataXml::HasUvs() const
  325. {
  326. return !uvs.empty();
  327. }
  328. size_t VertexDataXml::NumUvs() const
  329. {
  330. return uvs.size();
  331. }
  332. // IndexData
  333. IndexData::IndexData() :
  334. count(0),
  335. faceCount(0),
  336. is32bit(false)
  337. {
  338. }
  339. IndexData::~IndexData()
  340. {
  341. Reset();
  342. }
  343. void IndexData::Reset()
  344. {
  345. // Release shared ptr memory stream.
  346. buffer.reset();
  347. }
  348. size_t IndexData::IndexSize() const
  349. {
  350. return (is32bit ? sizeof(uint32_t) : sizeof(uint16_t));
  351. }
  352. size_t IndexData::FaceSize() const
  353. {
  354. return IndexSize() * 3;
  355. }
  356. // Mesh
  357. Mesh::Mesh() :
  358. sharedVertexData(0),
  359. skeleton(0),
  360. hasSkeletalAnimations(false)
  361. {
  362. }
  363. Mesh::~Mesh()
  364. {
  365. Reset();
  366. }
  367. void Mesh::Reset()
  368. {
  369. OGRE_SAFE_DELETE(skeleton)
  370. OGRE_SAFE_DELETE(sharedVertexData)
  371. for(size_t i=0, len=subMeshes.size(); i<len; ++i) {
  372. OGRE_SAFE_DELETE(subMeshes[i])
  373. }
  374. subMeshes.clear();
  375. for(size_t i=0, len=animations.size(); i<len; ++i) {
  376. OGRE_SAFE_DELETE(animations[i])
  377. }
  378. animations.clear();
  379. for(size_t i=0, len=poses.size(); i<len; ++i) {
  380. OGRE_SAFE_DELETE(poses[i])
  381. }
  382. poses.clear();
  383. }
  384. size_t Mesh::NumSubMeshes() const
  385. {
  386. return subMeshes.size();
  387. }
  388. SubMesh *Mesh::GetSubMesh(uint16_t index) const
  389. {
  390. for(size_t i=0; i<subMeshes.size(); ++i)
  391. if (subMeshes[i]->index == index)
  392. return subMeshes[i];
  393. return 0;
  394. }
  395. void Mesh::ConvertToAssimpScene(aiScene* dest)
  396. {
  397. // Setup
  398. dest->mNumMeshes = NumSubMeshes();
  399. dest->mMeshes = new aiMesh*[dest->mNumMeshes];
  400. // Create root node
  401. dest->mRootNode = new aiNode();
  402. dest->mRootNode->mNumMeshes = dest->mNumMeshes;
  403. dest->mRootNode->mMeshes = new unsigned int[dest->mRootNode->mNumMeshes];
  404. // Export meshes
  405. for(size_t i=0; i<dest->mNumMeshes; ++i)
  406. {
  407. dest->mMeshes[i] = subMeshes[i]->ConvertToAssimpMesh(this);
  408. dest->mRootNode->mMeshes[i] = i;
  409. }
  410. // Export skeleton
  411. if (skeleton)
  412. {
  413. // Bones
  414. if (!skeleton->bones.empty())
  415. {
  416. BoneList rootBones = skeleton->RootBones();
  417. dest->mRootNode->mNumChildren = rootBones.size();
  418. dest->mRootNode->mChildren = new aiNode*[dest->mRootNode->mNumChildren];
  419. for(size_t i=0, len=rootBones.size(); i<len; ++i)
  420. {
  421. dest->mRootNode->mChildren[i] = rootBones[i]->ConvertToAssimpNode(skeleton, dest->mRootNode);
  422. }
  423. }
  424. // Animations
  425. if (!skeleton->animations.empty())
  426. {
  427. dest->mNumAnimations = skeleton->animations.size();
  428. dest->mAnimations = new aiAnimation*[dest->mNumAnimations];
  429. for(size_t i=0, len=skeleton->animations.size(); i<len; ++i)
  430. {
  431. dest->mAnimations[i] = skeleton->animations[i]->ConvertToAssimpAnimation();
  432. }
  433. }
  434. }
  435. }
  436. // ISubMesh
  437. ISubMesh::ISubMesh() :
  438. index(0),
  439. materialIndex(-1),
  440. usesSharedVertexData(false),
  441. operationType(OT_POINT_LIST)
  442. {
  443. }
  444. // SubMesh
  445. SubMesh::SubMesh() :
  446. vertexData(0),
  447. indexData(new IndexData())
  448. {
  449. }
  450. SubMesh::~SubMesh()
  451. {
  452. Reset();
  453. }
  454. void SubMesh::Reset()
  455. {
  456. OGRE_SAFE_DELETE(vertexData)
  457. OGRE_SAFE_DELETE(indexData)
  458. }
  459. aiMesh *SubMesh::ConvertToAssimpMesh(Mesh *parent)
  460. {
  461. if (operationType != OT_TRIANGLE_LIST) {
  462. throw DeadlyImportError(Formatter::format() << "Only mesh operation type OT_TRIANGLE_LIST is supported. Found " << operationType);
  463. }
  464. aiMesh *dest = new aiMesh();
  465. dest->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  466. if (!name.empty())
  467. dest->mName = name;
  468. // Material index
  469. if (materialIndex != -1)
  470. dest->mMaterialIndex = materialIndex;
  471. // Pick source vertex data from shader geometry or from internal geometry.
  472. VertexData *src = (!usesSharedVertexData ? vertexData : parent->sharedVertexData);
  473. VertexElement *positionsElement = src->GetVertexElement(VertexElement::VES_POSITION);
  474. VertexElement *normalsElement = src->GetVertexElement(VertexElement::VES_NORMAL);
  475. VertexElement *uv1Element = src->GetVertexElement(VertexElement::VES_TEXTURE_COORDINATES, 0);
  476. VertexElement *uv2Element = src->GetVertexElement(VertexElement::VES_TEXTURE_COORDINATES, 1);
  477. // Sanity checks
  478. if (!positionsElement) {
  479. throw DeadlyImportError("Failed to import Ogre VertexElement::VES_POSITION. Mesh does not have vertex positions!");
  480. } else if (positionsElement->type != VertexElement::VET_FLOAT3) {
  481. throw DeadlyImportError("Ogre Mesh position vertex element type != VertexElement::VET_FLOAT3. This is not supported.");
  482. } else if (normalsElement && normalsElement->type != VertexElement::VET_FLOAT3) {
  483. throw DeadlyImportError("Ogre Mesh normal vertex element type != VertexElement::VET_FLOAT3. This is not supported.");
  484. }
  485. // Faces
  486. dest->mNumFaces = indexData->faceCount;
  487. dest->mFaces = new aiFace[dest->mNumFaces];
  488. // Assimp required unique vertices, we need to convert from Ogres shared indexing.
  489. size_t uniqueVertexCount = dest->mNumFaces * 3;
  490. dest->mNumVertices = uniqueVertexCount;
  491. dest->mVertices = new aiVector3D[dest->mNumVertices];
  492. // Source streams
  493. MemoryStream *positions = src->VertexBuffer(positionsElement->source);
  494. MemoryStream *normals = (normalsElement ? src->VertexBuffer(normalsElement->source) : 0);
  495. MemoryStream *uv1 = (uv1Element ? src->VertexBuffer(uv1Element->source) : 0);
  496. MemoryStream *uv2 = (uv2Element ? src->VertexBuffer(uv2Element->source) : 0);
  497. // Element size
  498. const size_t sizePosition = positionsElement->Size();
  499. const size_t sizeNormal = (normalsElement ? normalsElement->Size() : 0);
  500. const size_t sizeUv1 = (uv1Element ? uv1Element->Size() : 0);
  501. const size_t sizeUv2 = (uv2Element ? uv2Element->Size() : 0);
  502. // Vertex width
  503. const size_t vWidthPosition = src->VertexSize(positionsElement->source);
  504. const size_t vWidthNormal = (normalsElement ? src->VertexSize(normalsElement->source) : 0);
  505. const size_t vWidthUv1 = (uv1Element ? src->VertexSize(uv1Element->source) : 0);
  506. const size_t vWidthUv2 = (uv2Element ? src->VertexSize(uv2Element->source) : 0);
  507. bool boneAssignments = src->HasBoneAssignments();
  508. // Prepare normals
  509. if (normals)
  510. dest->mNormals = new aiVector3D[dest->mNumVertices];
  511. // Prepare UVs, ignoring incompatible UVs.
  512. if (uv1)
  513. {
  514. if (uv1Element->type == VertexElement::VET_FLOAT2 || uv1Element->type == VertexElement::VET_FLOAT3)
  515. {
  516. dest->mNumUVComponents[0] = uv1Element->ComponentCount();
  517. dest->mTextureCoords[0] = new aiVector3D[dest->mNumVertices];
  518. }
  519. else
  520. {
  521. DefaultLogger::get()->warn(Formatter::format() << "Ogre imported UV0 type " << uv1Element->TypeToString() << " is not compatible with Assimp. Ignoring UV.");
  522. uv1 = 0;
  523. }
  524. }
  525. if (uv2)
  526. {
  527. if (uv2Element->type == VertexElement::VET_FLOAT2 || uv2Element->type == VertexElement::VET_FLOAT3)
  528. {
  529. dest->mNumUVComponents[1] = uv2Element->ComponentCount();
  530. dest->mTextureCoords[1] = new aiVector3D[dest->mNumVertices];
  531. }
  532. else
  533. {
  534. DefaultLogger::get()->warn(Formatter::format() << "Ogre imported UV0 type " << uv2Element->TypeToString() << " is not compatible with Assimp. Ignoring UV.");
  535. uv2 = 0;
  536. }
  537. }
  538. aiVector3D *uv1Dest = (uv1 ? dest->mTextureCoords[0] : 0);
  539. aiVector3D *uv2Dest = (uv2 ? dest->mTextureCoords[1] : 0);
  540. MemoryStream *faces = indexData->buffer.get();
  541. for (size_t fi=0, isize=indexData->IndexSize(), fsize=indexData->FaceSize();
  542. fi<dest->mNumFaces; ++fi)
  543. {
  544. // Source Ogre face
  545. aiFace ogreFace;
  546. ogreFace.mNumIndices = 3;
  547. ogreFace.mIndices = new unsigned int[3];
  548. faces->Seek(fi * fsize, aiOrigin_SET);
  549. if (indexData->is32bit)
  550. {
  551. faces->Read(&ogreFace.mIndices[0], isize, 3);
  552. }
  553. else
  554. {
  555. uint16_t iout = 0;
  556. for (size_t ii=0; ii<3; ++ii)
  557. {
  558. faces->Read(&iout, isize, 1);
  559. ogreFace.mIndices[ii] = static_cast<unsigned int>(iout);
  560. }
  561. }
  562. // Destination Assimp face
  563. aiFace &face = dest->mFaces[fi];
  564. face.mNumIndices = 3;
  565. face.mIndices = new unsigned int[3];
  566. const size_t pos = fi * 3;
  567. for (size_t v=0; v<3; ++v)
  568. {
  569. const size_t newIndex = pos + v;
  570. // Write face index
  571. face.mIndices[v] = newIndex;
  572. // Ogres vertex index to ref into the source buffers.
  573. const size_t ogreVertexIndex = ogreFace.mIndices[v];
  574. src->AddVertexMapping(ogreVertexIndex, newIndex);
  575. // Position
  576. positions->Seek((vWidthPosition * ogreVertexIndex) + positionsElement->offset, aiOrigin_SET);
  577. positions->Read(&dest->mVertices[newIndex], sizePosition, 1);
  578. // Normal
  579. if (normals)
  580. {
  581. normals->Seek((vWidthNormal * ogreVertexIndex) + normalsElement->offset, aiOrigin_SET);
  582. normals->Read(&dest->mNormals[newIndex], sizeNormal, 1);
  583. }
  584. // UV0
  585. if (uv1 && uv1Dest)
  586. {
  587. uv1->Seek((vWidthUv1 * ogreVertexIndex) + uv1Element->offset, aiOrigin_SET);
  588. uv1->Read(&uv1Dest[newIndex], sizeUv1, 1);
  589. uv1Dest[newIndex].y = (uv1Dest[newIndex].y * -1) + 1; // Flip UV from Ogre to Assimp form
  590. }
  591. // UV1
  592. if (uv2 && uv2Dest)
  593. {
  594. uv2->Seek((vWidthUv2 * ogreVertexIndex) + uv2Element->offset, aiOrigin_SET);
  595. uv2->Read(&uv2Dest[newIndex], sizeUv2, 1);
  596. uv2Dest[newIndex].y = (uv2Dest[newIndex].y * -1) + 1; // Flip UV from Ogre to Assimp form
  597. }
  598. }
  599. }
  600. // Bones and bone weights
  601. if (parent->skeleton && boneAssignments)
  602. {
  603. AssimpVertexBoneWeightList weights = src->AssimpBoneWeights(dest->mNumVertices);
  604. std::set<uint16_t> referencedBones = src->ReferencedBonesByWeights();
  605. dest->mNumBones = referencedBones.size();
  606. dest->mBones = new aiBone*[dest->mNumBones];
  607. size_t assimpBoneIndex = 0;
  608. for(std::set<uint16_t>::const_iterator rbIter=referencedBones.begin(), rbEnd=referencedBones.end(); rbIter != rbEnd; ++rbIter, ++assimpBoneIndex)
  609. {
  610. Bone *bone = parent->skeleton->BoneById((*rbIter));
  611. dest->mBones[assimpBoneIndex] = bone->ConvertToAssimpBone(parent->skeleton, weights[bone->id]);
  612. }
  613. }
  614. return dest;
  615. }
  616. // MeshXml
  617. MeshXml::MeshXml() :
  618. sharedVertexData(0),
  619. skeleton(0)
  620. {
  621. }
  622. MeshXml::~MeshXml()
  623. {
  624. Reset();
  625. }
  626. void MeshXml::Reset()
  627. {
  628. OGRE_SAFE_DELETE(skeleton)
  629. OGRE_SAFE_DELETE(sharedVertexData)
  630. for(size_t i=0, len=subMeshes.size(); i<len; ++i) {
  631. OGRE_SAFE_DELETE(subMeshes[i])
  632. }
  633. subMeshes.clear();
  634. }
  635. size_t MeshXml::NumSubMeshes() const
  636. {
  637. return subMeshes.size();
  638. }
  639. SubMeshXml *MeshXml::GetSubMesh(uint16_t index) const
  640. {
  641. for(size_t i=0; i<subMeshes.size(); ++i)
  642. if (subMeshes[i]->index == index)
  643. return subMeshes[i];
  644. return 0;
  645. }
  646. void MeshXml::ConvertToAssimpScene(aiScene* dest)
  647. {
  648. // Setup
  649. dest->mNumMeshes = NumSubMeshes();
  650. dest->mMeshes = new aiMesh*[dest->mNumMeshes];
  651. // Create root node
  652. dest->mRootNode = new aiNode();
  653. dest->mRootNode->mNumMeshes = dest->mNumMeshes;
  654. dest->mRootNode->mMeshes = new unsigned int[dest->mRootNode->mNumMeshes];
  655. // Export meshes
  656. for(size_t i=0; i<dest->mNumMeshes; ++i)
  657. {
  658. dest->mMeshes[i] = subMeshes[i]->ConvertToAssimpMesh(this);
  659. dest->mRootNode->mMeshes[i] = i;
  660. }
  661. // Export skeleton
  662. if (skeleton)
  663. {
  664. // Bones
  665. if (!skeleton->bones.empty())
  666. {
  667. BoneList rootBones = skeleton->RootBones();
  668. dest->mRootNode->mNumChildren = rootBones.size();
  669. dest->mRootNode->mChildren = new aiNode*[dest->mRootNode->mNumChildren];
  670. for(size_t i=0, len=rootBones.size(); i<len; ++i)
  671. {
  672. dest->mRootNode->mChildren[i] = rootBones[i]->ConvertToAssimpNode(skeleton, dest->mRootNode);
  673. }
  674. }
  675. // Animations
  676. if (!skeleton->animations.empty())
  677. {
  678. dest->mNumAnimations = skeleton->animations.size();
  679. dest->mAnimations = new aiAnimation*[dest->mNumAnimations];
  680. for(size_t i=0, len=skeleton->animations.size(); i<len; ++i)
  681. {
  682. dest->mAnimations[i] = skeleton->animations[i]->ConvertToAssimpAnimation();
  683. }
  684. }
  685. }
  686. }
  687. // SubMeshXml
  688. SubMeshXml::SubMeshXml() :
  689. vertexData(0),
  690. indexData(new IndexDataXml())
  691. {
  692. }
  693. SubMeshXml::~SubMeshXml()
  694. {
  695. Reset();
  696. }
  697. void SubMeshXml::Reset()
  698. {
  699. OGRE_SAFE_DELETE(indexData)
  700. OGRE_SAFE_DELETE(vertexData)
  701. }
  702. aiMesh *SubMeshXml::ConvertToAssimpMesh(MeshXml *parent)
  703. {
  704. aiMesh *dest = new aiMesh();
  705. dest->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  706. if (!name.empty())
  707. dest->mName = name;
  708. // Material index
  709. if (materialIndex != -1)
  710. dest->mMaterialIndex = materialIndex;
  711. // Faces
  712. dest->mNumFaces = indexData->faceCount;
  713. dest->mFaces = new aiFace[dest->mNumFaces];
  714. // Assimp required unique vertices, we need to convert from Ogres shared indexing.
  715. size_t uniqueVertexCount = dest->mNumFaces * 3;
  716. dest->mNumVertices = uniqueVertexCount;
  717. dest->mVertices = new aiVector3D[dest->mNumVertices];
  718. VertexDataXml *src = (!usesSharedVertexData ? vertexData : parent->sharedVertexData);
  719. bool boneAssignments = src->HasBoneAssignments();
  720. bool normals = src->HasNormals();
  721. size_t uvs = src->NumUvs();
  722. // Prepare normals
  723. if (normals)
  724. dest->mNormals = new aiVector3D[dest->mNumVertices];
  725. // Prepare UVs
  726. for(size_t uvi=0; uvi<uvs; ++uvi)
  727. {
  728. dest->mNumUVComponents[uvi] = 2;
  729. dest->mTextureCoords[uvi] = new aiVector3D[dest->mNumVertices];
  730. }
  731. for (size_t fi=0; fi<dest->mNumFaces; ++fi)
  732. {
  733. // Source Ogre face
  734. aiFace &ogreFace = indexData->faces[fi];
  735. // Destination Assimp face
  736. aiFace &face = dest->mFaces[fi];
  737. face.mNumIndices = 3;
  738. face.mIndices = new unsigned int[3];
  739. const size_t pos = fi * 3;
  740. for (size_t v=0; v<3; ++v)
  741. {
  742. const size_t newIndex = pos + v;
  743. // Write face index
  744. face.mIndices[v] = newIndex;
  745. // Ogres vertex index to ref into the source buffers.
  746. const size_t ogreVertexIndex = ogreFace.mIndices[v];
  747. src->AddVertexMapping(ogreVertexIndex, newIndex);
  748. // Position
  749. dest->mVertices[newIndex] = src->positions[ogreVertexIndex];
  750. // Normal
  751. if (normals)
  752. dest->mNormals[newIndex] = src->normals[ogreVertexIndex];
  753. // UVs
  754. for(size_t uvi=0; uvi<uvs; ++uvi)
  755. {
  756. aiVector3D *uvDest = dest->mTextureCoords[uvi];
  757. std::vector<aiVector3D> &uvSrc = src->uvs[uvi];
  758. uvDest[newIndex] = uvSrc[ogreVertexIndex];
  759. }
  760. }
  761. }
  762. // Bones and bone weights
  763. if (parent->skeleton && boneAssignments)
  764. {
  765. AssimpVertexBoneWeightList weights = src->AssimpBoneWeights(dest->mNumVertices);
  766. std::set<uint16_t> referencedBones = src->ReferencedBonesByWeights();
  767. dest->mNumBones = referencedBones.size();
  768. dest->mBones = new aiBone*[dest->mNumBones];
  769. size_t assimpBoneIndex = 0;
  770. for(std::set<uint16_t>::const_iterator rbIter=referencedBones.begin(), rbEnd=referencedBones.end(); rbIter != rbEnd; ++rbIter, ++assimpBoneIndex)
  771. {
  772. Bone *bone = parent->skeleton->BoneById((*rbIter));
  773. dest->mBones[assimpBoneIndex] = bone->ConvertToAssimpBone(parent->skeleton, weights[bone->id]);
  774. }
  775. }
  776. return dest;
  777. }
  778. // Animation
  779. Animation::Animation(Skeleton *parent) :
  780. parentSkeleton(parent),
  781. parentMesh(0),
  782. length(0.0f),
  783. baseTime(-1.0f)
  784. {
  785. }
  786. Animation::Animation(Mesh *parent) :
  787. parentMesh(parent),
  788. parentSkeleton(0),
  789. length(0.0f),
  790. baseTime(-1.0f)
  791. {
  792. }
  793. VertexData *Animation::AssociatedVertexData(VertexAnimationTrack *track) const
  794. {
  795. if (!parentMesh)
  796. return 0;
  797. bool sharedGeom = (track->target == 0);
  798. if (sharedGeom)
  799. return parentMesh->sharedVertexData;
  800. else
  801. return parentMesh->GetSubMesh(track->target-1)->vertexData;
  802. }
  803. aiAnimation *Animation::ConvertToAssimpAnimation()
  804. {
  805. aiAnimation *anim = new aiAnimation();
  806. anim->mName = name;
  807. anim->mDuration = static_cast<double>(length);
  808. anim->mTicksPerSecond = 1.0;
  809. // Tracks
  810. if (!tracks.empty())
  811. {
  812. anim->mNumChannels = tracks.size();
  813. anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  814. for(size_t i=0, len=tracks.size(); i<len; ++i)
  815. {
  816. anim->mChannels[i] = tracks[i].ConvertToAssimpAnimationNode(parentSkeleton);
  817. }
  818. }
  819. return anim;
  820. }
  821. // Skeleton
  822. Skeleton::Skeleton() :
  823. blendMode(ANIMBLEND_AVERAGE)
  824. {
  825. }
  826. Skeleton::~Skeleton()
  827. {
  828. Reset();
  829. }
  830. void Skeleton::Reset()
  831. {
  832. for(size_t i=0, len=bones.size(); i<len; ++i) {
  833. OGRE_SAFE_DELETE(bones[i])
  834. }
  835. bones.clear();
  836. for(size_t i=0, len=animations.size(); i<len; ++i) {
  837. OGRE_SAFE_DELETE(animations[i])
  838. }
  839. animations.clear();
  840. }
  841. BoneList Skeleton::RootBones() const
  842. {
  843. BoneList rootBones;
  844. for(BoneList::const_iterator iter = bones.begin(); iter != bones.end(); ++iter)
  845. {
  846. if (!(*iter)->IsParented())
  847. rootBones.push_back((*iter));
  848. }
  849. return rootBones;
  850. }
  851. size_t Skeleton::NumRootBones() const
  852. {
  853. size_t num = 0;
  854. for(BoneList::const_iterator iter = bones.begin(); iter != bones.end(); ++iter)
  855. {
  856. if (!(*iter)->IsParented())
  857. num++;
  858. }
  859. return num;
  860. }
  861. Bone *Skeleton::BoneByName(const std::string &name) const
  862. {
  863. for(BoneList::const_iterator iter = bones.begin(); iter != bones.end(); ++iter)
  864. {
  865. if ((*iter)->name == name)
  866. return (*iter);
  867. }
  868. return 0;
  869. }
  870. Bone *Skeleton::BoneById(uint16_t id) const
  871. {
  872. for(BoneList::const_iterator iter = bones.begin(); iter != bones.end(); ++iter)
  873. {
  874. if ((*iter)->id == id)
  875. return (*iter);
  876. }
  877. return 0;
  878. }
  879. // Bone
  880. Bone::Bone() :
  881. id(0),
  882. parent(0),
  883. parentId(-1),
  884. scale(1.0f, 1.0f, 1.0f)
  885. {
  886. }
  887. bool Bone::IsParented() const
  888. {
  889. return (parentId != -1 && parent != 0);
  890. }
  891. uint16_t Bone::ParentId() const
  892. {
  893. return static_cast<uint16_t>(parentId);
  894. }
  895. void Bone::AddChild(Bone *bone)
  896. {
  897. if (!bone)
  898. return;
  899. if (bone->IsParented())
  900. throw DeadlyImportError("Attaching child Bone that is already parented: " + bone->name);
  901. bone->parent = this;
  902. bone->parentId = id;
  903. children.push_back(bone->id);
  904. }
  905. void Bone::CalculateWorldMatrixAndDefaultPose(Skeleton *skeleton)
  906. {
  907. if (!IsParented())
  908. worldMatrix = aiMatrix4x4(scale, rotation, position).Inverse();
  909. else
  910. worldMatrix = aiMatrix4x4(scale, rotation, position).Inverse() * parent->worldMatrix;
  911. defaultPose = aiMatrix4x4(scale, rotation, position);
  912. // Recursively for all children now that the parent matrix has been calculated.
  913. for (size_t i=0, len=children.size(); i<len; ++i)
  914. {
  915. Bone *child = skeleton->BoneById(children[i]);
  916. if (!child) {
  917. throw DeadlyImportError(Formatter::format() << "CalculateWorldMatrixAndDefaultPose: Failed to find child bone " << children[i] << " for parent " << id << " " << name);
  918. }
  919. child->CalculateWorldMatrixAndDefaultPose(skeleton);
  920. }
  921. }
  922. aiNode *Bone::ConvertToAssimpNode(Skeleton *skeleton, aiNode *parentNode)
  923. {
  924. // Bone node
  925. aiNode* node = new aiNode(name);
  926. node->mParent = parentNode;
  927. node->mTransformation = defaultPose;
  928. // Children
  929. if (!children.empty())
  930. {
  931. node->mNumChildren = children.size();
  932. node->mChildren = new aiNode*[node->mNumChildren];
  933. for(size_t i=0, len=children.size(); i<len; ++i)
  934. {
  935. Bone *child = skeleton->BoneById(children[i]);
  936. if (!child) {
  937. throw DeadlyImportError(Formatter::format() << "ConvertToAssimpNode: Failed to find child bone " << children[i] << " for parent " << id << " " << name);
  938. }
  939. node->mChildren[i] = child->ConvertToAssimpNode(skeleton, node);
  940. }
  941. }
  942. return node;
  943. }
  944. aiBone *Bone::ConvertToAssimpBone(Skeleton *parent, const std::vector<aiVertexWeight> &boneWeights)
  945. {
  946. aiBone *bone = new aiBone();
  947. bone->mName = name;
  948. bone->mOffsetMatrix = worldMatrix;
  949. if (!boneWeights.empty())
  950. {
  951. bone->mNumWeights = boneWeights.size();
  952. bone->mWeights = new aiVertexWeight[boneWeights.size()];
  953. memcpy(bone->mWeights, &boneWeights[0], boneWeights.size() * sizeof(aiVertexWeight));
  954. }
  955. return bone;
  956. }
  957. // VertexAnimationTrack
  958. VertexAnimationTrack::VertexAnimationTrack() :
  959. target(0),
  960. type(VAT_NONE)
  961. {
  962. }
  963. aiNodeAnim *VertexAnimationTrack::ConvertToAssimpAnimationNode(Skeleton *skeleton)
  964. {
  965. if (boneName.empty() || type != VAT_TRANSFORM) {
  966. throw DeadlyImportError("VertexAnimationTrack::ConvertToAssimpAnimationNode: Cannot convert track that has no target bone name or is not type of VAT_TRANSFORM");
  967. }
  968. aiNodeAnim *nodeAnim = new aiNodeAnim();
  969. nodeAnim->mNodeName = boneName;
  970. Bone *bone = skeleton->BoneByName(boneName);
  971. if (!bone) {
  972. throw DeadlyImportError("VertexAnimationTrack::ConvertToAssimpAnimationNode: Failed to find bone " + boneName + " from parent Skeleton");
  973. }
  974. // Keyframes
  975. size_t numKeyframes = transformKeyFrames.size();
  976. nodeAnim->mPositionKeys = new aiVectorKey[numKeyframes];
  977. nodeAnim->mRotationKeys = new aiQuatKey[numKeyframes];
  978. nodeAnim->mScalingKeys = new aiVectorKey[numKeyframes];
  979. nodeAnim->mNumPositionKeys = numKeyframes;
  980. nodeAnim->mNumRotationKeys = numKeyframes;
  981. nodeAnim->mNumScalingKeys = numKeyframes;
  982. for(size_t kfi=0; kfi<numKeyframes; ++kfi)
  983. {
  984. TransformKeyFrame &kfSource = transformKeyFrames[kfi];
  985. // Calculate the complete transformation from world space to bone space
  986. aiVector3D pos; aiQuaternion rot; aiVector3D scale;
  987. aiMatrix4x4 finalTransform = bone->defaultPose * kfSource.Transform();
  988. finalTransform.Decompose(scale, rot, pos);
  989. double t = static_cast<double>(kfSource.timePos);
  990. nodeAnim->mPositionKeys[kfi].mTime = t;
  991. nodeAnim->mRotationKeys[kfi].mTime = t;
  992. nodeAnim->mScalingKeys[kfi].mTime = t;
  993. nodeAnim->mPositionKeys[kfi].mValue = pos;
  994. nodeAnim->mRotationKeys[kfi].mValue = rot;
  995. nodeAnim->mScalingKeys[kfi].mValue = scale;
  996. }
  997. return nodeAnim;
  998. }
  999. // TransformKeyFrame
  1000. TransformKeyFrame::TransformKeyFrame() :
  1001. timePos(0.0f),
  1002. scale(1.0f, 1.0f, 1.0f)
  1003. {
  1004. }
  1005. aiMatrix4x4 TransformKeyFrame::Transform()
  1006. {
  1007. return aiMatrix4x4(scale, rotation, position);
  1008. }
  1009. } // Ogre
  1010. } // Assimp
  1011. #endif // ASSIMP_BUILD_NO_OGRE_IMPORTER