tsMeshFit.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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 <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, F32 mergeThreshold, F32 concavityThreshold, 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. for ( S32 i = 0; i < mesh->mVertexData.size(); i++ )
  377. {
  378. TSMesh::__TSMeshVertexBase &vdata = mesh->mVertexData.getBase(i);
  379. Point3F v = vdata.vert();
  380. vdata.vert( v * radius );
  381. }
  382. mesh->computeBounds();
  383. mMeshes.increment();
  384. MeshFit::Mesh& lastMesh = mMeshes.last();
  385. lastMesh.type = MeshFit::Sphere;
  386. lastMesh.transform.identity();
  387. lastMesh.transform.setPosition(center);
  388. lastMesh.tsmesh = mesh;
  389. }
  390. void MeshFit::fitSphere()
  391. {
  392. PrimFit primFitter;
  393. primFitter.fitSphere( mVerts.size(), (F32*)mVerts.address() );
  394. addSphere( primFitter.mSphereRadius, primFitter.mSphereCenter );
  395. }
  396. //---------------------------
  397. // Best-fit capsule
  398. void MeshFit::addCapsule( F32 radius, F32 height, const MatrixF& mat )
  399. {
  400. TSMesh* mesh = initMeshFromFile( TSShapeConstructor::getCapsuleShapePath() );
  401. if ( !mesh )
  402. return;
  403. // Translate and scale the mesh verts
  404. height = mMax( 0, height );
  405. F32 offset = ( height / ( 2 * radius ) ) - 0.5f;
  406. for ( S32 i = 0; i < mesh->mVertexData.size(); i++ )
  407. {
  408. Point3F v = mesh->mVertexData.getBase(i).vert();
  409. v.y += ( ( v.y > 0 ) ? offset : -offset );
  410. mesh->mVertexData.getBase(i).vert( v * radius );
  411. }
  412. mesh->computeBounds();
  413. mMeshes.increment();
  414. mMeshes.last().type = MeshFit::Capsule;
  415. mMeshes.last().transform = mat;
  416. mMeshes.last().tsmesh = mesh;
  417. }
  418. void MeshFit::fitCapsule()
  419. {
  420. PrimFit primFitter;
  421. primFitter.fitCapsule( mVerts.size(), (F32*)mVerts.address() );
  422. addCapsule( primFitter.mCapRadius, primFitter.mCapHeight, primFitter.mCapTransform );
  423. }
  424. //---------------------------
  425. // Best-fit k-discrete-oriented-polytope (where k is the number of axis-aligned planes)
  426. // All faces + 4 edges (aligned to X axis) of the unit cube
  427. void MeshFit::fit10_DOP_X()
  428. {
  429. Vector<Point3F> planes;
  430. planes.setSize( 10 );
  431. dCopyArray( planes.address(), sFacePlanes, 6 );
  432. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  433. fitK_DOP( planes );
  434. }
  435. // All faces + 4 edges (aligned to Y axis) of the unit cube
  436. void MeshFit::fit10_DOP_Y()
  437. {
  438. Vector<Point3F> planes;
  439. planes.setSize( 10 );
  440. dCopyArray( planes.address(), sFacePlanes, 6 );
  441. dCopyArray( planes.address()+6, sYEdgePlanes, 4 );
  442. fitK_DOP( planes );
  443. }
  444. // All faces + 4 edges (aligned to Z axis) of the unit cube
  445. void MeshFit::fit10_DOP_Z()
  446. {
  447. Vector<Point3F> planes;
  448. planes.setSize( 10 );
  449. dCopyArray( planes.address(), sFacePlanes, 6 );
  450. dCopyArray( planes.address()+6, sZEdgePlanes, 4 );
  451. fitK_DOP( planes );
  452. }
  453. // All faces and edges of the unit cube
  454. void MeshFit::fit18_DOP()
  455. {
  456. Vector<Point3F> planes;
  457. planes.setSize( 18 );
  458. dCopyArray( planes.address(), sFacePlanes, 6 );
  459. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  460. dCopyArray( planes.address()+10, sYEdgePlanes, 4 );
  461. dCopyArray( planes.address()+14, sZEdgePlanes, 4 );
  462. fitK_DOP( planes );
  463. }
  464. // All faces, edges and corners of the unit cube
  465. void MeshFit::fit26_DOP()
  466. {
  467. Vector<Point3F> planes;
  468. planes.setSize( 26 );
  469. dCopyArray( planes.address(), sFacePlanes, 6 );
  470. dCopyArray( planes.address()+6, sXEdgePlanes, 4 );
  471. dCopyArray( planes.address()+10, sYEdgePlanes, 4 );
  472. dCopyArray( planes.address()+14, sZEdgePlanes, 4 );
  473. dCopyArray( planes.address()+18, sCornerPlanes, 8 );
  474. fitK_DOP( planes );
  475. }
  476. void MeshFit::fitK_DOP( const Vector<Point3F>& planes )
  477. {
  478. // Push the planes up against the mesh
  479. Vector<F32> planeDs;
  480. for ( S32 i = 0; i < planes.size(); i++ )
  481. planeDs.push_back( maxDot( planes[i] ) );
  482. // Collect the intersection points of any 3 planes that lie inside
  483. // the maximum distances found above
  484. Vector<Point3F> points;
  485. Vector<U32> pointIndices;
  486. for ( S32 i = 0; i < planes.size()-2; i++ )
  487. {
  488. for ( S32 j = i+1; j < planes.size()-1; j++ )
  489. {
  490. for ( S32 k = j+1; k < planes.size(); k++ )
  491. {
  492. Point3F v23 = mCross( planes[j], planes[k] );
  493. F32 denom = mDot( planes[i], v23 );
  494. if ( denom == 0 )
  495. continue;
  496. Point3F v31 = mCross( planes[k], planes[i] );
  497. Point3F v12 = mCross( planes[i], planes[j] );
  498. Point3F p = ( planeDs[i]*v23 + planeDs[j]*v31 + planeDs[k]*v12 ) / denom;
  499. // Ignore intersection points outside the volume
  500. // described by the planes
  501. bool addPoint = true;
  502. for ( S32 n = 0; n < planes.size(); n++ )
  503. {
  504. if ( ( mDot( p, planes[n] ) - planeDs[n] ) > 0.005f )
  505. {
  506. addPoint = false;
  507. break;
  508. }
  509. }
  510. if (addPoint)
  511. {
  512. points.push_back(p);
  513. pointIndices.push_back(points.size() - 1);
  514. }
  515. }
  516. }
  517. }
  518. VHACD::IVHACD::Parameters p;
  519. p.m_fillMode = VHACD::FillMode::FLOOD_FILL;
  520. p.m_maxNumVerticesPerCH = 64;
  521. p.m_shrinkWrap = true;
  522. p.m_maxRecursionDepth = 64;
  523. p.m_minimumVolumePercentErrorAllowed = 10;
  524. p.m_resolution = 10000;
  525. p.m_maxConvexHulls = 1;
  526. VHACD::IVHACD* iface = VHACD::CreateVHACD();
  527. iface->Compute((F32*)points.address(), points.size(), (U32*)pointIndices.address(), pointIndices.size() / 3, p);
  528. // safety loop.
  529. while (!iface->IsReady())
  530. {
  531. Platform::sleep(1000);
  532. }
  533. // we only get the 1 in dop?
  534. VHACD::IVHACD::ConvexHull ch;
  535. iface->GetConvexHull(0, ch);
  536. // Create TSMesh from convex hull
  537. mMeshes.increment();
  538. MeshFit::Mesh& lastMesh = mMeshes.last();
  539. lastMesh.type = MeshFit::Hull;
  540. lastMesh.transform.identity();
  541. U32* indices = new U32[ch.m_triangles.size() * 3];
  542. for (U32 ind = 0; ind < ch.m_triangles.size(); ind++)
  543. {
  544. indices[ind * 3 + 0] = ch.m_triangles[ind].mI0;
  545. indices[ind * 3 + 1] = ch.m_triangles[ind].mI1;
  546. indices[ind * 3 + 2] = ch.m_triangles[ind].mI2;
  547. }
  548. F32* resultPts = new F32[ch.m_points.size() * 3];
  549. for (U32 pts = 0; pts < ch.m_points.size(); pts++)
  550. {
  551. resultPts[pts * 3 + 0] = ch.m_points[pts].mX;
  552. resultPts[pts * 3 + 1] = ch.m_points[pts].mY;
  553. resultPts[pts * 3 + 2] = ch.m_points[pts].mZ;
  554. }
  555. lastMesh.tsmesh = createTriMesh(resultPts, (S32)ch.m_points.size(),
  556. indices, (S32)ch.m_triangles.size());
  557. lastMesh.tsmesh->computeBounds();
  558. iface->Release();
  559. delete[] resultPts;
  560. delete[] indices;
  561. }
  562. //---------------------------
  563. // Best-fit set of convex hulls
  564. void MeshFit::fitConvexHulls( U32 depth, F32 mergeThreshold, F32 concavityThreshold, U32 maxHullVerts,
  565. F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError )
  566. {
  567. VHACD::IVHACD::Parameters p;
  568. p.m_fillMode = VHACD::FillMode::FLOOD_FILL;
  569. p.m_maxNumVerticesPerCH = maxHullVerts;
  570. p.m_shrinkWrap = true;
  571. p.m_maxRecursionDepth = 64;
  572. p.m_minimumVolumePercentErrorAllowed = 10;
  573. p.m_resolution = 10000;
  574. p.m_maxConvexHulls = depth;
  575. VHACD::IVHACD* iface = VHACD::CreateVHACD_ASYNC();
  576. iface->Compute((F32*)mVerts.address(), mVerts.size(), mIndices.address(), mIndices.size() / 3, p);
  577. // safety loop.
  578. while (!iface->IsReady())
  579. {
  580. Platform::sleep(1000);
  581. }
  582. // Add a TSMesh for each hull
  583. for ( S32 i = 0; i < iface->GetNConvexHulls(); i++ )
  584. {
  585. VHACD::IVHACD::ConvexHull ch;
  586. iface->GetConvexHull(i, ch);
  587. eMeshType meshType = MeshFit::Hull;
  588. // Check if we can use a box, sphere or capsule primitive for this hull
  589. if (( boxMaxError > 0 ) || ( sphereMaxError > 0 ) || ( capsuleMaxError > 0 ))
  590. {
  591. // Compute error between actual mesh and fitted primitives
  592. F32* points = new F32[ch.m_points.size() * 3];
  593. for (U32 pt = 0; pt < ch.m_points.size(); pt++)
  594. {
  595. points[pt * 3 + 0] = ch.m_points[pt].mX;
  596. points[pt * 3 + 1] = ch.m_points[pt].mY;
  597. points[pt * 3 + 2] = ch.m_points[pt].mZ;
  598. }
  599. U32* indices = new U32[ch.m_triangles.size() * 3];
  600. for (U32 ind = 0; ind < ch.m_triangles.size(); ind++)
  601. {
  602. indices[ind * 3 + 0] = ch.m_triangles[ind].mI0;
  603. indices[ind * 3 + 1] = ch.m_triangles[ind].mI1;
  604. indices[ind * 3 + 2] = ch.m_triangles[ind].mI2;
  605. }
  606. F32 meshVolume = FLOAT_MATH::fm_computeMeshVolume(points, ch.m_triangles.size(), indices);
  607. PrimFit primFitter;
  608. F32 boxError = 100.0f, sphereError = 100.0f, capsuleError = 100.0;
  609. if ( boxMaxError > 0 )
  610. {
  611. primFitter.fitBox(ch.m_points.size(), points);
  612. boxError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getBoxVolume() ) );
  613. }
  614. if ( sphereMaxError > 0 )
  615. {
  616. primFitter.fitSphere(ch.m_points.size(), points);
  617. sphereError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getSphereVolume() ) );
  618. }
  619. if ( capsuleMaxError > 0 )
  620. {
  621. primFitter.fitCapsule(ch.m_points.size(), points);
  622. capsuleError = 100.0f * ( 1.0f - ( meshVolume / primFitter.getCapsuleVolume() ) );
  623. }
  624. // Use the primitive type with smallest error less than the respective
  625. // max error, or Hull if none
  626. F32 minError = FLT_MAX;
  627. if ( ( boxError < boxMaxError ) && ( boxError < minError ) )
  628. {
  629. meshType = MeshFit::Box;
  630. minError = boxError;
  631. }
  632. if ( ( sphereError < sphereMaxError ) && ( sphereError < minError ) )
  633. {
  634. meshType = MeshFit::Sphere;
  635. minError = sphereError;
  636. }
  637. if ( ( capsuleError < capsuleMaxError ) && ( capsuleError < minError ) )
  638. {
  639. meshType = MeshFit::Capsule;
  640. minError = capsuleError;
  641. }
  642. if ( meshType == MeshFit::Box )
  643. addBox( primFitter.mBoxSides, primFitter.mBoxTransform );
  644. else if ( meshType == MeshFit::Sphere )
  645. addSphere( primFitter.mSphereRadius, primFitter.mSphereCenter );
  646. else if ( meshType == MeshFit::Capsule )
  647. addCapsule( primFitter.mCapRadius, primFitter.mCapHeight, primFitter.mCapTransform );
  648. // else fall through to Hull processing
  649. // cleanup
  650. delete[] points;
  651. delete[] indices;
  652. }
  653. if ( meshType == MeshFit::Hull )
  654. {
  655. // Create TSMesh from convex hull
  656. mMeshes.increment();
  657. MeshFit::Mesh& lastMesh = mMeshes.last();
  658. lastMesh.type = MeshFit::Hull;
  659. lastMesh.transform.identity();
  660. U32* indices = new U32[ch.m_triangles.size() * 3];
  661. for (U32 ind = 0; ind < ch.m_triangles.size(); ind++)
  662. {
  663. indices[ind * 3 + 0] = ch.m_triangles[ind].mI0;
  664. indices[ind * 3 + 1] = ch.m_triangles[ind].mI1;
  665. indices[ind * 3 + 2] = ch.m_triangles[ind].mI2;
  666. }
  667. F32* points = new F32[ch.m_points.size() * 3];
  668. for (U32 pt = 0; pt < ch.m_points.size(); pt++)
  669. {
  670. points[pt * 3 + 0] = ch.m_points[pt].mX;
  671. points[pt * 3 + 1] = ch.m_points[pt].mY;
  672. points[pt * 3 + 2] = ch.m_points[pt].mZ;
  673. }
  674. lastMesh.tsmesh = createTriMesh(points, ch.m_points.size(), indices, ch.m_triangles.size());
  675. lastMesh.tsmesh->computeBounds();
  676. delete[] points;
  677. delete[] indices;
  678. }
  679. }
  680. iface->Release();
  681. }
  682. //-----------------------------------------------------------------------------
  683. DefineTSShapeConstructorMethod( addPrimitive, bool, ( const char* meshName, const char* type, const char* params, TransformF txfm, const char* nodeName ),,
  684. ( meshName, type, params, txfm, nodeName ), false,
  685. "Add a new mesh primitive to the shape.\n"
  686. "@param meshName full name (object name + detail size) of the new mesh. If "
  687. "no detail size is present at the end of the name, a value of 2 is used.<br>"
  688. "An underscore before the number at the end of the name will be interpreted as "
  689. "a negative sign. eg. \"MyMesh_4\" will be interpreted as \"MyMesh-4\".\n"
  690. "@param type one of: \"box\", \"sphere\", \"capsule\"\n"
  691. "@param params mesh primitive parameters:\n"
  692. "<ul>"
  693. "<li>for box: \"size_x size_y size_z\"</li>"
  694. "<li>for sphere: \"radius\"</li>"
  695. "<li>for capsule: \"height radius\"</li>"
  696. "</ul>"
  697. "</ul>\n"
  698. "@param txfm local transform offset from the node for this mesh\n"
  699. "@param nodeName name of the node to attach the new mesh to (will change the "
  700. "object's node if adding a new mesh to an existing object)\n"
  701. "@return true if successful, false otherwise\n\n"
  702. "@tsexample\n"
  703. "%this.addMesh( \"Box4\", \"box\", \"2 4 2\", \"0 2 0 0 0 1 0\", \"eye\" );\n"
  704. "%this.addMesh( \"Sphere256\", \"sphere\", \"2\", \"0 0 0 0 0 1 0\", \"root\" );\n"
  705. "%this.addMesh( \"MyCapsule-1\", \"capsule\", \"2 5\", \"0 0 2 0 0 1 0\", \"base01\" );\n"
  706. "@endtsexample\n" )
  707. {
  708. MeshFit fit( mShape );
  709. if ( !dStricmp( type, "box" ) )
  710. {
  711. // Parse box parameters
  712. Point3F sides;
  713. if ( dSscanf( params, "%g %g %g", &sides.x, &sides.y, &sides.z ) == 3 )
  714. {
  715. fit.addBox( sides, MatrixF::Identity );
  716. fit.setReady();
  717. }
  718. }
  719. else if ( !dStricmp( type, "sphere" ) )
  720. {
  721. // Parse sphere parameters
  722. F32 radius;
  723. if ( dSscanf( params, "%g", &radius ) == 1)
  724. {
  725. fit.addSphere( radius, Point3F::Zero );
  726. fit.setReady();
  727. }
  728. }
  729. else if ( !dStricmp( type, "capsule" ) )
  730. {
  731. // Parse capsule parameters
  732. F32 radius, height;
  733. if ( dSscanf( params, "%g %g", &radius, &height ) == 1)
  734. {
  735. fit.addCapsule( radius, height, MatrixF::Identity );
  736. fit.setReady();
  737. }
  738. }
  739. if ( !fit.isReady() )
  740. {
  741. Con::errorf( "TSShapeConstructor::addPrimitive: Invalid params: '%s' for type '%s'",
  742. params, type );
  743. return false;
  744. }
  745. TSMesh* mesh = fit.getMesh( 0 )->tsmesh;
  746. MatrixF mat( txfm.getMatrix() );
  747. // Transform the mesh vertices
  748. if ( mesh->mVertexData.isReady() && mesh->mVerts.size() == 0 )
  749. {
  750. for (S32 i = 0; i < mesh->mVertexData.size(); i++)
  751. {
  752. TSMesh::__TSMeshVertexBase &vdata = mesh->mVertexData.getBase(i);
  753. Point3F v;
  754. mat.mulP( vdata.vert(), &v );
  755. vdata.vert( v );
  756. }
  757. }
  758. else
  759. {
  760. for (S32 i = 0; i < mesh->mVerts.size(); i++)
  761. {
  762. Point3F v(mesh->mVerts[i]);
  763. mat.mulP( v, &mesh->mVerts[i] );
  764. }
  765. }
  766. // Add the mesh to the shape at the right node
  767. mShape->addMesh( mesh, meshName );
  768. S32 dummy;
  769. String objName = String::GetTrailingNumber( meshName, dummy );
  770. setObjectNode( objName, nodeName );
  771. mShape->init();
  772. ADD_TO_CHANGE_SET();
  773. return true;
  774. }}
  775. DefineTSShapeConstructorMethod( addCollisionDetail, bool, ( S32 size, const char* type, const char* target, S32 depth, F32 merge, F32 concavity, S32 maxVerts, F32 boxMaxError, F32 sphereMaxError, F32 capsuleMaxError ), ( 4, 30, 30, 32, 0, 0, 0 ),
  776. ( size, type, target, depth, merge, concavity, maxVerts, boxMaxError, sphereMaxError, capsuleMaxError ), false,
  777. "Autofit a mesh primitive or set of convex hulls to the shape geometry. Hulls "
  778. "may optionally be converted to boxes, spheres and/or capsules based on their "
  779. "volume.\n"
  780. "@param size size for this detail level\n"
  781. "@param type one of: box, sphere, capsule, 10-dop x, 10-dop y, 10-dop z, 18-dop, "
  782. "26-dop, convex hulls. See the Shape Editor documentation for more details "
  783. "about these types.\n"
  784. "@param target geometry to fit collision mesh(es) to; either \"bounds\" (for the "
  785. "whole shape), or the name of an object in the shape\n"
  786. "@param depth maximum split recursion depth (hulls only)\n"
  787. "@param merge volume % threshold used to merge hulls together (hulls only)\n"
  788. "@param concavity volume % threshold used to detect concavity (hulls only)\n"
  789. "@param maxVerts maximum number of vertices per hull (hulls only)\n"
  790. "@param boxMaxError max % volume difference for a hull to be converted to a "
  791. "box (hulls only)\n"
  792. "@param sphereMaxError max % volume difference for a hull to be converted to "
  793. "a sphere (hulls only)\n"
  794. "@param capsuleMaxError max % volume difference for a hull to be converted to "
  795. "a capsule (hulls only)\n"
  796. "@return true if successful, false otherwise\n\n"
  797. "@tsexample\n"
  798. "%this.addCollisionDetail( -1, \"box\", \"bounds\" );\n"
  799. "%this.addCollisionDetail( -1, \"convex hulls\", \"bounds\", 4, 30, 30, 32, 0, 0, 0 );\n"
  800. "%this.addCollisionDetail( -1, \"convex hulls\", \"bounds\", 4, 30, 30, 32, 50, 50, 50 );\n"
  801. "@endtsexample\n" )
  802. {
  803. MeshFit fit( mShape );
  804. fit.initSourceGeometry( target );
  805. if ( !fit.isReady() )
  806. {
  807. Con::errorf( "TSShapeConstructor::addCollisionDetail: Failed to initialise mesh fitter "
  808. "using target: %s", target );
  809. return false;
  810. }
  811. if ( !dStricmp( type, "box" ) )
  812. fit.fitOBB();
  813. else if ( !dStricmp( type, "sphere" ) )
  814. fit.fitSphere();
  815. else if ( !dStricmp( type, "capsule" ) )
  816. fit.fitCapsule();
  817. else if ( !dStricmp( type, "10-dop x" ) )
  818. fit.fit10_DOP_X();
  819. else if ( !dStricmp( type, "10-dop y" ) )
  820. fit.fit10_DOP_Y();
  821. else if ( !dStricmp( type, "10-dop z" ) )
  822. fit.fit10_DOP_Z();
  823. else if ( !dStricmp( type, "18-dop" ) )
  824. fit.fit18_DOP();
  825. else if ( !dStricmp( type, "26-dop" ) )
  826. fit.fit26_DOP();
  827. else if ( !dStricmp( type, "convex hulls" ) )
  828. {
  829. fit.fitConvexHulls( depth, merge, concavity, maxVerts,
  830. boxMaxError, sphereMaxError, capsuleMaxError );
  831. }
  832. else
  833. {
  834. Con::errorf( "TSShape::addCollisionDetail: Invalid type: '%s'", type );
  835. return false;
  836. }
  837. // Now add the fitted meshes to the shape:
  838. // - primitives (box, sphere, capsule) need their own node (with appropriate
  839. // transform set) so that we can use the mesh bounds to compute the real
  840. // collision primitive at load time without having to examine the geometry.
  841. // - convex meshes may be added at the default node, with identity transform
  842. // - since all meshes are in the same detail level, they all get a unique
  843. // object name
  844. const String colNodeName( String::ToString( "Col%d", size ) );
  845. // Add the default node with identity transform
  846. S32 nodeIndex = mShape->findNode( colNodeName );
  847. if ( nodeIndex == -1 )
  848. {
  849. addNode( colNodeName, "" );
  850. }
  851. else
  852. {
  853. MatrixF mat;
  854. mShape->getNodeWorldTransform( nodeIndex, &mat );
  855. if ( !mat.isIdentity() )
  856. setNodeTransform( colNodeName, TransformF::Identity );
  857. }
  858. // Add the meshes to the shape =>
  859. for ( S32 i = 0; i < fit.getMeshCount(); i++ )
  860. {
  861. MeshFit::Mesh* mesh = fit.getMesh( i );
  862. // Determine a unique name for this mesh
  863. String objName;
  864. switch ( mesh->type )
  865. {
  866. case MeshFit::Box: objName = "ColBox"; break;
  867. case MeshFit::Sphere: objName = "ColSphere"; break;
  868. case MeshFit::Capsule: objName = "ColCapsule"; break;
  869. default: objName = "ColConvex"; break;
  870. }
  871. for ( S32 suffix = i; suffix != 0; suffix /= 26 )
  872. objName += ('A' + ( suffix % 26 ) );
  873. String meshName = objName + String::ToString( "%d", size );
  874. mShape->addMesh( mesh->tsmesh, meshName );
  875. // Add a node for this object if needed (non-identity transform)
  876. if ( mesh->transform.isIdentity() )
  877. {
  878. mShape->setObjectNode( objName, colNodeName );
  879. }
  880. else
  881. {
  882. addNode( meshName, colNodeName, TransformF( mesh->transform ) );
  883. mShape->setObjectNode( objName, meshName );
  884. }
  885. }
  886. mShape->init();
  887. ADD_TO_CHANGE_SET();
  888. return true;
  889. }}