tsMeshFit.cpp 31 KB

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