assimpAppMesh.cpp 12 KB

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