tsCollision.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "ts/tsShapeInstance.h"
  24. #include "ts/tsMaterialList.h"
  25. #include "scene/sceneObject.h"
  26. #include "collision/convex.h"
  27. #include "collision/collision.h"
  28. #include "T3D/tsStatic.h" // TODO: We shouldn't have this dependancy!
  29. #include "T3D/physics/physicsPlugin.h"
  30. #include "T3D/physics/physicsCollision.h"
  31. #include "collision/concretePolyList.h"
  32. #include "collision/vertexPolyList.h"
  33. #include "platform/profiler.h"
  34. #include "opcode/Opcode.h"
  35. #include "opcode/Ice/IceAABB.h"
  36. #include "opcode/Ice/IcePoint.h"
  37. #include "opcode/OPC_AABBTree.h"
  38. #include "opcode/OPC_AABBCollider.h"
  39. static bool gOpcodeInitialized = false;
  40. //-------------------------------------------------------------------------------------
  41. // Collision methods
  42. //-------------------------------------------------------------------------------------
  43. bool TSShapeInstance::buildPolyList(AbstractPolyList * polyList, S32 dl)
  44. {
  45. // if dl==-1, nothing to do
  46. if (dl==-1)
  47. return false;
  48. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::buildPolyList");
  49. // get subshape and object detail
  50. const TSDetail * detail = &mShape->details[dl];
  51. S32 ss = detail->subShapeNum;
  52. S32 od = detail->objectDetailNum;
  53. // This detail does not have any geometry.
  54. if ( ss < 0 )
  55. return false;
  56. // nothing emitted yet...
  57. bool emitted = false;
  58. U32 surfaceKey = 0;
  59. S32 start = mShape->subShapeFirstObject[ss];
  60. S32 end = mShape->subShapeNumObjects[ss] + start;
  61. if (start<end)
  62. {
  63. MatrixF initialMat;
  64. Point3F initialScale;
  65. polyList->getTransform(&initialMat,&initialScale);
  66. // set up for first object's node
  67. MatrixF mat;
  68. MatrixF scaleMat(true);
  69. F32* p = scaleMat;
  70. p[0] = initialScale.x;
  71. p[5] = initialScale.y;
  72. p[10] = initialScale.z;
  73. const MatrixF *previousMat = &mMeshObjects[start].getTransform();
  74. mat.mul(initialMat,scaleMat);
  75. mat.mul(*previousMat);
  76. polyList->setTransform(&mat,Point3F(1, 1, 1));
  77. // run through objects and collide
  78. for (S32 i=start; i<end; i++)
  79. {
  80. MeshObjectInstance * mesh = &mMeshObjects[i];
  81. if (od >= mesh->object->numMeshes)
  82. continue;
  83. if (&mesh->getTransform() != previousMat)
  84. {
  85. // different node from before, set up for this node
  86. previousMat = &mesh->getTransform();
  87. if (previousMat != NULL)
  88. {
  89. mat.mul(initialMat,scaleMat);
  90. mat.mul(*previousMat);
  91. polyList->setTransform(&mat,Point3F(1, 1, 1));
  92. }
  93. }
  94. // collide...
  95. emitted |= mesh->buildPolyList(od,polyList,surfaceKey,mMaterialList);
  96. }
  97. // restore original transform...
  98. polyList->setTransform(&initialMat,initialScale);
  99. }
  100. return emitted;
  101. }
  102. bool TSShapeInstance::getFeatures(const MatrixF& mat, const Point3F& n, ConvexFeature* cf, S32 dl)
  103. {
  104. // if dl==-1, nothing to do
  105. if (dl==-1)
  106. return false;
  107. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::buildPolyList");
  108. // get subshape and object detail
  109. const TSDetail * detail = &mShape->details[dl];
  110. S32 ss = detail->subShapeNum;
  111. S32 od = detail->objectDetailNum;
  112. // nothing emitted yet...
  113. bool emitted = false;
  114. U32 surfaceKey = 0;
  115. S32 start = mShape->subShapeFirstObject[ss];
  116. S32 end = mShape->subShapeNumObjects[ss] + start;
  117. if (start<end)
  118. {
  119. MatrixF final;
  120. const MatrixF* previousMat = &mMeshObjects[start].getTransform();
  121. final.mul(mat, *previousMat);
  122. // run through objects and collide
  123. for (S32 i=start; i<end; i++)
  124. {
  125. MeshObjectInstance * mesh = &mMeshObjects[i];
  126. if (od >= mesh->object->numMeshes)
  127. continue;
  128. if (&mesh->getTransform() != previousMat)
  129. {
  130. previousMat = &mesh->getTransform();
  131. final.mul(mat, *previousMat);
  132. }
  133. emitted |= mesh->getFeatures(od, final, n, cf, surfaceKey);
  134. }
  135. }
  136. return emitted;
  137. }
  138. bool TSShapeInstance::castRay(const Point3F & a, const Point3F & b, RayInfo * rayInfo, S32 dl)
  139. {
  140. // if dl==-1, nothing to do
  141. if (dl==-1)
  142. return false;
  143. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::castRay");
  144. // get subshape and object detail
  145. const TSDetail * detail = &mShape->details[dl];
  146. S32 ss = detail->subShapeNum;
  147. S32 od = detail->objectDetailNum;
  148. // This detail has no geometry to hit.
  149. if ( ss < 0 )
  150. return false;
  151. S32 start = mShape->subShapeFirstObject[ss];
  152. S32 end = mShape->subShapeNumObjects[ss] + start;
  153. RayInfo saveRay;
  154. saveRay.t = 1.0f;
  155. const MatrixF * saveMat = NULL;
  156. bool found = false;
  157. if (start<end)
  158. {
  159. Point3F ta, tb;
  160. // set up for first object's node
  161. MatrixF mat;
  162. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  163. mat = *previousMat;
  164. mat.inverse();
  165. mat.mulP(a,&ta);
  166. mat.mulP(b,&tb);
  167. // run through objects and collide
  168. for (S32 i=start; i<end; i++)
  169. {
  170. MeshObjectInstance * mesh = &mMeshObjects[i];
  171. if (od >= mesh->object->numMeshes)
  172. continue;
  173. if (&mesh->getTransform() != previousMat)
  174. {
  175. // different node from before, set up for this node
  176. previousMat = &mesh->getTransform();
  177. if (previousMat != NULL)
  178. {
  179. mat = *previousMat;
  180. mat.inverse();
  181. mat.mulP(a,&ta);
  182. mat.mulP(b,&tb);
  183. }
  184. }
  185. // collide...
  186. if (mesh->castRay(od,ta,tb,rayInfo, mMaterialList))
  187. {
  188. if (!rayInfo)
  189. return true;
  190. if (rayInfo->t <= saveRay.t)
  191. {
  192. saveRay = *rayInfo;
  193. saveMat = previousMat;
  194. }
  195. found = true;
  196. }
  197. }
  198. }
  199. // collide with any skins for this detail level...
  200. // TODO: if ever...
  201. // finalize the deal...
  202. if (found)
  203. {
  204. *rayInfo = saveRay;
  205. saveMat->mulV(rayInfo->normal);
  206. rayInfo->point = b-a;
  207. rayInfo->point *= rayInfo->t;
  208. rayInfo->point += a;
  209. }
  210. return found;
  211. }
  212. bool TSShapeInstance::castRayRendered(const Point3F & a, const Point3F & b, RayInfo * rayInfo, S32 dl)
  213. {
  214. // if dl==-1, nothing to do
  215. if (dl==-1)
  216. return false;
  217. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::castRayRendered");
  218. // get subshape and object detail
  219. const TSDetail * detail = &mShape->details[dl];
  220. S32 ss = detail->subShapeNum;
  221. S32 od = detail->objectDetailNum;
  222. if ( ss == -1 )
  223. return false;
  224. S32 start = mShape->subShapeFirstObject[ss];
  225. S32 end = mShape->subShapeNumObjects[ss] + start;
  226. RayInfo saveRay;
  227. saveRay.t = 1.0f;
  228. const MatrixF * saveMat = NULL;
  229. bool found = false;
  230. if (start<end)
  231. {
  232. Point3F ta, tb;
  233. // set up for first object's node
  234. MatrixF mat;
  235. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  236. mat = *previousMat;
  237. mat.inverse();
  238. mat.mulP(a,&ta);
  239. mat.mulP(b,&tb);
  240. // run through objects and collide
  241. for (S32 i=start; i<end; i++)
  242. {
  243. MeshObjectInstance * mesh = &mMeshObjects[i];
  244. if (od >= mesh->object->numMeshes)
  245. continue;
  246. if (&mesh->getTransform() != previousMat)
  247. {
  248. // different node from before, set up for this node
  249. previousMat = &mesh->getTransform();
  250. if (previousMat != NULL)
  251. {
  252. mat = *previousMat;
  253. mat.inverse();
  254. mat.mulP(a,&ta);
  255. mat.mulP(b,&tb);
  256. }
  257. }
  258. // collide...
  259. if (mesh->castRayRendered(od,ta,tb,rayInfo, mMaterialList))
  260. {
  261. if (!rayInfo)
  262. return true;
  263. if (rayInfo->t <= saveRay.t)
  264. {
  265. saveRay = *rayInfo;
  266. saveMat = previousMat;
  267. }
  268. found = true;
  269. }
  270. }
  271. }
  272. // collide with any skins for this detail level...
  273. // TODO: if ever...
  274. // finalize the deal...
  275. if (found)
  276. {
  277. *rayInfo = saveRay;
  278. saveMat->mulV(rayInfo->normal);
  279. rayInfo->point = b-a;
  280. rayInfo->point *= rayInfo->t;
  281. rayInfo->point += a;
  282. }
  283. return found;
  284. }
  285. Point3F TSShapeInstance::support(const Point3F & v, S32 dl)
  286. {
  287. // if dl==-1, nothing to do
  288. AssertFatal(dl != -1, "Error, should never try to collide with a non-existant detail level!");
  289. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::support");
  290. // get subshape and object detail
  291. const TSDetail * detail = &mShape->details[dl];
  292. S32 ss = detail->subShapeNum;
  293. S32 od = detail->objectDetailNum;
  294. S32 start = mShape->subShapeFirstObject[ss];
  295. S32 end = mShape->subShapeNumObjects[ss] + start;
  296. F32 currMaxDP = -1e9f;
  297. Point3F currSupport = Point3F(0, 0, 0);
  298. const MatrixF * previousMat = NULL;
  299. MatrixF mat;
  300. if (start<end)
  301. {
  302. Point3F va;
  303. // set up for first object's node
  304. previousMat = &mMeshObjects[start].getTransform();
  305. mat = *previousMat;
  306. mat.inverse();
  307. // run through objects and collide
  308. for (S32 i=start; i<end; i++)
  309. {
  310. MeshObjectInstance * mesh = &mMeshObjects[i];
  311. if (od >= mesh->object->numMeshes)
  312. continue;
  313. TSMesh* physMesh = mesh->getMesh(od);
  314. if (physMesh && !mesh->forceHidden && mesh->visible > 0.01f)
  315. {
  316. // collide...
  317. if (&mesh->getTransform() != previousMat)
  318. {
  319. // different node from before, set up for this node
  320. previousMat = &mesh->getTransform();
  321. mat = *previousMat;
  322. mat.inverse();
  323. }
  324. mat.mulV(v, &va);
  325. physMesh->support(mesh->frame, va, &currMaxDP, &currSupport);
  326. }
  327. }
  328. }
  329. if (currMaxDP != -1e9f)
  330. {
  331. previousMat->mulP(currSupport);
  332. return currSupport;
  333. }
  334. else
  335. {
  336. return Point3F(0, 0, 0);
  337. }
  338. }
  339. void TSShapeInstance::computeBounds(S32 dl, Box3F & bounds)
  340. {
  341. // if dl==-1, nothing to do
  342. if (dl==-1)
  343. return;
  344. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::computeBounds");
  345. // get subshape and object detail
  346. const TSDetail * detail = &mShape->details[dl];
  347. S32 ss = detail->subShapeNum;
  348. S32 od = detail->objectDetailNum;
  349. // use shape bounds for imposter details
  350. if (ss < 0)
  351. {
  352. bounds = mShape->bounds;
  353. return;
  354. }
  355. S32 start = mShape->subShapeFirstObject[ss];
  356. S32 end = mShape->subShapeNumObjects[ss] + start;
  357. // run through objects and updating bounds as we go
  358. bounds.minExtents.set( 10E30f, 10E30f, 10E30f);
  359. bounds.maxExtents.set(-10E30f,-10E30f,-10E30f);
  360. Box3F box;
  361. for (S32 i=start; i<end; i++)
  362. {
  363. MeshObjectInstance * mesh = &mMeshObjects[i];
  364. if (od >= mesh->object->numMeshes)
  365. continue;
  366. if (mesh->getMesh(od))
  367. {
  368. mesh->getMesh(od)->computeBounds(mesh->getTransform(),box, 0); // use frame 0 so TSSkinMesh uses skinned verts to compute bounds
  369. bounds.minExtents.setMin(box.minExtents);
  370. bounds.maxExtents.setMax(box.maxExtents);
  371. }
  372. }
  373. }
  374. //-------------------------------------------------------------------------------------
  375. // Object (MeshObjectInstance & PluginObjectInstance) collision methods
  376. //-------------------------------------------------------------------------------------
  377. bool TSShapeInstance::ObjectInstance::buildPolyList(S32 objectDetail, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  378. {
  379. TORQUE_UNUSED( objectDetail );
  380. TORQUE_UNUSED( polyList );
  381. TORQUE_UNUSED( surfaceKey );
  382. TORQUE_UNUSED( materials );
  383. AssertFatal(0,"TSShapeInstance::ObjectInstance::buildPolyList: no default method.");
  384. return false;
  385. }
  386. bool TSShapeInstance::ObjectInstance::getFeatures(S32 objectDetail, const MatrixF& mat, const Point3F& n, ConvexFeature* cf, U32& surfaceKey)
  387. {
  388. TORQUE_UNUSED( objectDetail );
  389. TORQUE_UNUSED( mat );
  390. TORQUE_UNUSED( n );
  391. TORQUE_UNUSED( cf );
  392. TORQUE_UNUSED( surfaceKey );
  393. AssertFatal(0,"TSShapeInstance::ObjectInstance::buildPolyList: no default method.");
  394. return false;
  395. }
  396. void TSShapeInstance::ObjectInstance::support(S32, const Point3F&, F32*, Point3F*)
  397. {
  398. AssertFatal(0,"TSShapeInstance::ObjectInstance::supprt: no default method.");
  399. }
  400. bool TSShapeInstance::ObjectInstance::castRay( S32 objectDetail, const Point3F &start, const Point3F &end, RayInfo *rayInfo, TSMaterialList *materials )
  401. {
  402. TORQUE_UNUSED( objectDetail );
  403. TORQUE_UNUSED( start );
  404. TORQUE_UNUSED( end );
  405. TORQUE_UNUSED( rayInfo );
  406. AssertFatal(0,"TSShapeInstance::ObjectInstance::castRay: no default method.");
  407. return false;
  408. }
  409. bool TSShapeInstance::MeshObjectInstance::buildPolyList( S32 objectDetail, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  410. {
  411. TSMesh * mesh = getMesh(objectDetail);
  412. if (mesh && !forceHidden && visible>0.01f)
  413. return mesh->buildPolyList(frame,polyList,surfaceKey,materials);
  414. return false;
  415. }
  416. bool TSShapeInstance::MeshObjectInstance::getFeatures(S32 objectDetail, const MatrixF& mat, const Point3F& n, ConvexFeature* cf, U32& surfaceKey)
  417. {
  418. TSMesh* mesh = getMesh(objectDetail);
  419. if (mesh && !forceHidden && visible > 0.01f)
  420. return mesh->getFeatures(frame, mat, n, cf, surfaceKey);
  421. return false;
  422. }
  423. void TSShapeInstance::MeshObjectInstance::support(S32 objectDetail, const Point3F& v, F32* currMaxDP, Point3F* currSupport)
  424. {
  425. TSMesh* mesh = getMesh(objectDetail);
  426. if (mesh && !forceHidden && visible > 0.01f)
  427. mesh->support(frame, v, currMaxDP, currSupport);
  428. }
  429. bool TSShapeInstance::MeshObjectInstance::castRay( S32 objectDetail, const Point3F & start, const Point3F & end, RayInfo * rayInfo, TSMaterialList* materials )
  430. {
  431. TSMesh* mesh = getMesh( objectDetail );
  432. if( mesh && !forceHidden && visible > 0.01f )
  433. return mesh->castRay( frame, start, end, rayInfo, materials );
  434. return false;
  435. }
  436. bool TSShapeInstance::MeshObjectInstance::castRayRendered( S32 objectDetail, const Point3F & start, const Point3F & end, RayInfo * rayInfo, TSMaterialList* materials )
  437. {
  438. TSMesh* mesh = getMesh( objectDetail );
  439. if( mesh && !forceHidden && visible > 0.01f )
  440. return mesh->castRayRendered( frame, start, end, rayInfo, materials );
  441. return false;
  442. }
  443. bool TSShapeInstance::ObjectInstance::castRayOpcode( S32 objectDetail, const Point3F & start, const Point3F & end, RayInfo *rayInfo, TSMaterialList* materials )
  444. {
  445. TORQUE_UNUSED( objectDetail );
  446. TORQUE_UNUSED( start );
  447. TORQUE_UNUSED( end );
  448. TORQUE_UNUSED( rayInfo );
  449. TORQUE_UNUSED( materials );
  450. return false;
  451. }
  452. bool TSShapeInstance::ObjectInstance::buildPolyListOpcode( S32 objectDetail, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  453. {
  454. TORQUE_UNUSED( objectDetail );
  455. TORQUE_UNUSED( polyList );
  456. TORQUE_UNUSED( surfaceKey );
  457. TORQUE_UNUSED( materials );
  458. return false;
  459. }
  460. bool TSShapeInstance::ObjectInstance::buildConvexOpcode( const MatrixF &mat, S32 objectDetail, const Box3F &bounds, Convex *c, Convex *list )
  461. {
  462. TORQUE_UNUSED( mat );
  463. TORQUE_UNUSED( objectDetail );
  464. TORQUE_UNUSED( bounds );
  465. TORQUE_UNUSED( c );
  466. TORQUE_UNUSED( list );
  467. return false;
  468. }
  469. bool TSShapeInstance::MeshObjectInstance::castRayOpcode( S32 objectDetail, const Point3F & start, const Point3F & end, RayInfo *info, TSMaterialList* materials )
  470. {
  471. TSMesh * mesh = getMesh(objectDetail);
  472. if (mesh && !forceHidden && visible>0.01f)
  473. return mesh->castRayOpcode(start, end, info, materials);
  474. return false;
  475. }
  476. bool TSShapeInstance::MeshObjectInstance::buildPolyListOpcode( S32 objectDetail, AbstractPolyList *polyList, const Box3F &box, TSMaterialList *materials )
  477. {
  478. TSMesh * mesh = getMesh(objectDetail);
  479. if ( mesh && !forceHidden && visible > 0.01f && box.isOverlapped( mesh->getBounds() ) )
  480. return mesh->buildPolyListOpcode(frame,polyList,box,materials);
  481. return false;
  482. }
  483. bool TSShapeInstance::MeshObjectInstance::buildConvexOpcode( const MatrixF &mat, S32 objectDetail, const Box3F &bounds, Convex *c, Convex *list)
  484. {
  485. TSMesh * mesh = getMesh(objectDetail);
  486. if ( mesh && !forceHidden && visible > 0.01f && bounds.isOverlapped( mesh->getBounds() ) )
  487. return mesh->buildConvexOpcode(mat, bounds, c, list);
  488. return false;
  489. }
  490. bool TSShapeInstance::buildPolyListOpcode( S32 dl, AbstractPolyList *polyList, const Box3F &box )
  491. {
  492. PROFILE_SCOPE( TSShapeInstance_buildPolyListOpcode_MeshObjInst );
  493. if (dl==-1)
  494. return false;
  495. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::buildPolyListOpcode");
  496. // get subshape and object detail
  497. const TSDetail * detail = &mShape->details[dl];
  498. S32 ss = detail->subShapeNum;
  499. if ( ss < 0 )
  500. return false;
  501. S32 od = detail->objectDetailNum;
  502. // nothing emitted yet...
  503. bool emitted = false;
  504. S32 start = mShape->subShapeFirstObject[ss];
  505. S32 end = mShape->subShapeNumObjects[ss] + start;
  506. if (start<end)
  507. {
  508. MatrixF initialMat;
  509. Point3F initialScale;
  510. polyList->getTransform(&initialMat,&initialScale);
  511. // set up for first object's node
  512. MatrixF mat;
  513. MatrixF scaleMat(true);
  514. F32* p = scaleMat;
  515. p[0] = initialScale.x;
  516. p[5] = initialScale.y;
  517. p[10] = initialScale.z;
  518. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  519. mat.mul(initialMat,scaleMat);
  520. mat.mul(*previousMat);
  521. polyList->setTransform(&mat,Point3F(1, 1, 1));
  522. // Update our bounding box...
  523. Box3F localBox = box;
  524. MatrixF otherMat = mat;
  525. otherMat.inverse();
  526. otherMat.mul(localBox);
  527. // run through objects and collide
  528. for (S32 i=start; i<end; i++)
  529. {
  530. MeshObjectInstance * mesh = &mMeshObjects[i];
  531. if (od >= mesh->object->numMeshes)
  532. continue;
  533. if (&mesh->getTransform() != previousMat)
  534. {
  535. // different node from before, set up for this node
  536. previousMat = &mesh->getTransform();
  537. if (previousMat != NULL)
  538. {
  539. mat.mul(initialMat,scaleMat);
  540. mat.mul(*previousMat);
  541. polyList->setTransform(&mat,Point3F(1, 1, 1));
  542. // Update our bounding box...
  543. otherMat = mat;
  544. otherMat.inverse();
  545. localBox = box;
  546. otherMat.mul(localBox);
  547. }
  548. }
  549. // collide...
  550. emitted |= mesh->buildPolyListOpcode(od,polyList,localBox,mMaterialList);
  551. }
  552. // restore original transform...
  553. polyList->setTransform(&initialMat,initialScale);
  554. }
  555. return emitted;
  556. }
  557. bool TSShapeInstance::castRayOpcode( S32 dl, const Point3F & startPos, const Point3F & endPos, RayInfo *info)
  558. {
  559. // if dl==-1, nothing to do
  560. if (dl==-1)
  561. return false;
  562. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::castRayOpcode");
  563. info->t = 100.f;
  564. // get subshape and object detail
  565. const TSDetail * detail = &mShape->details[dl];
  566. S32 ss = detail->subShapeNum;
  567. if ( ss < 0 )
  568. return false;
  569. S32 od = detail->objectDetailNum;
  570. // nothing emitted yet...
  571. bool emitted = false;
  572. const MatrixF* saveMat = NULL;
  573. S32 start = mShape->subShapeFirstObject[ss];
  574. S32 end = mShape->subShapeNumObjects[ss] + start;
  575. if (start<end)
  576. {
  577. MatrixF mat;
  578. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  579. mat = *previousMat;
  580. mat.inverse();
  581. Point3F localStart, localEnd;
  582. mat.mulP(startPos, &localStart);
  583. mat.mulP(endPos, &localEnd);
  584. // run through objects and collide
  585. for (S32 i=start; i<end; i++)
  586. {
  587. MeshObjectInstance * mesh = &mMeshObjects[i];
  588. if (od >= mesh->object->numMeshes)
  589. continue;
  590. if (&mesh->getTransform() != previousMat)
  591. {
  592. // different node from before, set up for this node
  593. previousMat = &mesh->getTransform();
  594. if (previousMat != NULL)
  595. {
  596. mat = *previousMat;
  597. mat.inverse();
  598. mat.mulP(startPos, &localStart);
  599. mat.mulP(endPos, &localEnd);
  600. }
  601. }
  602. // collide...
  603. if ( mesh->castRayOpcode(od,localStart, localEnd, info, mMaterialList) )
  604. {
  605. saveMat = previousMat;
  606. emitted = true;
  607. }
  608. }
  609. }
  610. if ( emitted )
  611. {
  612. saveMat->mulV(info->normal);
  613. info->point = endPos - startPos;
  614. info->point *= info->t;
  615. info->point += startPos;
  616. }
  617. return emitted;
  618. }
  619. bool TSShapeInstance::buildConvexOpcode( const MatrixF &objMat, const Point3F &objScale, S32 dl, const Box3F &bounds, Convex *c, Convex *list )
  620. {
  621. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::buildConvexOpcode");
  622. // get subshape and object detail
  623. const TSDetail * detail = &mShape->details[dl];
  624. S32 ss = detail->subShapeNum;
  625. S32 od = detail->objectDetailNum;
  626. // nothing emitted yet...
  627. bool emitted = false;
  628. S32 start = mShape->subShapeFirstObject[ss];
  629. S32 end = mShape->subShapeNumObjects[ss] + start;
  630. if (start<end)
  631. {
  632. MatrixF initialMat = objMat;
  633. Point3F initialScale = objScale;
  634. // set up for first object's node
  635. MatrixF mat;
  636. MatrixF scaleMat(true);
  637. F32* p = scaleMat;
  638. p[0] = initialScale.x;
  639. p[5] = initialScale.y;
  640. p[10] = initialScale.z;
  641. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  642. mat.mul(initialMat,scaleMat);
  643. mat.mul(*previousMat);
  644. // Update our bounding box...
  645. Box3F localBox = bounds;
  646. MatrixF otherMat = mat;
  647. otherMat.inverse();
  648. otherMat.mul(localBox);
  649. // run through objects and collide
  650. for (S32 i=start; i<end; i++)
  651. {
  652. MeshObjectInstance * mesh = &mMeshObjects[i];
  653. if (od >= mesh->object->numMeshes)
  654. continue;
  655. if (&mesh->getTransform() != previousMat)
  656. {
  657. // different node from before, set up for this node
  658. previousMat = &mesh->getTransform();
  659. if (previousMat != NULL)
  660. {
  661. mat.mul(initialMat,scaleMat);
  662. mat.mul(*previousMat);
  663. // Update our bounding box...
  664. otherMat = mat;
  665. otherMat.inverse();
  666. localBox = bounds;
  667. otherMat.mul(localBox);
  668. }
  669. }
  670. // collide... note we pass the original mech transform
  671. // here so that the convex data returned is in mesh space.
  672. emitted |= mesh->buildConvexOpcode(*previousMat,od,localBox,c, list);
  673. }
  674. }
  675. return emitted;
  676. }
  677. void TSShape::findColDetails( bool useVisibleMesh, Vector<S32> *outDetails, Vector<S32> *outLOSDetails ) const
  678. {
  679. PROFILE_SCOPE( TSShape_findColDetails );
  680. if ( useVisibleMesh )
  681. {
  682. // If we're using the visible mesh for collision then
  683. // find the highest detail and use that.
  684. U32 highestDetail = -1;
  685. F32 highestSize = -F32_MAX;
  686. for ( U32 i = 0; i < details.size(); i++ )
  687. {
  688. // Make sure we skip any details that shouldn't be rendered
  689. if ( details[i].size < 0 )
  690. continue;
  691. /*
  692. // Also make sure we skip any collision details with a size.
  693. const String &name = names[details[i].nameIndex];
  694. if ( dStrStartsWith( name, "Collision" ) ||
  695. dStrStartsWith( name, "LOS" ) )
  696. continue;
  697. */
  698. // Otherwise test against the current highest size
  699. if ( details[i].size > highestSize )
  700. {
  701. highestDetail = i;
  702. highestSize = details[i].size;
  703. }
  704. }
  705. // We use the same detail for both raycast and collisions.
  706. if ( highestDetail != -1 )
  707. {
  708. outDetails->push_back( highestDetail );
  709. if ( outLOSDetails )
  710. outLOSDetails->push_back( highestDetail );
  711. }
  712. return;
  713. }
  714. // Detail meshes starting with COL or LOS is considered
  715. // to be a collision mesh.
  716. //
  717. // The LOS (light of sight) details are used for raycasts.
  718. for ( U32 i = 0; i < details.size(); i++ )
  719. {
  720. const String &name = names[ details[i].nameIndex ];
  721. if ( !dStrStartsWith( name, "Collision" ) )
  722. continue;
  723. outDetails->push_back(i);
  724. // If we're not returning LOS details then skip out.
  725. if ( !outLOSDetails )
  726. continue;
  727. // The way LOS works is that it will check to see if there is a LOS detail that matches
  728. // the the collision detail + 1 + MaxCollisionShapes (this variable name should change in
  729. // the future). If it can't find a matching LOS it will simply use the collision instead.
  730. // We check for any "unmatched" LOS's further down.
  731. // Extract the detail number from the name.
  732. S32 number = 0;
  733. String::GetTrailingNumber( name, number );
  734. // Look for a matching LOS collision detail.
  735. //
  736. // TODO: Fix the old 9 detail offset which is there
  737. // because you cannot have two detail markers with
  738. // the same detail number.
  739. //
  740. const S32 LOSOverrideOffset = 9;
  741. String buff = String::ToString( "LOS-%d", mAbs( number ) + LOSOverrideOffset );
  742. S32 los = findDetail( buff );
  743. // If we didn't find the lod detail then use the
  744. // normal collision detail for LOS tests.
  745. if ( los == -1 )
  746. los = i;
  747. outLOSDetails->push_back( los );
  748. }
  749. // If we're not returning LOS details then skip out.
  750. if ( !outLOSDetails )
  751. return;
  752. // Snag any "unmatched" LOS details and put
  753. // them at the end of the list.
  754. for ( U32 i = 0; i < details.size(); i++ )
  755. {
  756. const String &name = names[ details[i].nameIndex ];
  757. if ( !dStrStartsWith( name, "LOS" ) )
  758. continue;
  759. // See if we already have this LOS
  760. bool found = false;
  761. for (U32 j = 0; j < outLOSDetails->size(); j++)
  762. {
  763. if ( (*outLOSDetails)[j] == i )
  764. {
  765. found = true;
  766. break;
  767. }
  768. }
  769. if ( !found )
  770. outLOSDetails->push_back(i);
  771. }
  772. }
  773. PhysicsCollision* TSShape::buildColShape( bool useVisibleMesh, const Point3F &scale )
  774. {
  775. return _buildColShapes( useVisibleMesh, scale, NULL, false );
  776. }
  777. void TSShape::buildColShapes( bool useVisibleMesh, const Point3F &scale, Vector< CollisionShapeInfo > *list )
  778. {
  779. _buildColShapes( useVisibleMesh, scale, list, true );
  780. }
  781. PhysicsCollision* TSShape::_buildColShapes( bool useVisibleMesh, const Point3F &scale, Vector< CollisionShapeInfo > *list, bool perMesh )
  782. {
  783. PROFILE_SCOPE( TSShape_buildColShapes );
  784. if ( !PHYSICSMGR )
  785. return NULL;
  786. PhysicsCollision *colShape = NULL;
  787. U32 surfaceKey = 0;
  788. if ( useVisibleMesh )
  789. {
  790. // Here we build triangle collision meshes from the
  791. // visible detail levels.
  792. // A negative subshape on the detail means we don't have geometry.
  793. const TSShape::Detail &detail = details[0];
  794. if ( detail.subShapeNum < 0 )
  795. return NULL;
  796. // We don't try to optimize the triangles we're given
  797. // and assume the art was created properly for collision.
  798. ConcretePolyList polyList;
  799. polyList.setTransform( &MatrixF::Identity, scale );
  800. // Create the collision meshes.
  801. S32 start = subShapeFirstObject[ detail.subShapeNum ];
  802. S32 end = start + subShapeNumObjects[ detail.subShapeNum ];
  803. for ( S32 o=start; o < end; o++ )
  804. {
  805. const TSShape::Object &object = objects[o];
  806. if ( detail.objectDetailNum >= object.numMeshes )
  807. continue;
  808. // No mesh or no verts.... nothing to do.
  809. TSMesh *mesh = meshes[ object.startMeshIndex + detail.objectDetailNum ];
  810. if ( !mesh || mesh->mNumVerts == 0 )
  811. continue;
  812. // Gather the mesh triangles.
  813. polyList.clear();
  814. mesh->buildPolyList( 0, &polyList, surfaceKey, NULL );
  815. // Create the collision shape if we haven't already.
  816. if ( !colShape )
  817. colShape = PHYSICSMGR->createCollision();
  818. // Get the object space mesh transform.
  819. MatrixF localXfm;
  820. getNodeWorldTransform( object.nodeIndex, &localXfm );
  821. colShape->addTriangleMesh( polyList.mVertexList.address(),
  822. polyList.mVertexList.size(),
  823. polyList.mIndexList.address(),
  824. polyList.mIndexList.size() / 3,
  825. localXfm );
  826. if ( perMesh )
  827. {
  828. list->increment();
  829. list->last().colNode = -1;
  830. list->last().colShape = colShape;
  831. colShape = NULL;
  832. }
  833. }
  834. // Return what we built... if anything.
  835. return colShape;
  836. }
  837. // Scan out the collision hulls...
  838. //
  839. // TODO: We need to support LOS collision for physics.
  840. //
  841. for ( U32 i = 0; i < details.size(); i++ )
  842. {
  843. const TSShape::Detail &detail = details[i];
  844. const String &name = names[detail.nameIndex];
  845. // Is this a valid collision detail.
  846. if ( !dStrStartsWith( name, "Collision" ) || detail.subShapeNum < 0 )
  847. continue;
  848. // Now go thru the meshes for this detail.
  849. S32 start = subShapeFirstObject[ detail.subShapeNum ];
  850. S32 end = start + subShapeNumObjects[ detail.subShapeNum ];
  851. if ( start >= end )
  852. continue;
  853. for ( S32 o=start; o < end; o++ )
  854. {
  855. const TSShape::Object &object = objects[o];
  856. const String &meshName = names[ object.nameIndex ];
  857. if ( object.numMeshes <= detail.objectDetailNum )
  858. continue;
  859. // No mesh, a flat bounds, or no verts.... nothing to do.
  860. TSMesh *mesh = meshes[ object.startMeshIndex + detail.objectDetailNum ];
  861. if ( !mesh || mesh->getBounds().isEmpty() || mesh->mNumVerts == 0 )
  862. continue;
  863. // We need the default mesh transform.
  864. MatrixF localXfm;
  865. getNodeWorldTransform( object.nodeIndex, &localXfm );
  866. // We have some sort of collision shape... so allocate it.
  867. if ( !colShape )
  868. colShape = PHYSICSMGR->createCollision();
  869. // We have geometry... what is it?
  870. if ( dStrStartsWith( meshName, "Colbox" ) )
  871. {
  872. // The bounds define the box extents directly.
  873. Point3F halfWidth = mesh->getBounds().getExtents() * 0.5f;
  874. // Add the offset to the center of the bounds
  875. // into the local space transform.
  876. MatrixF centerXfm( true );
  877. centerXfm.setPosition( mesh->getBounds().getCenter() );
  878. localXfm.mul( centerXfm );
  879. colShape->addBox( halfWidth, localXfm );
  880. }
  881. else if ( dStrStartsWith( meshName, "Colsphere" ) )
  882. {
  883. // Get a sphere inscribed to the bounds.
  884. F32 radius = mesh->getBounds().len_min() * 0.5f;
  885. // Add the offset to the center of the bounds
  886. // into the local space transform.
  887. MatrixF primXfm( true );
  888. primXfm.setPosition( mesh->getBounds().getCenter() );
  889. localXfm.mul( primXfm );
  890. colShape->addSphere( radius, localXfm );
  891. }
  892. else if ( dStrStartsWith( meshName, "Colcapsule" ) )
  893. {
  894. // Use the smallest extent as the radius for the capsule.
  895. Point3F extents = mesh->getBounds().getExtents();
  896. F32 radius = extents.least() * 0.5f;
  897. // We need to center the capsule and align it to the Y axis.
  898. MatrixF primXfm( true );
  899. primXfm.setPosition( mesh->getBounds().getCenter() );
  900. // Use the longest axis as the capsule height.
  901. F32 height = -radius * 2.0f;
  902. if ( extents.x > extents.y && extents.x > extents.z )
  903. {
  904. primXfm.setColumn( 0, Point3F( 0, 0, 1 ) );
  905. primXfm.setColumn( 1, Point3F( 1, 0, 0 ) );
  906. primXfm.setColumn( 2, Point3F( 0, 1, 0 ) );
  907. height += extents.x;
  908. }
  909. else if ( extents.z > extents.x && extents.z > extents.y )
  910. {
  911. primXfm.setColumn( 0, Point3F( 0, 1, 0 ) );
  912. primXfm.setColumn( 1, Point3F( 0, 0, 1 ) );
  913. primXfm.setColumn( 2, Point3F( 1, 0, 0 ) );
  914. height += extents.z;
  915. }
  916. else
  917. height += extents.y;
  918. // Add the primitive transform into the local transform.
  919. localXfm.mul( primXfm );
  920. // If we didn't find a positive height then fallback to
  921. // creating a sphere which is better than nothing.
  922. if ( height > 0.0f )
  923. colShape->addCapsule( radius, height, localXfm );
  924. else
  925. colShape->addSphere( radius, localXfm );
  926. }
  927. else if ( dStrStartsWith( meshName, "Colmesh" ) )
  928. {
  929. // For a triangle mesh we gather the triangles raw from the
  930. // mesh and don't do any optimizations or cleanup.
  931. ConcretePolyList polyList;
  932. polyList.setTransform( &MatrixF::Identity, scale );
  933. mesh->buildPolyList( 0, &polyList, surfaceKey, NULL );
  934. colShape->addTriangleMesh( polyList.mVertexList.address(),
  935. polyList.mVertexList.size(),
  936. polyList.mIndexList.address(),
  937. polyList.mIndexList.size() / 3,
  938. localXfm );
  939. }
  940. else
  941. {
  942. // Any other mesh name we assume as a generic convex hull.
  943. //
  944. // Collect the verts using the vertex polylist which will
  945. // filter out duplicates. This is importaint as the convex
  946. // generators can sometimes fail with duplicate verts.
  947. //
  948. VertexPolyList polyList;
  949. MatrixF meshMat( localXfm );
  950. Point3F t = meshMat.getPosition();
  951. t.convolve( scale );
  952. meshMat.setPosition( t );
  953. polyList.setTransform( &MatrixF::Identity, scale );
  954. mesh->buildPolyList( 0, &polyList, surfaceKey, NULL );
  955. colShape->addConvex( polyList.getVertexList().address(),
  956. polyList.getVertexList().size(),
  957. meshMat );
  958. }
  959. if ( perMesh )
  960. {
  961. list->increment();
  962. S32 detailNum;
  963. String::GetTrailingNumber( name, detailNum );
  964. String str = String::ToString( "%s%i", meshName.c_str(), detailNum );
  965. S32 found = findNode( str );
  966. if ( found == -1 )
  967. {
  968. str = str.replace('-','_');
  969. found = findNode( str );
  970. }
  971. list->last().colNode = found;
  972. list->last().colShape = colShape;
  973. colShape = NULL;
  974. }
  975. } // objects
  976. } // details
  977. return colShape;
  978. }
  979. bool TSMesh::buildPolyListOpcode( const S32 od, AbstractPolyList *polyList, const Box3F &nodeBox, TSMaterialList *materials )
  980. {
  981. PROFILE_SCOPE( TSMesh_buildPolyListOpcode );
  982. // This is small... there is no win for preallocating it.
  983. Opcode::AABBCollider opCollider;
  984. opCollider.SetPrimitiveTests( true );
  985. // This isn't really needed within the AABBCollider as
  986. // we don't use temporal coherance... use a static to
  987. // remove the allocation overhead.
  988. static Opcode::AABBCache opCache;
  989. IceMaths::AABB opBox;
  990. opBox.SetMinMax( Point( nodeBox.minExtents.x, nodeBox.minExtents.y, nodeBox.minExtents.z ),
  991. Point( nodeBox.maxExtents.x, nodeBox.maxExtents.y, nodeBox.maxExtents.z ) );
  992. Opcode::CollisionAABB opCBox(opBox);
  993. if ( !opCollider.Collide( opCache, opCBox, *mOptTree ) )
  994. return false;
  995. U32 count = opCollider.GetNbTouchedPrimitives();
  996. const udword *idx = opCollider.GetTouchedPrimitives();
  997. Opcode::VertexPointers vp;
  998. U32 plIdx[3];
  999. S32 j;
  1000. Point3F tmp;
  1001. const IceMaths::Point **verts;
  1002. const Opcode::MeshInterface *mi = mOptTree->GetMeshInterface();
  1003. for ( S32 i=0; i < count; i++ )
  1004. {
  1005. // Get the triangle...
  1006. mi->GetTriangle( vp, idx[i] );
  1007. verts = vp.Vertex;
  1008. // And register it in the polylist...
  1009. polyList->begin( NULL, i );
  1010. for( j = 2; j > -1; j-- )
  1011. {
  1012. tmp.set( verts[j]->x, verts[j]->y, verts[j]->z );
  1013. plIdx[j] = polyList->addPoint( tmp );
  1014. polyList->vertex( plIdx[j] );
  1015. }
  1016. polyList->plane( plIdx[0], plIdx[2], plIdx[1] );
  1017. polyList->end();
  1018. }
  1019. // TODO: Add a polyList->getCount() so we can see if we
  1020. // got clipped polys and didn't really emit anything.
  1021. return count > 0;
  1022. }
  1023. bool TSMesh::buildConvexOpcode( const MatrixF &meshToObjectMat, const Box3F &nodeBox, Convex *convex, Convex *list )
  1024. {
  1025. PROFILE_SCOPE( TSMesh_buildConvexOpcode );
  1026. // This is small... there is no win for preallocating it.
  1027. Opcode::AABBCollider opCollider;
  1028. opCollider.SetPrimitiveTests( true );
  1029. // This isn't really needed within the AABBCollider as
  1030. // we don't use temporal coherance... use a static to
  1031. // remove the allocation overhead.
  1032. static Opcode::AABBCache opCache;
  1033. IceMaths::AABB opBox;
  1034. opBox.SetMinMax( Point( nodeBox.minExtents.x, nodeBox.minExtents.y, nodeBox.minExtents.z ),
  1035. Point( nodeBox.maxExtents.x, nodeBox.maxExtents.y, nodeBox.maxExtents.z ) );
  1036. Opcode::CollisionAABB opCBox(opBox);
  1037. if( !opCollider.Collide( opCache, opCBox, *mOptTree ) )
  1038. return false;
  1039. U32 cnt = opCollider.GetNbTouchedPrimitives();
  1040. const udword *idx = opCollider.GetTouchedPrimitives();
  1041. Opcode::VertexPointers vp;
  1042. for ( S32 i = 0; i < cnt; i++ )
  1043. {
  1044. // First, check our active convexes for a potential match (and clean things
  1045. // up, too.)
  1046. const U32 curIdx = idx[i];
  1047. // See if the square already exists as part of the working set.
  1048. bool gotMatch = false;
  1049. CollisionWorkingList& wl = convex->getWorkingList();
  1050. for ( CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext )
  1051. {
  1052. if( itr->mConvex->getType() != TSPolysoupConvexType )
  1053. continue;
  1054. const TSStaticPolysoupConvex *chunkc = static_cast<TSStaticPolysoupConvex*>( itr->mConvex );
  1055. if( chunkc->getObject() != TSStaticPolysoupConvex::smCurObject )
  1056. continue;
  1057. if( chunkc->mesh != this )
  1058. continue;
  1059. if( chunkc->idx != curIdx )
  1060. continue;
  1061. // A match! Don't need to add it.
  1062. gotMatch = true;
  1063. break;
  1064. }
  1065. if( gotMatch )
  1066. continue;
  1067. // Get the triangle...
  1068. mOptTree->GetMeshInterface()->GetTriangle( vp, idx[i] );
  1069. Point3F a( vp.Vertex[0]->x, vp.Vertex[0]->y, vp.Vertex[0]->z );
  1070. Point3F b( vp.Vertex[1]->x, vp.Vertex[1]->y, vp.Vertex[1]->z );
  1071. Point3F c( vp.Vertex[2]->x, vp.Vertex[2]->y, vp.Vertex[2]->z );
  1072. // Transform the result into object space!
  1073. meshToObjectMat.mulP( a );
  1074. meshToObjectMat.mulP( b );
  1075. meshToObjectMat.mulP( c );
  1076. PlaneF p( c, b, a );
  1077. Point3F peak = ((a + b + c) / 3.0f) - (p * 0.15f);
  1078. // Set up the convex...
  1079. TSStaticPolysoupConvex *cp = new TSStaticPolysoupConvex();
  1080. list->registerObject( cp );
  1081. convex->addToWorkingList( cp );
  1082. cp->mesh = this;
  1083. cp->idx = curIdx;
  1084. cp->mObject = TSStaticPolysoupConvex::smCurObject;
  1085. cp->normal = p;
  1086. cp->verts[0] = a;
  1087. cp->verts[1] = b;
  1088. cp->verts[2] = c;
  1089. cp->verts[3] = peak;
  1090. // Update the bounding box.
  1091. Box3F &bounds = cp->box;
  1092. bounds.minExtents.set( F32_MAX, F32_MAX, F32_MAX );
  1093. bounds.maxExtents.set( -F32_MAX, -F32_MAX, -F32_MAX );
  1094. bounds.minExtents.setMin( a );
  1095. bounds.minExtents.setMin( b );
  1096. bounds.minExtents.setMin( c );
  1097. bounds.minExtents.setMin( peak );
  1098. bounds.maxExtents.setMax( a );
  1099. bounds.maxExtents.setMax( b );
  1100. bounds.maxExtents.setMax( c );
  1101. bounds.maxExtents.setMax( peak );
  1102. }
  1103. return true;
  1104. }
  1105. void TSMesh::prepOpcodeCollision()
  1106. {
  1107. // Make sure opcode is loaded!
  1108. if( !gOpcodeInitialized )
  1109. {
  1110. Opcode::InitOpcode();
  1111. gOpcodeInitialized = true;
  1112. }
  1113. // Don't re init if we already have something...
  1114. if ( mOptTree )
  1115. return;
  1116. // Ok, first set up a MeshInterface
  1117. Opcode::MeshInterface *mi = new Opcode::MeshInterface();
  1118. mOpMeshInterface = mi;
  1119. // Figure out how many triangles we have...
  1120. U32 triCount = 0;
  1121. const U32 base = 0;
  1122. for ( U32 i = 0; i < primitives.size(); i++ )
  1123. {
  1124. TSDrawPrimitive & draw = primitives[i];
  1125. const U32 start = draw.start;
  1126. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildPolyList (1)" );
  1127. // gonna depend on what kind of primitive it is...
  1128. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  1129. triCount += draw.numElements / 3;
  1130. else
  1131. {
  1132. // Have to walk the tristrip to get a count... may have degenerates
  1133. U32 idx0 = base + indices[start + 0];
  1134. U32 idx1;
  1135. U32 idx2 = base + indices[start + 1];
  1136. U32 * nextIdx = &idx1;
  1137. for ( S32 j = 2; j < draw.numElements; j++ )
  1138. {
  1139. *nextIdx = idx2;
  1140. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  1141. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  1142. idx2 = base + indices[start + j];
  1143. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  1144. continue;
  1145. triCount++;
  1146. }
  1147. }
  1148. }
  1149. // Just do the first trilist for now.
  1150. mi->SetNbVertices( mVertexData.isReady() ? mNumVerts : verts.size() );
  1151. mi->SetNbTriangles( triCount );
  1152. // Stuff everything into appropriate arrays.
  1153. IceMaths::IndexedTriangle *its = new IceMaths::IndexedTriangle[ mi->GetNbTriangles() ], *curIts = its;
  1154. IceMaths::Point *pts = new IceMaths::Point[ mi->GetNbVertices() ];
  1155. mOpTris = its;
  1156. mOpPoints = pts;
  1157. // add the polys...
  1158. for ( U32 i = 0; i < primitives.size(); i++ )
  1159. {
  1160. TSDrawPrimitive & draw = primitives[i];
  1161. const U32 start = draw.start;
  1162. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildPolyList (1)" );
  1163. const U32 matIndex = draw.matIndex & TSDrawPrimitive::MaterialMask;
  1164. // gonna depend on what kind of primitive it is...
  1165. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  1166. {
  1167. for ( S32 j = 0; j < draw.numElements; )
  1168. {
  1169. curIts->mVRef[2] = base + indices[start + j + 0];
  1170. curIts->mVRef[1] = base + indices[start + j + 1];
  1171. curIts->mVRef[0] = base + indices[start + j + 2];
  1172. curIts->mMatIdx = matIndex;
  1173. curIts++;
  1174. j += 3;
  1175. }
  1176. }
  1177. else
  1178. {
  1179. AssertFatal( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Strip,"TSMesh::buildPolyList (2)" );
  1180. U32 idx0 = base + indices[start + 0];
  1181. U32 idx1;
  1182. U32 idx2 = base + indices[start + 1];
  1183. U32 * nextIdx = &idx1;
  1184. for ( S32 j = 2; j < draw.numElements; j++ )
  1185. {
  1186. *nextIdx = idx2;
  1187. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  1188. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  1189. idx2 = base + indices[start + j];
  1190. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  1191. continue;
  1192. curIts->mVRef[2] = idx0;
  1193. curIts->mVRef[1] = idx1;
  1194. curIts->mVRef[0] = idx2;
  1195. curIts->mMatIdx = matIndex;
  1196. curIts++;
  1197. }
  1198. }
  1199. }
  1200. AssertFatal( (curIts - its) == mi->GetNbTriangles(), "Triangle count mismatch!" );
  1201. for( S32 i = 0; i < mi->GetNbVertices(); i++ )
  1202. {
  1203. if( mVertexData.isReady() )
  1204. {
  1205. const __TSMeshVertexBase &vertData = mVertexData.getBase(i);
  1206. pts[i].Set( vertData.vert().x, vertData.vert().y, vertData.vert().z );
  1207. }
  1208. else
  1209. {
  1210. pts[i].Set( verts[i].x, verts[i].y, verts[i].z );
  1211. }
  1212. }
  1213. mi->SetPointers( its, pts );
  1214. // Ok, we've got a mesh interface populated, now let's build a thingy to collide against.
  1215. mOptTree = new Opcode::Model();
  1216. Opcode::OPCODECREATE opcc;
  1217. opcc.mCanRemap = true;
  1218. opcc.mIMesh = mi;
  1219. opcc.mKeepOriginal = false;
  1220. opcc.mNoLeaf = false;
  1221. opcc.mQuantized = false;
  1222. opcc.mSettings.mLimit = 1;
  1223. mOptTree->Build( opcc );
  1224. }
  1225. static Point3F texGenAxis[18] =
  1226. {
  1227. Point3F(0,0,1), Point3F(1,0,0), Point3F(0,-1,0),
  1228. Point3F(0,0,-1), Point3F(1,0,0), Point3F(0,1,0),
  1229. Point3F(1,0,0), Point3F(0,1,0), Point3F(0,0,1),
  1230. Point3F(-1,0,0), Point3F(0,1,0), Point3F(0,0,-1),
  1231. Point3F(0,1,0), Point3F(1,0,0), Point3F(0,0,1),
  1232. Point3F(0,-1,0), Point3F(-1,0,0), Point3F(0,0,-1)
  1233. };
  1234. bool TSMesh::castRayOpcode( const Point3F &s, const Point3F &e, RayInfo *info, TSMaterialList *materials )
  1235. {
  1236. Opcode::RayCollider ray;
  1237. Opcode::CollisionFaces cfs;
  1238. IceMaths::Point dir( e.x - s.x, e.y - s.y, e.z - s.z );
  1239. const F32 rayLen = dir.Magnitude();
  1240. IceMaths::Ray vec( Point(s.x, s.y, s.z), dir.Normalize() );
  1241. ray.SetDestination( &cfs);
  1242. ray.SetFirstContact( false );
  1243. ray.SetClosestHit( true );
  1244. ray.SetPrimitiveTests( true );
  1245. ray.SetCulling( true );
  1246. ray.SetMaxDist( rayLen );
  1247. AssertFatal( ray.ValidateSettings() == NULL, "invalid ray settings" );
  1248. // Do collision.
  1249. bool safety = ray.Collide( vec, *mOptTree );
  1250. AssertFatal( safety, "TSMesh::castRayOpcode - no good ray collide!" );
  1251. // If no hit, just skip out.
  1252. if( cfs.GetNbFaces() == 0 )
  1253. return false;
  1254. // Got a hit!
  1255. AssertFatal( cfs.GetNbFaces() == 1, "bad" );
  1256. const Opcode::CollisionFace &face = cfs.GetFaces()[0];
  1257. // If the cast was successful let's check if the t value is less than what we had
  1258. // and toggle the collision boolean
  1259. // Stupid t... i prefer coffee
  1260. const F32 t = face.mDistance / rayLen;
  1261. if( t < 0.0f || t > 1.0f )
  1262. return false;
  1263. if( t <= info->t )
  1264. {
  1265. info->t = t;
  1266. // Calculate the normal.
  1267. Opcode::VertexPointers vp;
  1268. mOptTree->GetMeshInterface()->GetTriangle( vp, face.mFaceID );
  1269. if ( materials && vp.MatIdx >= 0 && vp.MatIdx < materials->size() )
  1270. info->material = materials->getMaterialInst( vp.MatIdx );
  1271. // Get the two edges.
  1272. IceMaths::Point baseVert = *vp.Vertex[0];
  1273. IceMaths::Point a = *vp.Vertex[1] - baseVert;
  1274. IceMaths::Point b = *vp.Vertex[2] - baseVert;
  1275. IceMaths::Point n;
  1276. n.Cross( a, b );
  1277. n.Normalize();
  1278. info->normal.set( n.x, n.y, n.z );
  1279. // generate UV coordinate across mesh based on
  1280. // matching normals, this isn't done by default and is
  1281. // primarily of interest in matching a collision point to
  1282. // either a GUI control coordinate or finding a hit pixel in texture space
  1283. if (info->generateTexCoord)
  1284. {
  1285. baseVert = *vp.Vertex[0];
  1286. a = *vp.Vertex[1];
  1287. b = *vp.Vertex[2];
  1288. Point3F facePoint = (1.0f - face.mU - face.mV) * Point3F(baseVert.x, baseVert.y, baseVert.z)
  1289. + face.mU * Point3F(a.x, a.y, a.z) + face.mV * Point3F(b.x, b.y, b.z);
  1290. U32 faces[1024];
  1291. U32 numFaces = 0;
  1292. for (U32 i = 0; i < mOptTree->GetMeshInterface()->GetNbTriangles(); i++)
  1293. {
  1294. if ( i == face.mFaceID )
  1295. {
  1296. faces[numFaces++] = i;
  1297. }
  1298. else
  1299. {
  1300. IceMaths::Point n2;
  1301. mOptTree->GetMeshInterface()->GetTriangle( vp, i );
  1302. baseVert = *vp.Vertex[0];
  1303. a = *vp.Vertex[1] - baseVert;
  1304. b = *vp.Vertex[2] - baseVert;
  1305. n2.Cross( a, b );
  1306. n2.Normalize();
  1307. F32 eps = .01f;
  1308. if ( mFabs(n.x - n2.x) < eps && mFabs(n.y - n2.y) < eps && mFabs(n.z - n2.z) < eps)
  1309. {
  1310. faces[numFaces++] = i;
  1311. }
  1312. }
  1313. if (numFaces == 1024)
  1314. {
  1315. // too many faces in this collision mesh for UV generation
  1316. return true;
  1317. }
  1318. }
  1319. Point3F min(F32_MAX, F32_MAX, F32_MAX);
  1320. Point3F max(-F32_MAX, -F32_MAX, -F32_MAX);
  1321. for (U32 i = 0; i < numFaces; i++)
  1322. {
  1323. mOptTree->GetMeshInterface()->GetTriangle( vp, faces[i] );
  1324. for ( U32 j =0; j < 3; j++)
  1325. {
  1326. a = *vp.Vertex[j];
  1327. if (a.x < min.x)
  1328. min.x = a.x;
  1329. if (a.y < min.y)
  1330. min.y = a.y;
  1331. if (a.z < min.z)
  1332. min.z = a.z;
  1333. if (a.x > max.x)
  1334. max.x = a.x;
  1335. if (a.y > max.y)
  1336. max.y = a.y;
  1337. if (a.z > max.z)
  1338. max.z = a.z;
  1339. }
  1340. }
  1341. // slerp
  1342. Point3F divSafe = (max - min);
  1343. if (divSafe.x == 0.0f) divSafe.x = POINT_EPSILON;
  1344. if (divSafe.y == 0.0f) divSafe.y = POINT_EPSILON;
  1345. if (divSafe.z == 0.0f) divSafe.z = POINT_EPSILON;
  1346. Point3F s = ( (max - min) - (facePoint - min) ) / divSafe;
  1347. // compute axis
  1348. S32 bestAxis = 0;
  1349. F32 best = 0.f;
  1350. for (U32 i = 0 ; i < 6 ; i++)
  1351. {
  1352. F32 dot = mDot (info->normal, texGenAxis[i*3]);
  1353. if (dot > best)
  1354. {
  1355. best = dot;
  1356. bestAxis = i;
  1357. }
  1358. }
  1359. Point3F xv = texGenAxis[bestAxis*3+1];
  1360. Point3F yv = texGenAxis[bestAxis*3+2];
  1361. S32 sv, tv;
  1362. if (xv.x)
  1363. sv = 0;
  1364. else if (xv.y)
  1365. sv = 1;
  1366. else
  1367. sv = 2;
  1368. if (yv.x)
  1369. tv = 0;
  1370. else if (yv.y)
  1371. tv = 1;
  1372. else
  1373. tv = 2;
  1374. // handle coord translation
  1375. if (bestAxis == 2 || bestAxis == 3)
  1376. {
  1377. S32 x = sv;
  1378. sv = tv;
  1379. tv = x;
  1380. if (yv.z < 0)
  1381. s[sv] = 1.f - s[sv];
  1382. }
  1383. if (bestAxis < 2)
  1384. {
  1385. if (yv.y < 0)
  1386. s[sv] = 1.f - s[sv];
  1387. }
  1388. if (bestAxis > 3)
  1389. {
  1390. s[sv] = 1.f - s[sv];
  1391. if (yv.z > 0)
  1392. s[tv] = 1.f - s[tv];
  1393. }
  1394. // done!
  1395. info->texCoord.set(s[sv], s[tv]);
  1396. }
  1397. return true;
  1398. }
  1399. return false;
  1400. }