tsMeshFit.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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 "console/consoleTypes.h"
  24. #include "core/resourceManager.h"
  25. #include "ts/tsShapeConstruct.h"
  26. #include "console/engineAPI.h"
  27. #define ENABLE_VHACD_IMPLEMENTATION 1
  28. #define VHACD_DISABLE_THREADING 0
  29. #include "ts/vhacd/VHACD.h"
  30. #include <FloatMath.h>
  31. //-----------------------------------------------------------------------------
  32. static const Point3F sFacePlanes[] = {
  33. Point3F( -1.0f, 0.0f, 0.0f ),
  34. Point3F( 1.0f, 0.0f, 0.0f ),
  35. Point3F( 0.0f, -1.0f, 0.0f ),
  36. Point3F( 0.0f, 1.0f, 0.0f ),
  37. Point3F( 0.0f, 0.0f, -1.0f ),
  38. Point3F( 0.0f, 0.0f, 1.0f ),
  39. };
  40. static const Point3F sXEdgePlanes[] = {
  41. Point3F( 0.0f, -0.7071f, -0.7071f ),
  42. Point3F( 0.0f, -0.7071f, 0.7071f ),
  43. Point3F( 0.0f, 0.7071f, -0.7071f ),
  44. Point3F( 0.0f, 0.7071f, 0.7071f ),
  45. };
  46. static const Point3F sYEdgePlanes[] = {
  47. Point3F( -0.7071f, 0.0f, -0.7071f ),
  48. Point3F( -0.7071f, 0.0f, 0.7071f ),
  49. Point3F( 0.7071f, 0.0f, -0.7071f ),
  50. Point3F( 0.7071f, 0.0f, 0.7071f ),
  51. };
  52. static const Point3F sZEdgePlanes[] = {
  53. Point3F( -0.7071f, -0.7071f, 0.0f ),
  54. Point3F( -0.7071f, 0.7071f, 0.0f ),
  55. Point3F( 0.7071f, -0.7071f, 0.0f ),
  56. Point3F( 0.7071f, 0.7071f, 0.0f ),
  57. };
  58. static const Point3F sCornerPlanes[] = {
  59. Point3F( -0.5774f, -0.5774f, -0.5774f ),
  60. Point3F( -0.5774f, -0.5774f, 0.5774f ),
  61. Point3F( -0.5774f, 0.5774f, -0.5774f ),
  62. Point3F( -0.5774f, 0.5774f, 0.5774f ),
  63. Point3F( 0.5774f, -0.5774f, -0.5774f ),
  64. Point3F( 0.5774f, -0.5774f, 0.5774f ),
  65. Point3F( 0.5774f, 0.5774f, -0.5774f ),
  66. Point3F( 0.5774f, 0.5774f, 0.5774f ),
  67. };
  68. //-----------------------------------------------------------------------------
  69. /** A helper class for fitting primitives (Box, Sphere, Capsule) to a triangulated mesh */
  70. struct PrimFit
  71. {
  72. MatrixF mBoxTransform;
  73. Point3F mBoxSides;
  74. Point3F mSphereCenter;
  75. F32 mSphereRadius;
  76. MatrixF mCapTransform;
  77. F32 mCapRadius;
  78. F32 mCapHeight;
  79. public:
  80. PrimFit() :
  81. mBoxTransform(true), mBoxSides(1,1,1),
  82. mSphereCenter(0,0,0), mSphereRadius(1),
  83. mCapTransform(true), mCapRadius(1), mCapHeight(1)
  84. {
  85. }
  86. inline F32 getBoxVolume() const { return mBoxSides.x * mBoxSides.y * mBoxSides.z; }
  87. inline F32 getSphereVolume() const { return 4.0f / 3.0f * M_PI * mPow( mSphereRadius, 3 ); }
  88. inline F32 getCapsuleVolume() const { return 2 * M_PI * mPow( mCapRadius, 2 ) * (4.0f / 3.0f * mCapRadius + mCapHeight); }
  89. void fitBox( U32 vertCount, const F32* verts )
  90. {
  91. FLOAT_MATH::fm_computeBestFitOBB( vertCount, verts, sizeof(F32)*3, (F32*)mBoxSides, (F32*)mBoxTransform, false );
  92. mBoxTransform.transpose();
  93. }
  94. void fitSphere( U32 vertCount, const F32* verts )
  95. {
  96. mSphereRadius = FLOAT_MATH::fm_computeBestFitSphere( vertCount, verts, sizeof(F32)*3, (F32*)mSphereCenter );
  97. }
  98. void fitCapsule( U32 vertCount, const F32* verts )
  99. {
  100. FLOAT_MATH::fm_computeBestFitCapsule( vertCount, verts, sizeof(F32)*3, mCapRadius, mCapHeight, (F32*)mCapTransform );
  101. mCapTransform.transpose();
  102. }
  103. };
  104. class MeshFit
  105. {
  106. public:
  107. enum eMeshType
  108. {
  109. Box = 0,
  110. Sphere,
  111. Capsule,
  112. Hull,
  113. };
  114. struct Mesh
  115. {
  116. eMeshType type;
  117. MatrixF transform;
  118. TSMesh *tsmesh;
  119. };
  120. private:
  121. TSShape *mShape; ///!< Source geometry shape
  122. Vector<Point3F> mVerts; ///!< Source geometry verts (all meshes)
  123. Vector<U32> mIndices; ///!< Source geometry indices (triangle lists, all meshes)
  124. bool mIsReady; ///!< Flag indicating whether we are ready to fit/create meshes
  125. Vector<Mesh> mMeshes; ///!< Fitted meshes
  126. void addSourceMesh( const TSShape::Object& obj, const TSMesh* mesh );
  127. TSMesh* initMeshFromFile( const String& filename ) const;
  128. TSMesh* createTriMesh( F32* verts, S32 numVerts, U32* indices, S32 numTris ) const;
  129. F32 maxDot( const VectorF& v ) const;
  130. void fitK_DOP( const Vector<Point3F>& planes );
  131. public:
  132. MeshFit(TSShape* shape) : mShape(shape), mIsReady(false) { }
  133. void setReady() { mIsReady = true; }
  134. bool isReady() const { return mIsReady; }
  135. void initSourceGeometry( const String& target );
  136. S32 getMeshCount() const { return mMeshes.size(); }
  137. Mesh* getMesh( S32 index ) { return &(mMeshes[index]); }
  138. // Box
  139. void addBox( const Point3F& sides, const MatrixF& mat );
  140. void fitOBB();
  141. // Sphere
  142. void addSphere( F32 radius, const Point3F& center );
  143. void fitSphere();
  144. // Capsule
  145. void addCapsule( F32 radius, F32 height, const MatrixF& mat );
  146. void fitCapsule();
  147. // k-DOP
  148. void fit10_DOP_X();
  149. void fit10_DOP_Y();
  150. void fit10_DOP_Z();
  151. void fit18_DOP();
  152. void fit26_DOP();
  153. // Convex Hulls
  154. void fitConvexHulls( U32 depth, U32 fillType, F32 minPercentage, U32 maxHulls, U32 maxHullVerts,
  155. F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError );
  156. };
  157. void MeshFit::initSourceGeometry( const String& target )
  158. {
  159. mMeshes.clear();
  160. mVerts.clear();
  161. mIndices.clear();
  162. if ( target.equal( "bounds", String::NoCase ) )
  163. {
  164. // Add all geometry in the highest detail level
  165. S32 dl = 0;
  166. S32 ss = mShape->details[dl].subShapeNum;
  167. if ( ss < 0 )
  168. return;
  169. S32 od = mShape->details[dl].objectDetailNum;
  170. S32 start = mShape->subShapeFirstObject[ss];
  171. S32 end = start + mShape->subShapeNumObjects[ss];
  172. for ( S32 i = start; i < end; i++ )
  173. {
  174. const TSShape::Object &obj = mShape->objects[i];
  175. const TSMesh* mesh = ( od < obj.numMeshes ) ? mShape->meshes[obj.startMeshIndex + od] : NULL;
  176. if ( mesh )
  177. addSourceMesh( obj, mesh );
  178. }
  179. }
  180. else
  181. {
  182. // Add highest detail mesh from this object
  183. S32 objIndex = mShape->findObject( target );
  184. if ( objIndex == -1 )
  185. return;
  186. const TSShape::Object &obj = mShape->objects[objIndex];
  187. for ( S32 i = 0; i < obj.numMeshes; i++ )
  188. {
  189. const TSMesh* mesh = mShape->meshes[obj.startMeshIndex + i];
  190. if ( mesh )
  191. {
  192. addSourceMesh( obj, mesh );
  193. break;
  194. }
  195. }
  196. }
  197. mIsReady = ( !mVerts.empty() && !mIndices.empty() );
  198. }
  199. void MeshFit::addSourceMesh( const TSShape::Object& obj, const TSMesh* mesh )
  200. {
  201. // Add indices
  202. S32 indicesBase = mIndices.size();
  203. for ( S32 i = 0; i < mesh->mPrimitives.size(); i++ )
  204. {
  205. const TSDrawPrimitive& draw = mesh->mPrimitives[i];
  206. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  207. {
  208. mIndices.merge( &mesh->mIndices[draw.start], draw.numElements );
  209. }
  210. else
  211. {
  212. U32 idx0 = mesh->mIndices[draw.start + 0];
  213. U32 idx1;
  214. U32 idx2 = mesh->mIndices[draw.start + 1];
  215. U32 *nextIdx = &idx1;
  216. for ( S32 j = 2; j < draw.numElements; j++ )
  217. {
  218. *nextIdx = idx2;
  219. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  220. idx2 = mesh->mIndices[draw.start + j];
  221. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  222. continue;
  223. mIndices.push_back( idx0 );
  224. mIndices.push_back( idx1 );
  225. mIndices.push_back( idx2 );
  226. }
  227. }
  228. }
  229. // Offset indices for already added verts
  230. for ( S32 j = indicesBase; j < mIndices.size(); j++ )
  231. mIndices[j] += mVerts.size();
  232. // Add verts
  233. S32 count, stride;
  234. U8* pVert;
  235. if ( mesh->mVertexData.isReady() && mesh->mVerts.size() == 0 )
  236. {
  237. count = mesh->mVertexData.size();
  238. stride = mesh->mVertexData.vertSize();
  239. pVert = (U8*)mesh->mVertexData.address();
  240. }
  241. else
  242. {
  243. count = mesh->mVerts.size();
  244. stride = sizeof(Point3F);
  245. pVert = (U8*)mesh->mVerts.address();
  246. }
  247. MatrixF objMat;
  248. mShape->getNodeWorldTransform( obj.nodeIndex, &objMat );
  249. mVerts.reserve( mVerts.size() + count );
  250. for ( S32 j = 0; j < count; j++, pVert += stride )
  251. {
  252. mVerts.increment();
  253. objMat.mulP( *(Point3F*)pVert, &mVerts.last() );
  254. }
  255. }
  256. TSMesh* MeshFit::initMeshFromFile( const String& filename ) const
  257. {
  258. // Open the source shape file and make a copy of the mesh
  259. Resource<TSShape> hShape = ResourceManager::get().load(filename);
  260. if (!bool(hShape) || !((TSShape*)hShape)->meshes.size())
  261. {
  262. Con::errorf("TSShape::createMesh: Could not load source mesh from %s", filename.c_str());
  263. return NULL;
  264. }
  265. TSMesh* srcMesh = ((TSShape*)hShape)->meshes[0];
  266. return mShape->copyMesh( srcMesh );
  267. }
  268. TSMesh* MeshFit::createTriMesh( F32* verts, S32 numVerts, U32* indices, S32 numTris ) const
  269. {
  270. TSMesh* mesh = mShape->copyMesh( NULL );
  271. mesh->numFrames = 1;
  272. mesh->numMatFrames = 1;
  273. mesh->vertsPerFrame = numVerts;
  274. mesh->setFlags(0);
  275. mesh->mNumVerts = numVerts;
  276. mesh->mIndices.reserve( numTris * 3 );
  277. for ( S32 i = 0; i < numTris; i++ )
  278. {
  279. mesh->mIndices.push_back( indices[i*3 + 0] );
  280. mesh->mIndices.push_back( indices[i*3 + 2] );
  281. mesh->mIndices.push_back( indices[i*3 + 1] );
  282. }
  283. mesh->mVerts.set( verts, numVerts );
  284. // Compute mesh normals
  285. mesh->mNorms.setSize( mesh->mVerts.size() );
  286. for (S32 iNorm = 0; iNorm < mesh->mNorms.size(); iNorm++)
  287. mesh->mNorms[iNorm] = Point3F::Zero;
  288. // Sum triangle normals for each vertex
  289. for (S32 iInd = 0; iInd < mesh->mIndices.size(); iInd += 3)
  290. {
  291. // Compute the normal for this triangle
  292. S32 idx0 = mesh->mIndices[iInd + 0];
  293. S32 idx1 = mesh->mIndices[iInd + 1];
  294. S32 idx2 = mesh->mIndices[iInd + 2];
  295. const Point3F& v0 = mesh->mVerts[idx0];
  296. const Point3F& v1 = mesh->mVerts[idx1];
  297. const Point3F& v2 = mesh->mVerts[idx2];
  298. Point3F n;
  299. mCross(v2 - v0, v1 - v0, &n);
  300. n.normalize(); // remove this to use 'weighted' normals (large triangles will have more effect)
  301. mesh->mNorms[idx0] += n;
  302. mesh->mNorms[idx1] += n;
  303. mesh->mNorms[idx2] += n;
  304. }
  305. // Normalize the vertex normals (this takes care of averaging the triangle normals)
  306. for (S32 iNorm = 0; iNorm < mesh->mNorms.size(); iNorm++)
  307. mesh->mNorms[iNorm].normalize();
  308. // Set some dummy UVs
  309. mesh->mTverts.setSize( numVerts );
  310. for ( S32 j = 0; j < mesh->mTverts.size(); j++ )
  311. mesh->mTverts[j].set( 0, 0 );
  312. // Add a single triangle-list primitive
  313. mesh->mPrimitives.increment();
  314. mesh->mPrimitives.last().start = 0;
  315. mesh->mPrimitives.last().numElements = mesh->mIndices.size();
  316. mesh->mPrimitives.last().matIndex = TSDrawPrimitive::Triangles |
  317. TSDrawPrimitive::Indexed |
  318. TSDrawPrimitive::NoMaterial;
  319. mesh->createTangents( mesh->mVerts, mesh->mNorms);
  320. mesh->mEncodedNorms.set( NULL,0 );
  321. return mesh;
  322. }
  323. F32 MeshFit::maxDot( const VectorF& v ) const
  324. {
  325. F32 maxDot = -FLT_MAX;
  326. for ( S32 i = 0; i < mVerts.size(); i++ )
  327. maxDot = getMax( maxDot, mDot( v, mVerts[i] ) );
  328. return maxDot;
  329. }
  330. //---------------------------
  331. // Best-fit oriented bounding box
  332. void MeshFit::addBox( const Point3F& sides, const MatrixF& mat )
  333. {
  334. TSMesh* mesh = initMeshFromFile( TSShapeConstructor::getCubeShapePath() );
  335. if ( !mesh )
  336. return;
  337. if (mesh->mVerts.size() > 0)
  338. {
  339. for (S32 i = 0; i < mesh->mVerts.size(); i++)
  340. {
  341. Point3F v = mesh->mVerts[i];
  342. v.convolve(sides);
  343. mesh->mVerts[i] = v;
  344. }
  345. mesh->mVertexData.setReady(false);
  346. }
  347. else
  348. {
  349. for (S32 i = 0; i < mesh->mVertexData.size(); i++)
  350. {
  351. TSMesh::__TSMeshVertexBase &vdata = mesh->mVertexData.getBase(i);
  352. Point3F v = vdata.vert();
  353. v.convolve(sides);
  354. vdata.vert(v);
  355. }
  356. }
  357. mesh->computeBounds();
  358. mMeshes.increment();
  359. mMeshes.last().type = MeshFit::Box;
  360. mMeshes.last().transform = mat;
  361. mMeshes.last().tsmesh = mesh;
  362. }
  363. void MeshFit::fitOBB()
  364. {
  365. PrimFit primFitter;
  366. primFitter.fitBox( mVerts.size(), (F32*)mVerts.address() );
  367. addBox( primFitter.mBoxSides, primFitter.mBoxTransform );
  368. }
  369. //---------------------------
  370. // Best-fit sphere
  371. void MeshFit::addSphere( F32 radius, const Point3F& center )
  372. {
  373. TSMesh* mesh = initMeshFromFile( TSShapeConstructor::getSphereShapePath() );
  374. if ( !mesh )
  375. return;
  376. if (mesh->mVerts.size() > 0)
  377. {
  378. for (S32 i = 0; i < mesh->mVerts.size(); i++)
  379. {
  380. Point3F v = mesh->mVerts[i];
  381. mesh->mVerts[i] = v * radius;
  382. }
  383. mesh->mVertexData.setReady(false);
  384. }
  385. else
  386. {
  387. for (S32 i = 0; i < mesh->mVertexData.size(); i++)
  388. {
  389. TSMesh::__TSMeshVertexBase& vdata = mesh->mVertexData.getBase(i);
  390. Point3F v = vdata.vert();
  391. vdata.vert(v * radius);
  392. }
  393. }
  394. mesh->computeBounds();
  395. mMeshes.increment();
  396. MeshFit::Mesh& lastMesh = mMeshes.last();
  397. lastMesh.type = MeshFit::Sphere;
  398. lastMesh.transform.identity();
  399. lastMesh.transform.setPosition(center);
  400. lastMesh.tsmesh = mesh;
  401. }
  402. void MeshFit::fitSphere()
  403. {
  404. PrimFit primFitter;
  405. primFitter.fitSphere( mVerts.size(), (F32*)mVerts.address() );
  406. addSphere( primFitter.mSphereRadius, primFitter.mSphereCenter );
  407. }
  408. //---------------------------
  409. // Best-fit capsule
  410. void MeshFit::addCapsule( F32 radius, F32 height, const MatrixF& mat )
  411. {
  412. TSMesh* mesh = initMeshFromFile( TSShapeConstructor::getCapsuleShapePath() );
  413. if ( !mesh )
  414. return;
  415. // Translate and scale the mesh verts
  416. height = mMax( 0, height );
  417. F32 offset = ( height / ( 2 * radius ) ) - 0.5f;
  418. if (mesh->mVerts.size() > 0)
  419. {
  420. for (S32 i = 0; i < mesh->mVerts.size(); i++)
  421. {
  422. Point3F v = mesh->mVerts[i];
  423. v.y += ((v.y > 0) ? offset : -offset);
  424. mesh->mVerts[i] = v * radius;
  425. }
  426. mesh->mVertexData.setReady(false);
  427. }
  428. else
  429. {
  430. for (S32 i = 0; i < mesh->mVertexData.size(); i++)
  431. {
  432. TSMesh::__TSMeshVertexBase& vdata = mesh->mVertexData.getBase(i);
  433. Point3F v = vdata.vert();
  434. v.y += ((v.y > 0) ? offset : -offset);
  435. vdata.vert(v * radius);
  436. }
  437. }
  438. mesh->computeBounds();
  439. mMeshes.increment();
  440. mMeshes.last().type = MeshFit::Capsule;
  441. mMeshes.last().transform = mat;
  442. mMeshes.last().tsmesh = mesh;
  443. }
  444. void MeshFit::fitCapsule()
  445. {
  446. PrimFit primFitter;
  447. primFitter.fitCapsule( mVerts.size(), (F32*)mVerts.address() );
  448. addCapsule( primFitter.mCapRadius, primFitter.mCapHeight, primFitter.mCapTransform );
  449. }
  450. //---------------------------
  451. // Best-fit k-discrete-oriented-polytope (where k is the number of axis-aligned planes)
  452. // All faces + 4 edges (aligned to X axis) of the unit cube
  453. void MeshFit::fit10_DOP_X()
  454. {
  455. Vector<Point3F> planes;
  456. planes.setSize( 10 );
  457. dCopyArray( planes.address(), sFacePlanes, 6 );
  458. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  459. fitK_DOP( planes );
  460. }
  461. // All faces + 4 edges (aligned to Y axis) of the unit cube
  462. void MeshFit::fit10_DOP_Y()
  463. {
  464. Vector<Point3F> planes;
  465. planes.setSize( 10 );
  466. dCopyArray( planes.address(), sFacePlanes, 6 );
  467. dCopyArray( planes.address()+6, sYEdgePlanes, 4 );
  468. fitK_DOP( planes );
  469. }
  470. // All faces + 4 edges (aligned to Z axis) of the unit cube
  471. void MeshFit::fit10_DOP_Z()
  472. {
  473. Vector<Point3F> planes;
  474. planes.setSize( 10 );
  475. dCopyArray( planes.address(), sFacePlanes, 6 );
  476. dCopyArray( planes.address()+6, sZEdgePlanes, 4 );
  477. fitK_DOP( planes );
  478. }
  479. // All faces and edges of the unit cube
  480. void MeshFit::fit18_DOP()
  481. {
  482. Vector<Point3F> planes;
  483. planes.setSize( 18 );
  484. dCopyArray( planes.address(), sFacePlanes, 6 );
  485. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  486. dCopyArray( planes.address()+10, sYEdgePlanes, 4 );
  487. dCopyArray( planes.address()+14, sZEdgePlanes, 4 );
  488. fitK_DOP( planes );
  489. }
  490. // All faces, edges and corners of the unit cube
  491. void MeshFit::fit26_DOP()
  492. {
  493. Vector<Point3F> planes;
  494. planes.setSize( 26 );
  495. dCopyArray( planes.address(), sFacePlanes, 6 );
  496. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  497. dCopyArray( planes.address()+10, sYEdgePlanes, 4 );
  498. dCopyArray( planes.address()+14, sZEdgePlanes, 4 );
  499. dCopyArray( planes.address()+18, sCornerPlanes, 8 );
  500. fitK_DOP( planes );
  501. }
  502. void MeshFit::fitK_DOP( const Vector<Point3F>& planes )
  503. {
  504. // Push the planes up against the mesh
  505. Vector<F32> planeDs;
  506. for ( S32 i = 0; i < planes.size(); i++ )
  507. planeDs.push_back( maxDot( planes[i] ) );
  508. // Collect the intersection points of any 3 planes that lie inside
  509. // the maximum distances found above
  510. Vector<Point3F> points;
  511. Vector<U32> pointIndices;
  512. for ( S32 i = 0; i < planes.size()-2; i++ )
  513. {
  514. for ( S32 j = i+1; j < planes.size()-1; j++ )
  515. {
  516. for ( S32 k = j+1; k < planes.size(); k++ )
  517. {
  518. Point3F v23 = mCross( planes[j], planes[k] );
  519. F32 denom = mDot( planes[i], v23 );
  520. if ( denom == 0 )
  521. continue;
  522. Point3F v31 = mCross( planes[k], planes[i] );
  523. Point3F v12 = mCross( planes[i], planes[j] );
  524. Point3F p = ( planeDs[i]*v23 + planeDs[j]*v31 + planeDs[k]*v12 ) / denom;
  525. // Ignore intersection points outside the volume
  526. // described by the planes
  527. bool addPoint = true;
  528. for ( S32 n = 0; n < planes.size(); n++ )
  529. {
  530. if ( ( mDot( p, planes[n] ) - planeDs[n] ) > 0.005f )
  531. {
  532. addPoint = false;
  533. break;
  534. }
  535. }
  536. if (addPoint)
  537. {
  538. points.push_back(p);
  539. pointIndices.push_back(points.size() - 1);
  540. }
  541. }
  542. }
  543. }
  544. VHACD::IVHACD::Parameters p;
  545. p.m_fillMode = VHACD::FillMode::FLOOD_FILL;
  546. p.m_maxNumVerticesPerCH = 64;
  547. p.m_shrinkWrap = true;
  548. p.m_maxRecursionDepth = 64;
  549. p.m_minimumVolumePercentErrorAllowed = 10;
  550. p.m_resolution = 10000;
  551. p.m_maxConvexHulls = 1;
  552. VHACD::IVHACD* iface = VHACD::CreateVHACD();
  553. iface->Compute((F32*)points.address(), points.size(), (U32*)pointIndices.address(), pointIndices.size() / 3, p);
  554. // safety loop.
  555. while (!iface->IsReady())
  556. {
  557. Platform::sleep(1000);
  558. }
  559. // we only get the 1 in dop?
  560. VHACD::IVHACD::ConvexHull ch;
  561. iface->GetConvexHull(0, ch);
  562. // Create TSMesh from convex hull
  563. mMeshes.increment();
  564. MeshFit::Mesh& lastMesh = mMeshes.last();
  565. lastMesh.type = MeshFit::Hull;
  566. lastMesh.transform.identity();
  567. U32* indices = new U32[ch.m_triangles.size() * 3];
  568. for (U32 ind = 0; ind < ch.m_triangles.size(); ind++)
  569. {
  570. indices[ind * 3 + 0] = ch.m_triangles[ind].mI0;
  571. indices[ind * 3 + 1] = ch.m_triangles[ind].mI1;
  572. indices[ind * 3 + 2] = ch.m_triangles[ind].mI2;
  573. }
  574. F32* resultPts = new F32[ch.m_points.size() * 3];
  575. for (U32 pts = 0; pts < ch.m_points.size(); pts++)
  576. {
  577. resultPts[pts * 3 + 0] = ch.m_points[pts].mX;
  578. resultPts[pts * 3 + 1] = ch.m_points[pts].mY;
  579. resultPts[pts * 3 + 2] = ch.m_points[pts].mZ;
  580. }
  581. lastMesh.tsmesh = createTriMesh(resultPts, (S32)ch.m_points.size(),
  582. indices, (S32)ch.m_triangles.size());
  583. lastMesh.tsmesh->computeBounds();
  584. iface->Release();
  585. delete[] resultPts;
  586. delete[] indices;
  587. }
  588. //---------------------------
  589. // Best-fit set of convex hulls
  590. void MeshFit::fitConvexHulls( U32 depth, U32 fillType, F32 minPercentage, U32 maxHulls, U32 maxHullVerts,
  591. F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError )
  592. {
  593. VHACD::IVHACD::Parameters p;
  594. p.m_fillMode = (VHACD::FillMode)fillType;
  595. p.m_maxNumVerticesPerCH = maxHullVerts;
  596. p.m_shrinkWrap = true;
  597. p.m_maxRecursionDepth = depth;
  598. p.m_minimumVolumePercentErrorAllowed = minPercentage;
  599. p.m_resolution = 10000;
  600. p.m_maxConvexHulls = maxHulls;
  601. VHACD::IVHACD* iface = VHACD::CreateVHACD_ASYNC();
  602. iface->Compute((F32*)mVerts.address(), mVerts.size(), mIndices.address(), mIndices.size() / 3, p);
  603. // safety loop.
  604. while (!iface->IsReady())
  605. {
  606. Platform::sleep(1000);
  607. }
  608. // Add a TSMesh for each hull
  609. for ( S32 i = 0; i < iface->GetNConvexHulls(); i++ )
  610. {
  611. VHACD::IVHACD::ConvexHull ch;
  612. iface->GetConvexHull(i, ch);
  613. eMeshType meshType = MeshFit::Hull;
  614. // Check if we can use a box, sphere or capsule primitive for this hull
  615. if (( boxMaxError > 0 ) || ( sphereMaxError > 0 ) || ( capsuleMaxError > 0 ))
  616. {
  617. // Compute error between actual mesh and fitted primitives
  618. F32* points = new F32[ch.m_points.size() * 3];
  619. for (U32 pt = 0; pt < ch.m_points.size(); pt++)
  620. {
  621. points[pt * 3 + 0] = ch.m_points[pt].mX;
  622. points[pt * 3 + 1] = ch.m_points[pt].mY;
  623. points[pt * 3 + 2] = ch.m_points[pt].mZ;
  624. }
  625. U32* indices = new U32[ch.m_triangles.size() * 3];
  626. for (U32 ind = 0; ind < ch.m_triangles.size(); ind++)
  627. {
  628. indices[ind * 3 + 0] = ch.m_triangles[ind].mI0;
  629. indices[ind * 3 + 1] = ch.m_triangles[ind].mI1;
  630. indices[ind * 3 + 2] = ch.m_triangles[ind].mI2;
  631. }
  632. F32 meshVolume = FLOAT_MATH::fm_computeMeshVolume(points, ch.m_triangles.size(), indices);
  633. PrimFit primFitter;
  634. F32 boxError = 100.0f, sphereError = 100.0f, capsuleError = 100.0;
  635. if ( boxMaxError > 0 )
  636. {
  637. primFitter.fitBox(ch.m_points.size(), points);
  638. boxError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getBoxVolume() ) );
  639. }
  640. if ( sphereMaxError > 0 )
  641. {
  642. primFitter.fitSphere(ch.m_points.size(), points);
  643. sphereError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getSphereVolume()));
  644. }
  645. if ( capsuleMaxError > 0 )
  646. {
  647. primFitter.fitCapsule(ch.m_points.size(), points);
  648. capsuleError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getCapsuleVolume() ) );
  649. }
  650. // Use the primitive type with smallest error less than the respective
  651. // max error, or Hull if none
  652. F32 minError = FLT_MAX;
  653. if ( ( boxError < boxMaxError ) && ( boxError < minError ) )
  654. {
  655. meshType = MeshFit::Box;
  656. minError = boxError;
  657. }
  658. if ( ( sphereError < sphereMaxError ) && ( sphereError < minError ) )
  659. {
  660. meshType = MeshFit::Sphere;
  661. minError = sphereError;
  662. }
  663. if ( ( capsuleError < capsuleMaxError ) && ( capsuleError < minError ) )
  664. {
  665. meshType = MeshFit::Capsule;
  666. minError = capsuleError;
  667. }
  668. if ( meshType == MeshFit::Box )
  669. addBox( primFitter.mBoxSides, primFitter.mBoxTransform );
  670. else if ( meshType == MeshFit::Sphere )
  671. addSphere( primFitter.mSphereRadius, primFitter.mSphereCenter );
  672. else if ( meshType == MeshFit::Capsule )
  673. addCapsule( primFitter.mCapRadius, primFitter.mCapHeight, primFitter.mCapTransform );
  674. // else fall through to Hull processing
  675. // cleanup
  676. delete[] points;
  677. delete[] indices;
  678. }
  679. if ( meshType == MeshFit::Hull )
  680. {
  681. // Create TSMesh from convex hull
  682. mMeshes.increment();
  683. MeshFit::Mesh& lastMesh = mMeshes.last();
  684. lastMesh.type = MeshFit::Hull;
  685. lastMesh.transform.identity();
  686. U32* indices = new U32[ch.m_triangles.size() * 3];
  687. for (U32 ind = 0; ind < ch.m_triangles.size(); ind++)
  688. {
  689. indices[ind * 3 + 0] = ch.m_triangles[ind].mI0;
  690. indices[ind * 3 + 1] = ch.m_triangles[ind].mI1;
  691. indices[ind * 3 + 2] = ch.m_triangles[ind].mI2;
  692. }
  693. F32* points = new F32[ch.m_points.size() * 3];
  694. for (U32 pt = 0; pt < ch.m_points.size(); pt++)
  695. {
  696. points[pt * 3 + 0] = ch.m_points[pt].mX;
  697. points[pt * 3 + 1] = ch.m_points[pt].mY;
  698. points[pt * 3 + 2] = ch.m_points[pt].mZ;
  699. }
  700. lastMesh.tsmesh = createTriMesh(points, ch.m_points.size(), indices, ch.m_triangles.size());
  701. lastMesh.tsmesh->computeBounds();
  702. delete[] points;
  703. delete[] indices;
  704. }
  705. }
  706. iface->Release();
  707. }
  708. //-----------------------------------------------------------------------------
  709. DefineTSShapeConstructorMethod( addPrimitive, bool, ( const char* meshName, const char* type, const char* params, TransformF txfm, const char* nodeName ),,
  710. ( meshName, type, params, txfm, nodeName ), false,
  711. "Add a new mesh primitive to the shape.\n"
  712. "@param meshName full name (object name + detail size) of the new mesh. If "
  713. "no detail size is present at the end of the name, a value of 2 is used.<br>"
  714. "An underscore before the number at the end of the name will be interpreted as "
  715. "a negative sign. eg. \"MyMesh_4\" will be interpreted as \"MyMesh-4\".\n"
  716. "@param type one of: \"box\", \"sphere\", \"capsule\"\n"
  717. "@param params mesh primitive parameters:\n"
  718. "<ul>"
  719. "<li>for box: \"size_x size_y size_z\"</li>"
  720. "<li>for sphere: \"radius\"</li>"
  721. "<li>for capsule: \"height radius\"</li>"
  722. "</ul>"
  723. "</ul>\n"
  724. "@param txfm local transform offset from the node for this mesh\n"
  725. "@param nodeName name of the node to attach the new mesh to (will change the "
  726. "object's node if adding a new mesh to an existing object)\n"
  727. "@return true if successful, false otherwise\n\n"
  728. "@tsexample\n"
  729. "%this.addMesh( \"Box4\", \"box\", \"2 4 2\", \"0 2 0 0 0 1 0\", \"eye\" );\n"
  730. "%this.addMesh( \"Sphere256\", \"sphere\", \"2\", \"0 0 0 0 0 1 0\", \"root\" );\n"
  731. "%this.addMesh( \"MyCapsule-1\", \"capsule\", \"2 5\", \"0 0 2 0 0 1 0\", \"base01\" );\n"
  732. "@endtsexample\n" )
  733. {
  734. MeshFit fit( mShape );
  735. if ( !dStricmp( type, "box" ) )
  736. {
  737. // Parse box parameters
  738. Point3F sides;
  739. if ( dSscanf( params, "%g %g %g", &sides.x, &sides.y, &sides.z ) == 3 )
  740. {
  741. fit.addBox( sides, MatrixF::Identity );
  742. fit.setReady();
  743. }
  744. }
  745. else if ( !dStricmp( type, "sphere" ) )
  746. {
  747. // Parse sphere parameters
  748. F32 radius;
  749. if ( dSscanf( params, "%g", &radius ) == 1)
  750. {
  751. fit.addSphere( radius, Point3F::Zero );
  752. fit.setReady();
  753. }
  754. }
  755. else if ( !dStricmp( type, "capsule" ) )
  756. {
  757. // Parse capsule parameters
  758. F32 radius, height;
  759. if ( dSscanf( params, "%g %g", &radius, &height ) == 1)
  760. {
  761. fit.addCapsule( radius, height, MatrixF::Identity );
  762. fit.setReady();
  763. }
  764. }
  765. if ( !fit.isReady() )
  766. {
  767. Con::errorf( "TSShapeConstructor::addPrimitive: Invalid params: '%s' for type '%s'",
  768. params, type );
  769. return false;
  770. }
  771. TSMesh* mesh = fit.getMesh( 0 )->tsmesh;
  772. MatrixF mat( txfm.getMatrix() );
  773. // Transform the mesh vertices
  774. if ( mesh->mVertexData.isReady() && mesh->mVerts.size() == 0 )
  775. {
  776. for (S32 i = 0; i < mesh->mVertexData.size(); i++)
  777. {
  778. TSMesh::__TSMeshVertexBase &vdata = mesh->mVertexData.getBase(i);
  779. Point3F v;
  780. mat.mulP( vdata.vert(), &v );
  781. vdata.vert( v );
  782. }
  783. }
  784. else
  785. {
  786. for (S32 i = 0; i < mesh->mVerts.size(); i++)
  787. {
  788. Point3F v(mesh->mVerts[i]);
  789. mat.mulP( v, &mesh->mVerts[i] );
  790. }
  791. }
  792. // Add the mesh to the shape at the right node
  793. mShape->addMesh( mesh, meshName );
  794. S32 dummy;
  795. String objName = String::GetTrailingNumber( meshName, dummy );
  796. setObjectNode( objName, nodeName );
  797. mShape->init();
  798. ADD_TO_CHANGE_SET();
  799. return true;
  800. }}
  801. DefineTSShapeConstructorMethod( addCollisionDetail, bool, ( S32 size, const char* type, const char* target, const char* fillMode, S32 depth, F32 minPercentage, S32 maxHulls, S32 maxVerts, F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError ), ( "flood fill", 4, 10, 30, 32, 0, 0, 0),
  802. ( size, type, target, fillMode, depth, minPercentage, maxHulls, maxVerts, boxMaxError, sphereMaxError, capsuleMaxError ), false,
  803. "Autofit a mesh primitive or set of convex hulls to the shape geometry. Hulls "
  804. "may optionally be converted to boxes, spheres and/or capsules based on their "
  805. "volume.\n"
  806. "@param size size for this detail level\n"
  807. "@param type one of: box, sphere, capsule, 10-dop x, 10-dop y, 10-dop z, 18-dop, "
  808. "26-dop, convex hulls. See the Shape Editor documentation for more details "
  809. "about these types.\n"
  810. "@param target geometry to fit collision mesh(es) to; either \"bounds\" (for the "
  811. "whole shape), or the name of an object in the shape\n"
  812. "@param depth maximum split recursion depth (hulls only)\n"
  813. "@param merge volume % threshold used to merge hulls together (hulls only)\n"
  814. "@param maxHulls allowed to be generated (hulls only)\n"
  815. "@param maxVerts maximum number of vertices per hull (hulls only)\n"
  816. "@param boxMaxError max % volume difference for a hull to be converted to a "
  817. "box (hulls only)\n"
  818. "@param sphereMaxError max % volume difference for a hull to be converted to "
  819. "a sphere (hulls only)\n"
  820. "@param capsuleMaxError max % volume difference for a hull to be converted to "
  821. "a capsule (hulls only)\n"
  822. "@return true if successful, false otherwise\n\n"
  823. "@tsexample\n"
  824. "%this.addCollisionDetail( -1, \"box\", \"bounds\" );\n"
  825. "%this.addCollisionDetail( -1, \"convex hulls\", \"bounds\", 4, 30, 30, 32, 0, 0, 0 );\n"
  826. "%this.addCollisionDetail( -1, \"convex hulls\", \"bounds\", 4, 30, 30, 32, 50, 50, 50 );\n"
  827. "@endtsexample\n" )
  828. {
  829. MeshFit fit( mShape );
  830. fit.initSourceGeometry( target );
  831. if ( !fit.isReady() )
  832. {
  833. Con::errorf( "TSShapeConstructor::addCollisionDetail: Failed to initialise mesh fitter "
  834. "using target: %s", target );
  835. return false;
  836. }
  837. if ( !dStricmp( type, "box" ) )
  838. fit.fitOBB();
  839. else if ( !dStricmp( type, "sphere" ) )
  840. fit.fitSphere();
  841. else if ( !dStricmp( type, "capsule" ) )
  842. fit.fitCapsule();
  843. else if ( !dStricmp( type, "10-dop x" ) )
  844. fit.fit10_DOP_X();
  845. else if ( !dStricmp( type, "10-dop y" ) )
  846. fit.fit10_DOP_Y();
  847. else if ( !dStricmp( type, "10-dop z" ) )
  848. fit.fit10_DOP_Z();
  849. else if ( !dStricmp( type, "18-dop" ) )
  850. fit.fit18_DOP();
  851. else if ( !dStricmp( type, "26-dop" ) )
  852. fit.fit26_DOP();
  853. else if ( !dStricmp( type, "convex hulls" ) )
  854. {
  855. U32 fillType = 0;
  856. if (!dStricmp(fillMode, "surface only"))
  857. fillType = 1;
  858. if (!dStricmp(fillMode, "raycast fill"))
  859. fillType = 2;
  860. fit.fitConvexHulls( depth, fillType, minPercentage, maxHulls, maxVerts,
  861. boxMaxError, sphereMaxError, capsuleMaxError );
  862. }
  863. else
  864. {
  865. Con::errorf( "TSShape::addCollisionDetail: Invalid type: '%s'", type );
  866. return false;
  867. }
  868. // Now add the fitted meshes to the shape:
  869. // - primitives (box, sphere, capsule) need their own node (with appropriate
  870. // transform set) so that we can use the mesh bounds to compute the real
  871. // collision primitive at load time without having to examine the geometry.
  872. // - convex meshes may be added at the default node, with identity transform
  873. // - since all meshes are in the same detail level, they all get a unique
  874. // object name
  875. const String colNodeName( String::ToString( "Col%d", size ) );
  876. // Add the default node with identity transform
  877. S32 nodeIndex = mShape->findNode( colNodeName );
  878. if ( nodeIndex == -1 )
  879. {
  880. addNode( colNodeName, "" );
  881. }
  882. else
  883. {
  884. MatrixF mat;
  885. mShape->getNodeWorldTransform( nodeIndex, &mat );
  886. if ( !mat.isIdentity() )
  887. setNodeTransform( colNodeName, TransformF::Identity );
  888. // clean node commands that are related to this target.
  889. cleanTargetNodes(colNodeName, target);
  890. }
  891. // Add the meshes to the shape =>
  892. for ( S32 i = 0; i < fit.getMeshCount(); i++ )
  893. {
  894. MeshFit::Mesh* mesh = fit.getMesh( i );
  895. // Determine a unique name for this mesh
  896. String objName;
  897. switch ( mesh->type )
  898. {
  899. case MeshFit::Box: objName = "ColBox"; break;
  900. case MeshFit::Sphere: objName = "ColSphere"; break;
  901. case MeshFit::Capsule: objName = "ColCapsule"; break;
  902. default: objName = "ColConvex"; break;
  903. }
  904. S32 suffix = i;
  905. while (true)
  906. {
  907. String tempName = objName;
  908. if (suffix == 0)
  909. suffix = 1;
  910. for (S32 s = suffix; s != 0; s /= 26) {
  911. tempName += ('A' + (s % 26));
  912. }
  913. if (mShape->findName(tempName) == -1)
  914. break;
  915. suffix++;
  916. }
  917. for (S32 s = suffix; s != 0; s /= 26) {
  918. objName += ('A' + (s % 26));
  919. }
  920. String meshName = objName + String::ToString("%d", size);
  921. mShape->addMesh( mesh->tsmesh, meshName );
  922. // Add a node for this object if needed (non-identity transform)
  923. addNode( meshName, colNodeName, target, TransformF( mesh->transform ) );
  924. mShape->setObjectNode( objName, meshName );
  925. }
  926. mShape->init();
  927. ADD_TO_CHANGE_SET();
  928. return true;
  929. }}