assimpAppMesh.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "ts/collada/colladaExtensions.h"
  24. #include "ts/assimp/assimpAppMesh.h"
  25. // assimp include files.
  26. #include <assimp/cimport.h>
  27. #include <assimp/scene.h>
  28. #include <assimp/postprocess.h>
  29. #include <assimp/types.h>
  30. bool AssimpAppMesh::fixedSizeEnabled = false;
  31. S32 AssimpAppMesh::fixedSize = 2;
  32. //------------------------------------------------------------------------------
  33. void AssimpAppMesh::computeBounds(Box3F& bounds)
  34. {
  35. bounds = Box3F::Invalid;
  36. if (isSkin())
  37. {
  38. // Compute bounds for skinned mesh
  39. Vector<MatrixF> boneTransforms;
  40. boneTransforms.setSize(nodeIndex.size());
  41. // Calculate bone transformations
  42. for (S32 iBone = 0; iBone < boneTransforms.size(); iBone++) {
  43. MatrixF nodeMat = bones[iBone]->getNodeTransform(TSShapeLoader::DefaultTime);
  44. TSShapeLoader::zapScale(nodeMat); // Remove scaling to ensure uniform transformation
  45. boneTransforms[iBone].mul(nodeMat, initialTransforms[iBone]);
  46. }
  47. // Transform vertices using weighted bone transformations
  48. Vector<Point3F> transformedVerts;
  49. transformedVerts.setSize(initialVerts.size());
  50. transformedVerts.fill(Point3F::Zero);
  51. for (S32 iWeight = 0; iWeight < vertexIndex.size(); iWeight++) {
  52. const S32 vertIndex = vertexIndex[iWeight];
  53. const MatrixF& deltaTransform = boneTransforms[boneIndex[iWeight]];
  54. Point3F weightedVert;
  55. deltaTransform.mulP(initialVerts[vertIndex], &weightedVert);
  56. weightedVert *= weight[iWeight];
  57. transformedVerts[vertIndex] += weightedVert;
  58. }
  59. // Extend bounds using the transformed vertices
  60. for (const auto& vert : transformedVerts) {
  61. bounds.extend(vert);
  62. }
  63. }
  64. else
  65. {
  66. MatrixF transform = getMeshTransform(TSShapeLoader::DefaultTime);
  67. TSShapeLoader::zapScale(transform);
  68. for (S32 iVert = 0; iVert < points.size(); iVert++)
  69. {
  70. Point3F p;
  71. transform.mulP(points[iVert], &p);
  72. bounds.extend(p);
  73. }
  74. }
  75. }
  76. TSMesh* AssimpAppMesh::constructTSMesh()
  77. {
  78. TSMesh* tsmesh;
  79. if (isSkin())
  80. {
  81. TSSkinMesh* tsskin = new TSSkinMesh();
  82. tsmesh = tsskin;
  83. // Copy skin elements
  84. tsskin->weight = weight;
  85. tsskin->boneIndex = boneIndex;
  86. tsskin->vertexIndex = vertexIndex;
  87. tsskin->batchData.nodeIndex = nodeIndex;
  88. tsskin->batchData.initialTransforms = initialTransforms;
  89. tsskin->batchData.initialVerts = initialVerts;
  90. tsskin->batchData.initialNorms = initialNorms;
  91. }
  92. else
  93. {
  94. tsmesh = new TSMesh();
  95. }
  96. // Copy mesh elements
  97. tsmesh->mVerts = points;
  98. tsmesh->mNorms = normals;
  99. tsmesh->mTverts = uvs;
  100. tsmesh->mPrimitives = primitives;
  101. tsmesh->mIndices = indices;
  102. tsmesh->mColors = colors;
  103. tsmesh->mTverts2 = uv2s;
  104. // Finish initializing the shape
  105. computeBounds(tsmesh->mBounds);
  106. tsmesh->setFlags(flags);
  107. tsmesh->updateMeshFlags();
  108. //tsmesh->computeBounds();
  109. tsmesh->numFrames = numFrames;
  110. tsmesh->numMatFrames = numMatFrames;
  111. tsmesh->vertsPerFrame = vertsPerFrame;
  112. tsmesh->createTangents(tsmesh->mVerts, tsmesh->mNorms);
  113. tsmesh->mEncodedNorms.set(NULL, 0);
  114. return tsmesh;
  115. }
  116. AssimpAppMesh::AssimpAppMesh(const struct aiMesh* mesh, AssimpAppNode* node)
  117. : mMeshData(mesh), appNode(node)
  118. {
  119. Con::printf("[ASSIMP] Mesh Created: %s for Node: %s", getName(), node->getName());
  120. // See if it's a skinned mesh
  121. mIsSkinMesh = false;
  122. for (U32 b = 0; b < mesh->mNumBones; b++)
  123. if (mMeshData->mBones[b]->mNumWeights > 0)
  124. {
  125. mIsSkinMesh = true;
  126. break;
  127. }
  128. }
  129. const char* AssimpAppMesh::getName(bool allowFixed)
  130. {
  131. // Some exporters add a 'PIVOT' or unnamed node between the mesh and the
  132. // actual object node. Detect this and return the object node name instead
  133. // of the pivot node.
  134. const char* nodeName = appNode->getName();
  135. if ( dStrEqual(nodeName, "null") || dStrEndsWith(nodeName, "PIVOT") )
  136. nodeName = appNode->getParentName();
  137. // If all geometry is being fixed to the same size, append the size
  138. // to the name
  139. return allowFixed && fixedSizeEnabled ? avar("%s %d", nodeName, fixedSize) : nodeName;
  140. }
  141. MatrixF AssimpAppMesh::getMeshTransform(F32 time)
  142. {
  143. return appNode->getNodeTransform(time);
  144. }
  145. void AssimpAppMesh::lockMesh(F32 t, const MatrixF& objOffset)
  146. {
  147. // After this function, the following are expected to be populated:
  148. // points, normals, uvs, primitives, indices
  149. // There is also colors and uv2s but those don't seem to be required.
  150. points.reserve(mMeshData->mNumVertices);
  151. uvs.reserve(mMeshData->mNumVertices);
  152. normals.reserve(mMeshData->mNumVertices);
  153. bool flipNormals = ColladaUtils::getOptions().invertNormals;
  154. bool noUVFound = false;
  155. for (U32 i = 0; i<mMeshData->mNumVertices; i++)
  156. {
  157. // Points and Normals
  158. aiVector3D pt = mMeshData->mVertices[i];
  159. aiVector3D nrm;
  160. if (mMeshData->HasNormals())
  161. nrm = mMeshData->mNormals[i];
  162. else
  163. nrm.Set(0, 0, 0);
  164. Point3F tmpVert;
  165. Point3F tmpNormal;
  166. tmpVert = Point3F(pt.x, pt.y, pt.z);
  167. tmpNormal = Point3F(nrm.x, nrm.y, nrm.z);
  168. if (flipNormals)
  169. tmpNormal *= -1.0f;
  170. objOffset.mulP(tmpVert);
  171. points.push_back(tmpVert);
  172. if (mMeshData->HasTextureCoords(0))
  173. {
  174. uvs.push_back(Point2F(mMeshData->mTextureCoords[0][i].x, mMeshData->mTextureCoords[0][i].y));
  175. }
  176. else
  177. {
  178. // I don't know if there's any solution to this issue.
  179. // If it's not mapped, it's not mapped.
  180. noUVFound = true;
  181. uvs.push_back(Point2F(1, 1));
  182. }
  183. // UV2s
  184. if (mMeshData->HasTextureCoords(1))
  185. {
  186. uv2s.push_back(Point2F(mMeshData->mTextureCoords[1][i].x, mMeshData->mTextureCoords[1][i].y));
  187. }
  188. // Vertex Colors
  189. if (mMeshData->HasVertexColors(0))
  190. {
  191. LinearColorF vColor(mMeshData->mColors[0][i].r,
  192. mMeshData->mColors[0][i].g,
  193. mMeshData->mColors[0][i].b,
  194. mMeshData->mColors[0][i].a);
  195. colors.push_back(vColor.toColorI());
  196. }
  197. //uvs.push_back(mModel->mVerts[i].texcoord);
  198. normals.push_back(tmpNormal);
  199. //edgeVerts.push_back(mModel->mVerts[i].edge);
  200. }
  201. U32 numFaces = mMeshData->mNumFaces;
  202. //primitives.reserve(numFaces);
  203. //Fetch the number of indices
  204. U32 indicesCount = 0;
  205. for (U32 i = 0; i < numFaces; i++)
  206. {
  207. indicesCount += mMeshData->mFaces[i].mNumIndices;
  208. }
  209. indices.reserve(indicesCount);
  210. // Create TSMesh primitive
  211. primitives.increment();
  212. TSDrawPrimitive& primitive = primitives.last();
  213. primitive.start = 0;
  214. primitive.matIndex = (TSDrawPrimitive::Triangles | TSDrawPrimitive::Indexed) | (S32)mMeshData->mMaterialIndex;
  215. primitive.numElements = indicesCount;
  216. for ( U32 n = 0; n < mMeshData->mNumFaces; ++n)
  217. {
  218. const struct aiFace* face = &mMeshData->mFaces[n];
  219. if ( face->mNumIndices == 3 )
  220. {
  221. U32 indexCount = face->mNumIndices;
  222. for (U32 ind = 0; ind < indexCount; ind++)
  223. {
  224. U32 index = face->mIndices[ind];
  225. indices.push_back(index);
  226. }
  227. }
  228. else
  229. {
  230. Con::printf("[ASSIMP] Non-Triangle Face Found. Indices: %d", face->mNumIndices);
  231. }
  232. }
  233. U32 boneCount = mMeshData->mNumBones;
  234. bones.setSize(boneCount);
  235. // Count the total number of weights for all of the bones.
  236. U32 totalWeights = 0;
  237. U32 nonZeroWeights = 0;
  238. for (U32 b = 0; b < boneCount; b++)
  239. totalWeights += mMeshData->mBones[b]->mNumWeights;
  240. // Assimp gives weights sorted by bone index. We need them in vertex order.
  241. Vector<F32> tmpWeight;
  242. Vector<S32> tmpBoneIndex;
  243. Vector<S32> tmpVertexIndex;
  244. tmpWeight.setSize(totalWeights);
  245. tmpBoneIndex.setSize(totalWeights);
  246. tmpVertexIndex.setSize(totalWeights);
  247. // Count the total number of weights for all of the bones.
  248. Map<String, aiNode*> boneLookup;
  249. for (U32 b = 0; b < boneCount; b++) {
  250. boneLookup[mMeshData->mBones[b]->mName.C_Str()] =
  251. AssimpAppNode::findChildNodeByName(mMeshData->mBones[b]->mName.C_Str(), appNode->mScene->mRootNode);
  252. }
  253. for (U32 b = 0; b < boneCount; b++)
  254. {
  255. const aiBone* bone = mMeshData->mBones[b];
  256. aiNode* nodePtr = boneLookup[bone->mName.C_Str()];
  257. bones[b] = nodePtr ? new AssimpAppNode(appNode->mScene, nodePtr) : new AssimpAppNode(appNode->mScene, appNode->mNode);
  258. MatrixF boneTransform;
  259. AssimpAppNode::assimpToTorqueMat(mMeshData->mBones[b]->mOffsetMatrix, boneTransform);
  260. Point3F boneScale = boneTransform.getScale();
  261. Point3F bonePos = boneTransform.getPosition();
  262. if (boneScale != Point3F::One && ColladaUtils::getOptions().ignoreNodeScale)
  263. {
  264. Point3F scaleMult = Point3F::One / boneScale;
  265. boneTransform.scale(scaleMult);
  266. bonePos /= scaleMult;
  267. }
  268. bonePos *= ColladaUtils::getOptions().unit * ColladaUtils::getOptions().formatScaleFactor;
  269. boneTransform.setPosition(bonePos);
  270. initialTransforms.push_back(boneTransform);
  271. //Weights
  272. U32 numWeights = mMeshData->mBones[b]->mNumWeights;
  273. for (U32 w = 0; w < numWeights; ++w)
  274. {
  275. aiVertexWeight* aiWeight = &mMeshData->mBones[b]->mWeights[w];
  276. if (aiWeight->mWeight > 0.0f)
  277. {
  278. tmpWeight[nonZeroWeights] = aiWeight->mWeight;
  279. tmpVertexIndex[nonZeroWeights] = aiWeight->mVertexId;
  280. tmpBoneIndex[nonZeroWeights] = b;
  281. nonZeroWeights++;
  282. }
  283. }
  284. }
  285. weight.setSize(nonZeroWeights);
  286. vertexIndex.setSize(nonZeroWeights);
  287. boneIndex.setSize(nonZeroWeights);
  288. // Copy the weights to our vectors in vertex order and
  289. // normalize vertex weights (force weights for each vert to sum to 1)
  290. U32 nextWeight = 0;
  291. for (U32 i = 0; i < mMeshData->mNumVertices; ++i)
  292. {
  293. U32 vertStart = nextWeight;
  294. F32 invTotalWeight = 0;
  295. for (U32 ind = 0; ind < nonZeroWeights; ++ind)
  296. {
  297. if (tmpVertexIndex[ind] == i)
  298. {
  299. weight[nextWeight] = tmpWeight[ind];
  300. invTotalWeight += tmpWeight[ind];
  301. vertexIndex[nextWeight] = tmpVertexIndex[ind];
  302. boneIndex[nextWeight] = tmpBoneIndex[ind];
  303. nextWeight++;
  304. }
  305. }
  306. // Now normalize the vertex weights
  307. if (invTotalWeight > 0.0)
  308. {
  309. invTotalWeight = 1.0f / invTotalWeight;
  310. for (U32 ind = vertStart; ind < nextWeight; ++ind)
  311. weight[ind] *= invTotalWeight;
  312. }
  313. }
  314. if ( noUVFound )
  315. Con::warnf("[ASSIMP] No UV Data for mesh.");
  316. }
  317. void AssimpAppMesh::lookupSkinData()
  318. { // This function is intentionally left blank. The skin data - bones, weights and indexes are
  319. // processed in lockMesh() with the rest of the mesh data.
  320. }
  321. F32 AssimpAppMesh::getVisValue(F32 t)
  322. {
  323. return 1.0f;
  324. }