index.html 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
  5. <meta http-equiv="X-UA-Compatible" content="IE=11"/>
  6. <meta name="generator" content="Doxygen 1.12.0"/>
  7. <meta name="viewport" content="width=device-width, initial-scale=1"/>
  8. <title>Jolt Physics: Jolt Physics</title>
  9. <link href="tabs.css" rel="stylesheet" type="text/css"/>
  10. <script type="text/javascript" src="jquery.js"></script>
  11. <script type="text/javascript" src="dynsections.js"></script>
  12. <script type="text/javascript" src="clipboard.js"></script>
  13. <link href="navtree.css" rel="stylesheet" type="text/css"/>
  14. <script type="text/javascript" src="navtreedata.js"></script>
  15. <script type="text/javascript" src="navtree.js"></script>
  16. <script type="text/javascript" src="resize.js"></script>
  17. <script type="text/javascript" src="cookie.js"></script>
  18. <link href="search/search.css" rel="stylesheet" type="text/css"/>
  19. <script type="text/javascript" src="search/searchdata.js"></script>
  20. <script type="text/javascript" src="search/search.js"></script>
  21. <script type="text/x-mathjax-config">
  22. MathJax.Hub.Config({
  23. extensions: ["tex2jax.js"],
  24. jax: ["input/TeX","output/HTML-CSS"],
  25. });
  26. </script>
  27. <script type="text/javascript" async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js"></script>
  28. <link href="doxygen.css" rel="stylesheet" type="text/css" />
  29. </head>
  30. <body>
  31. <div id="top"><!-- do not remove this div, it is closed by doxygen! -->
  32. <div id="titlearea">
  33. <table cellspacing="0" cellpadding="0">
  34. <tbody>
  35. <tr id="projectrow">
  36. <td id="projectlogo"><img alt="Logo" src="LogoSmall.png"/></td>
  37. <td id="projectalign">
  38. <div id="projectname">Jolt Physics
  39. </div>
  40. <div id="projectbrief">A multi core friendly Game Physics Engine</div>
  41. </td>
  42. </tr>
  43. </tbody>
  44. </table>
  45. </div>
  46. <!-- end header part -->
  47. <!-- Generated by Doxygen 1.12.0 -->
  48. <script type="text/javascript">
  49. /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
  50. var searchBox = new SearchBox("searchBox", "search/",'.html');
  51. /* @license-end */
  52. </script>
  53. <script type="text/javascript">
  54. /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
  55. $(function() { codefold.init(0); });
  56. /* @license-end */
  57. </script>
  58. <script type="text/javascript" src="menudata.js"></script>
  59. <script type="text/javascript" src="menu.js"></script>
  60. <script type="text/javascript">
  61. /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
  62. $(function() {
  63. initMenu('',true,false,'search.php','Search',true);
  64. $(function() { init_search(); });
  65. });
  66. /* @license-end */
  67. </script>
  68. <div id="main-nav"></div>
  69. </div><!-- top -->
  70. <div id="side-nav" class="ui-resizable side-nav-resizable">
  71. <div id="nav-tree">
  72. <div id="nav-tree-contents">
  73. <div id="nav-sync" class="sync"></div>
  74. </div>
  75. </div>
  76. <div id="splitbar" style="-moz-user-select:none;"
  77. class="ui-resizable-handle">
  78. </div>
  79. </div>
  80. <script type="text/javascript">
  81. /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
  82. $(function(){initNavTree('index.html',''); initResizable(true); });
  83. /* @license-end */
  84. </script>
  85. <div id="doc-content">
  86. <!-- window showing the filter options -->
  87. <div id="MSearchSelectWindow"
  88. onmouseover="return searchBox.OnSearchSelectShow()"
  89. onmouseout="return searchBox.OnSearchSelectHide()"
  90. onkeydown="return searchBox.OnSearchSelectKey(event)">
  91. </div>
  92. <!-- iframe showing the search results (closed by default) -->
  93. <div id="MSearchResultsWindow">
  94. <div id="MSearchResults">
  95. <div class="SRPage">
  96. <div id="SRIndex">
  97. <div id="SRResults"></div>
  98. <div class="SRStatus" id="Loading">Loading...</div>
  99. <div class="SRStatus" id="Searching">Searching...</div>
  100. <div class="SRStatus" id="NoMatches">No Matches</div>
  101. </div>
  102. </div>
  103. </div>
  104. </div>
  105. <div><div class="header">
  106. <div class="headertitle"><div class="title">Jolt Physics </div></div>
  107. </div><!--header-->
  108. <div class="contents">
  109. <div class="toc"><h3>Table of Contents</h3>
  110. <ul>
  111. <li class="level1">
  112. <a href="#architecture-jolt-physics">Architecture of Jolt Physics</a>
  113. </li>
  114. <li class="level1">
  115. <a href="#getting-started">Getting Started</a>
  116. </li>
  117. <li class="level1">
  118. <a href="#bodies">Bodies</a>
  119. <ul>
  120. <li class="level2">
  121. <a href="#body-types">Types</a>
  122. </li>
  123. <li class="level2">
  124. <a href="#creating-bodies">Creating Bodies</a>
  125. </li>
  126. <li class="level2">
  127. <a href="#multi-threaded-access">Multithreaded Access</a>
  128. </li>
  129. <li class="level2">
  130. <a href="#single-threaded-access">Single Threaded Access</a>
  131. </li>
  132. <li class="level2">
  133. <a href="#shapes">Shapes</a>
  134. <ul>
  135. <li class="level3">
  136. <a href="#dynamic-mesh-shapes">Dynamic Mesh Shapes</a>
  137. </li>
  138. <li class="level3">
  139. <a href="#creating-shapes">Creating Shapes</a>
  140. </li>
  141. <li class="level3">
  142. <a href="#saving-shapes">Saving Shapes</a>
  143. </li>
  144. <li class="level3">
  145. <a href="#convex-radius">Convex Radius</a>
  146. </li>
  147. <li class="level3">
  148. <a href="#center-of-mass">Center of Mass</a>
  149. </li>
  150. <li class="level3">
  151. <a href="#scaling-shapes">Scaling Shapes</a>
  152. </li>
  153. <li class="level3">
  154. <a href="#creating-custom-shapes">Creating Custom Shapes</a>
  155. </li>
  156. </ul>
  157. </li>
  158. <li class="level2">
  159. <a href="#sensors">Sensors</a>
  160. </li>
  161. <li class="level2">
  162. <a href="#sleeping-bodies">Sleeping</a>
  163. </li>
  164. <li class="level2">
  165. <a href="#soft-bodies">Soft Bodies</a>
  166. <ul>
  167. <li class="level3">
  168. <a href="#soft-body-contact-listener">Soft Body Contact Listeners</a>
  169. </li>
  170. <li class="level3">
  171. <a href="#skinning-soft-bodies">Skinning Soft Bodies</a>
  172. </li>
  173. <li class="level3">
  174. <a href="#soft-body-wip">Soft Body Work In Progress</a>
  175. </li>
  176. </ul>
  177. </li>
  178. </ul>
  179. </li>
  180. <li class="level1">
  181. <a href="#constraints">Constraints</a>
  182. <ul>
  183. <li class="level2">
  184. <a href="#constraint-motors">Constraint Motors</a>
  185. </li>
  186. <li class="level2">
  187. <a href="#breakable-constraints">Breakable Constraints</a>
  188. </li>
  189. </ul>
  190. </li>
  191. <li class="level1">
  192. <a href="#collision-detection">Collision Detection</a>
  193. <ul>
  194. <li class="level2">
  195. <a href="#broad-phase">Broad Phase</a>
  196. </li>
  197. <li class="level2">
  198. <a href="#narrow-phase">Narrow Phase</a>
  199. </li>
  200. <li class="level2">
  201. <a href="#collision-filtering">Collision Filtering</a>
  202. </li>
  203. <li class="level2">
  204. <a href="#level-of-detail">Level of Detail</a>
  205. </li>
  206. <li class="level2">
  207. <a href="#continuous-collision-detection">Continuous Collision Detection</a>
  208. </li>
  209. <li class="level2">
  210. <a href="#ghost-collisions">Ghost Collisions</a>
  211. </li>
  212. </ul>
  213. </li>
  214. <li class="level1">
  215. <a href="#character-controllers">Character Controllers</a>
  216. </li>
  217. <li class="level1">
  218. <a href="#the-simulation-step">The Simulation Step</a>
  219. </li>
  220. <li class="level1">
  221. <a href="#conventions-and-limits">Conventions and Limits</a>
  222. </li>
  223. <li class="level1">
  224. <a href="#big-worlds">Big Worlds</a>
  225. </li>
  226. <li class="level1">
  227. <a href="#space-simulations">Space Simulations</a>
  228. </li>
  229. <li class="level1">
  230. <a href="#deterministic-simulation">Deterministic Simulation</a>
  231. </li>
  232. <li class="level1">
  233. <a href="#rolling-back-a-simulation">Rolling Back a Simulation</a>
  234. </li>
  235. <li class="level1">
  236. <a href="#sloppy-determinism">Being Sloppy While Still Being Deterministic</a>
  237. </li>
  238. <li class="level1">
  239. <a href="#working-with-multiple-physics-systems">Working With Multiple Physics Systems</a>
  240. </li>
  241. <li class="level1">
  242. <a href="#debug-rendering">Debug Rendering</a>
  243. </li>
  244. <li class="level1">
  245. <a href="#memory-management">Memory Management</a>
  246. </li>
  247. <li class="level1">
  248. <a href="#the-simulation-step-in-detail">The Simulation Step in Detail</a>
  249. <ul>
  250. <li class="level2">
  251. <a href="#broad-phase-update-prepare">Broad Phase Update Prepare</a>
  252. </li>
  253. <li class="level2">
  254. <a href="#broad-phase-update-finalize">Broad Phase Update Finalize</a>
  255. </li>
  256. <li class="level2">
  257. <a href="#step-listeners-update">Step Listeners</a>
  258. </li>
  259. <li class="level2">
  260. <a href="#apply-gravity-update">Apply Gravity</a>
  261. </li>
  262. <li class="level2">
  263. <a href="#determine-active-constraints">Determine Active Constraints</a>
  264. </li>
  265. <li class="level2">
  266. <a href="#build-islands-from-constraints">Build Islands from Constraints</a>
  267. </li>
  268. <li class="level2">
  269. <a href="#find-collisions">Find Collisions</a>
  270. </li>
  271. <li class="level2">
  272. <a href="#setup-velocity-constraints">Setup Velocity Constraints</a>
  273. </li>
  274. <li class="level2">
  275. <a href="#finalize-islands">Finalize Islands</a>
  276. </li>
  277. <li class="level2">
  278. <a href="#set-body-island-idx">Set Body Island Idx</a>
  279. </li>
  280. <li class="level2">
  281. <a href="#solve-velocity-constraints">Solve Velocity Constraints</a>
  282. </li>
  283. <li class="level2">
  284. <a href="#pre-integrate">Pre Integrate</a>
  285. </li>
  286. <li class="level2">
  287. <a href="#integrate-and-clamp-velocities">Integrate &amp; Clamp Velocities</a>
  288. </li>
  289. <li class="level2">
  290. <a href="#post-integrate">Post Integrate</a>
  291. </li>
  292. <li class="level2">
  293. <a href="#find-ccd-contacts">Find CCD Contacts</a>
  294. </li>
  295. <li class="level2">
  296. <a href="#resolve-ccd-contacts">Resolve CCD Contacts</a>
  297. </li>
  298. <li class="level2">
  299. <a href="#finalize-contact-cache">Finalize Contact Cache, Contact Removed Callbacks</a>
  300. </li>
  301. <li class="level2">
  302. <a href="#solve-position-constraints">Solve Position Constraints, Update Bodies Broad Phase</a>
  303. </li>
  304. <li class="level2">
  305. <a href="#soft-body-prepare">Soft Body Prepare</a>
  306. </li>
  307. <li class="level2">
  308. <a href="#soft-body-collide">Soft Body Collide</a>
  309. </li>
  310. <li class="level2">
  311. <a href="#soft-body-simulate">Soft Body Simulate</a>
  312. </li>
  313. <li class="level2">
  314. <a href="#soft-body-finalize">Soft Body Finalize</a>
  315. </li>
  316. </ul>
  317. </li>
  318. </ul>
  319. </div>
  320. <div class="textblock"><p><a class="anchor" id="md__docs_2_architecture"></a></p>
  321. <h1><a class="anchor" id="architecture-jolt-physics"></a>
  322. Architecture of Jolt Physics</h1>
  323. <h1><a class="anchor" id="getting-started"></a>
  324. Getting Started</h1>
  325. <p>To get started, look at the <a href="https://github.com/jrouwe/JoltPhysics/blob/master/HelloWorld/HelloWorld.cpp">HelloWorld</a> example. A <a href="https://github.com/jrouwe/JoltPhysicsHelloWorld">HelloWorld example using CMake FetchContent</a> is also available to show how you can integrate Jolt Physics in a CMake project.</p>
  326. <p>Every feature in Jolt has its own sample. <a class="el" href="md__docs_2_samples.html">Running the Samples application</a> and browsing through the <a href="https://github.com/jrouwe/JoltPhysics/tree/master/Samples/Tests">code</a> is a great way to learn about the library!</p>
  327. <p>The rest of this document describes the concepts used in Jolt in more detail.</p>
  328. <h1><a class="anchor" id="bodies"></a>
  329. Bodies</h1>
  330. <p>We use a pretty traditional physics engine setup, so <a class="el" href="class_body.html">bodies</a> in our simulation are objects which have attached collision <a class="el" href="class_shape.html">shapes</a></p>
  331. <h2><a class="anchor" id="body-types"></a>
  332. Types</h2>
  333. <p>Bodies can either be:</p><ul>
  334. <li><a class="el" href="_motion_type_8h.html#a328245ddbb758681fad3c44c9d488fd8">static</a> (not moving or simulating)</li>
  335. <li><a class="el" href="_motion_type_8h.html#a328245ddbb758681fad3c44c9d488fd8">dynamic</a> (moved by forces) or</li>
  336. <li><a class="el" href="_motion_type_8h.html#a328245ddbb758681fad3c44c9d488fd8">kinematic</a> (moved by velocities only).</li>
  337. </ul>
  338. <p>Moving bodies have a <a class="el" href="class_motion_properties.html">MotionProperties</a> object that contains information about the movement of the object. Static bodies do not have this to save space (but they can be configured to have it if a static body needs to become dynamic during its lifetime by setting <a class="el" href="class_body_creation_settings.html#afe686c8d207fb99499a89e19d1780158">BodyCreationSettings::mAllowDynamicOrKinematic</a>).</p>
  339. <h2><a class="anchor" id="creating-bodies"></a>
  340. Creating Bodies</h2>
  341. <p>Bodies are inserted into the <a class="el" href="class_physics_system.html">PhysicsSystem</a> and interacted with through the <a class="el" href="class_body_interface.html">BodyInterface</a>.</p>
  342. <p>The general life cycle of a body is:</p>
  343. <ul>
  344. <li><a class="el" href="class_body_interface.html#ae0205e33e033e932177183c7b20da0f1">BodyInterface::CreateBody</a> - Construct a <a class="el" href="class_body.html">Body</a> object and initialize it. You cannot use <code>new</code> to create a <a class="el" href="class_body.html">Body</a>.</li>
  345. <li><a class="el" href="class_body_interface.html#a4ba54993b7bbc05f1a6ffccbc46f0397">BodyInterface::AddBody</a> - Add the body to the <a class="el" href="class_physics_system.html">PhysicsSystem</a> and make it participate in the simulation.</li>
  346. <li><a class="el" href="class_body_interface.html#a522d341ddd68225e12eb510f072399f9" title="Remove body from the physics system. Note that you need to add a body to the physics system before yo...">BodyInterface::RemoveBody</a> - Remove it from the <a class="el" href="class_physics_system.html">PhysicsSystem</a>.</li>
  347. <li><a class="el" href="class_body_interface.html#a43fb4ffc35661c67642ffa804d1dad8a">BodyInterface::DestroyBody</a> - Deinitialize and destruct the <a class="el" href="class_body.html">Body</a>. You cannot use <code>delete</code> to delete a <a class="el" href="class_body.html">Body</a>. This function will not automatically remove the <a class="el" href="class_body.html">Body</a> from the <a class="el" href="class_physics_system.html">PhysicsSystem</a>.</li>
  348. </ul>
  349. <p>If you need to add many bodies at the same time then use the batching functions:</p>
  350. <ul>
  351. <li><a class="el" href="class_body_interface.html#aab69381ebd96bc19d152bc8a928e9902">BodyInterface::AddBodiesPrepare</a> - Prepares bodies to be added to the <a class="el" href="class_physics_system.html">PhysicsSystem</a>. Doesn't affect simulation and can be done from a background thread.</li>
  352. <li><a class="el" href="class_body_interface.html#a64e1dd1d09088ca5a07384397f77f0aa">BodyInterface::AddBodiesFinalize</a> - Finalize insertion. This atomically adds all bodies to the <a class="el" href="class_physics_system.html">PhysicsSystem</a>.</li>
  353. <li><a class="el" href="class_body_interface.html#abc4f7a8cfd9e27064365eef9753bfa27">BodyInterface::AddBodiesAbort</a> - If you've called AddBodiesPrepare but changed your mind and no longer want to add the bodies to the <a class="el" href="class_physics_system.html">PhysicsSystem</a>. Useful when streaming in level sections and the player decides to go the other way.</li>
  354. <li><a class="el" href="class_body_interface.html#a4e0007d53ba413e916a527b870b35a87">BodyInterface::RemoveBodies</a> - Batch remove a lot of bodies from the <a class="el" href="class_physics_system.html">PhysicsSystem</a>.</li>
  355. </ul>
  356. <p>Always use the batch adding functions when possible! Adding many bodies, one at a time, results in a really inefficient broadphase (a trace will notify when this happens) and in extreme cases may lead to the broadphase running out of internal nodes (std::abort will be called in that case). If you cannot avoid adding many bodies one at a time, use <a class="el" href="class_physics_system.html#ab3cd9f2562f0f051c032b3bc298d9604">PhysicsSystem::OptimizeBroadPhase</a> to rebuild the tree.</p>
  357. <p>You can call AddBody, RemoveBody, AddBody, RemoveBody to temporarily remove and later reinsert a body into the simulation.</p>
  358. <h2><a class="anchor" id="multi-threaded-access"></a>
  359. Multithreaded Access</h2>
  360. <p>Jolt is designed to be accessed from multiple threads so the body interface comes in two flavors: A locking and a non-locking variant. The locking variant uses a mutex array (a fixed size array of mutexes, bodies are associated with a mutex through hashing and multiple bodies use the same mutex, see <a class="el" href="class_mutex_array.html">MutexArray</a>) to prevent concurrent access to the same body. The non-locking variant doesn't use mutexes, so requires the user to be careful.</p>
  361. <p>In general, body ID's (<a class="el" href="class_body_i_d.html">BodyID</a>) are used to refer to bodies. You can access a body through the following construct: </p><pre class="fragment">JPH::BodyLockInterface lock_interface = physics_system.GetBodyLockInterface(); // Or GetBodyLockInterfaceNoLock
  362. JPH::BodyID body_id = ...; // Obtain ID to body
  363. // Scoped lock
  364. {
  365. JPH::BodyLockRead lock(lock_interface, body_id);
  366. if (lock.Succeeded()) // body_id may no longer be valid
  367. {
  368. const JPH::Body &amp;body = lock.GetBody();
  369. // Do something with body
  370. ...
  371. }
  372. }
  373. </pre><p>When another thread has removed the body between the time the body ID was obtained and the lock, the lock will fail. While the lock is taken, other threads cannot modify the body, so it is safe to work with it. Each body ID contains a sequence number, so body ID's will only be reused after many add/remove cycles. To write to a body use <a class="el" href="class_body_lock_write.html">BodyLockWrite</a>.</p>
  374. <p>You cannot use <a class="el" href="class_body_lock_read.html">BodyLockRead</a> to lock multiple bodies (if two threads lock the same bodies in opposite order you'll get a deadlock). Use <a class="el" href="class_body_lock_multi_read.html">BodyLockMultiRead</a> or <a class="el" href="class_body_lock_multi_write.html">BodyLockMultiWrite</a> to lock them in a consistent order.</p>
  375. <p>Note that a lot of convenience functions are exposed through the <a class="el" href="class_body_interface.html">BodyInterface</a>, but not all functionality is available, so you may need to lock the body to get the pointer and then call the function directly on the body.</p>
  376. <h2><a class="anchor" id="single-threaded-access"></a>
  377. Single Threaded Access</h2>
  378. <p>If you're only accessing the physics system from a single thread, you can use <a class="el" href="class_body.html">Body</a> pointers instead of <a class="el" href="class_body_i_d.html" title="ID of a body. This is a way of reasoning about bodies in a multithreaded simulation while avoiding ra...">BodyID</a>'s. In this case you can also use the non-locking variant of the body interface.</p>
  379. <p>Note that there are still some restrictions:</p>
  380. <ul>
  381. <li>You cannot read from / write to bodies or constraints while <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> is running. As soon as the Update starts, all body / constraint mutexes are locked.</li>
  382. <li>Collision callbacks (see <a class="el" href="class_contact_listener.html">ContactListener</a>) are called from within the <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> call from multiple threads. You can only read the body data during a callback.</li>
  383. <li>Activation callbacks (see <a class="el" href="class_body_activation_listener.html">BodyActivationListener</a>) are called in the same way. Again you should only read the body during the callback and not make any modifications.</li>
  384. <li>Step callbacks (see <a class="el" href="class_physics_step_listener.html" title="A listener class that receives a callback before every physics simulation step.">PhysicsStepListener</a>) are also called from <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> from multiple threads. You're responsible for making sure that there are no race conditions. In a step listener you can read/write bodies or constraints but you cannot add/remove them.</li>
  385. </ul>
  386. <p>If you are accessing the physics system from multiple threads, you should probably use <a class="el" href="class_body_i_d.html" title="ID of a body. This is a way of reasoning about bodies in a multithreaded simulation while avoiding ra...">BodyID</a>'s and the locking variant of the body interface. It is however still possible to use <a class="el" href="class_body.html">Body</a> pointers if you're really careful. E.g. if there is a clear owner of a <a class="el" href="class_body.html">Body</a> and you ensure that this owner does not read/write state during <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> or while other threads are reading the <a class="el" href="class_body.html">Body</a> there will not be any race conditions.</p>
  387. <h2><a class="anchor" id="shapes"></a>
  388. Shapes</h2>
  389. <p>Each body has a shape attached that determines the collision volume. The following shapes are available (in order of computational complexity):</p>
  390. <ul>
  391. <li><a class="el" href="class_sphere_shape.html">SphereShape</a> - A sphere centered around zero.</li>
  392. <li><a class="el" href="class_box_shape.html">BoxShape</a> - A box centered around zero.</li>
  393. <li><a class="el" href="class_capsule_shape.html">CapsuleShape</a> - A capsule centered around zero.</li>
  394. <li><a class="el" href="class_tapered_capsule_shape.html">TaperedCapsuleShape</a> - A capsule with different radii at the bottom and top.</li>
  395. <li><a class="el" href="class_cylinder_shape.html">CylinderShape</a> - A cylinder shape. Note that cylinders are the least stable of all shapes, so use another shape if possible.</li>
  396. <li><a class="el" href="class_tapered_cylinder_shape.html">TaperedCylinderShape</a> - A cylinder with different radii at the bottom and top. Note that cylinders are the least stable of all shapes, so use another shape if possible.</li>
  397. <li><a class="el" href="class_convex_hull_shape.html">ConvexHullShape</a> - A convex hull defined by a set of points.</li>
  398. <li><a class="el" href="class_triangle_shape.html">TriangleShape</a> - A single triangle. Use a <a class="el" href="class_mesh_shape.html">MeshShape</a> if you have multiple triangles.</li>
  399. <li><a class="el" href="class_plane_shape.html">PlaneShape</a> - An infinite plane. Negative half space is considered solid.</li>
  400. <li><a class="el" href="class_static_compound_shape.html">StaticCompoundShape</a> - A shape containing other shapes. This shape is constructed once and cannot be changed afterwards. Child shapes are organized in a tree to speed up collision detection.</li>
  401. <li><a class="el" href="class_mutable_compound_shape.html">MutableCompoundShape</a> - A shape containing other shapes. This shape can be constructed/changed at runtime and trades construction time for runtime performance. Child shapes are organized in a list to make modification easy.</li>
  402. <li><a class="el" href="class_mesh_shape.html">MeshShape</a> - A shape consisting of triangles. They are mostly used for static geometry.</li>
  403. <li><a class="el" href="class_height_field_shape.html">HeightFieldShape</a> - A shape consisting of NxN points that define the height at each point, very suitable for representing hilly terrain. Any body that uses this shape needs to be static.</li>
  404. <li><a class="el" href="class_empty_shape.html">EmptyShape</a> - A shape that collides with nothing and that can be used as a placeholder or for dummy bodies.</li>
  405. </ul>
  406. <p>Next to this there are a number of decorator shapes that change the behavior of their children:</p>
  407. <ul>
  408. <li><a class="el" href="class_scaled_shape.html">ScaledShape</a> - This shape can scale a child shape. Note that if a shape is rotated first and then scaled, you can introduce shearing which is not supported by the library.</li>
  409. <li><a class="el" href="class_rotated_translated_shape.html">RotatedTranslatedShape</a> - This shape can rotate and translate a child shape, it can e.g. be used to offset a sphere from the origin.</li>
  410. <li><a class="el" href="class_offset_center_of_mass_shape.html">OffsetCenterOfMassShape</a> - This shape does not change its child shape but it does shift the calculated center of mass for that shape. It allows you to e.g. shift the center of mass of a vehicle down to improve its handling.</li>
  411. </ul>
  412. <h3><a class="anchor" id="dynamic-mesh-shapes"></a>
  413. Dynamic Mesh Shapes</h3>
  414. <p>Meshes are usually static, but they can be made kinematic or dynamic provided that they don't collide with other mesh- or heightfield shapes (an assert will trigger when this happens and the collision will be ignored).</p>
  415. <p>Mesh shapes also cannot calculate their mass and inertia, so when you want a dynamic mesh, you need to provide these yourself by setting <a class="el" href="class_body_creation_settings.html#aaefa0f471f73fbfaf0f288e56e20b384" title="Determines how mMassPropertiesOverride will be used.">BodyCreationSettings::mOverrideMassProperties</a> = <a class="el" href="_body_creation_settings_8h.html#a758835911f67742d0ad74841f6bdbe38a851f1413e004fb968effbb7c8e8d5965" title="Tells the system to take the mass and inertia from mMassPropertiesOverride.">EOverrideMassProperties::MassAndInertiaProvided</a> and supplying the mass and inertia in <a class="el" href="class_body_creation_settings.html#af7f022cb3042750da187b24e8a242c99" title="Contains replacement mass settings which override the automatically calculated values.">BodyCreationSettings::mMassPropertiesOverride</a>.</p>
  416. <p>An example can be found <a href="https://github.com/jrouwe/JoltPhysics/blob/master/Samples/Tests/General/DynamicMeshTest.cpp">here</a>.</p>
  417. <p>Note that you should try to avoid dynamic mesh shapes as they are fairly expensive to simulate. Also, mesh shapes don't have a clear inside/outside so a mesh is only considered to be colliding when one of its triangles intersect with the other object. This can result in objects getting stuck inside the mesh without knowing which way is out.</p>
  418. <h3><a class="anchor" id="creating-shapes"></a>
  419. Creating Shapes</h3>
  420. <p>Simple shapes like spheres and boxes can be constructed immediately by simply new-ing them. Other shapes need to be converted into an optimized format in order to be usable in the physics simulation. The uncooked data is usually stored in a <a class="el" href="class_shape_settings.html">ShapeSettings</a> object and then converted to cooked format by a <a class="el" href="class_shape_settings.html#a21e53b5758542a5527c7941d61d838fa">Create</a> function that returns a <a class="el" href="class_result.html">Result</a> object that indicates success or failure and provides the cooked object.</p>
  421. <p>Creating a convex hull for example looks like: </p><pre class="fragment">// Shapes are refcounted and can be shared between bodies
  422. JPH::Ref&lt;Shape&gt; shape;
  423. // The ShapeSettings object is only required for building the shape, all information is copied into the Shape class
  424. {
  425. // Create an array of vertices
  426. JPH::Array&lt;JPH::Vec3&gt; vertices = { ... };
  427. // Create the settings object for a convex hull
  428. JPH::ConvexHullShapeSettings settings(vertices, JPH::cDefaultConvexRadius);
  429. // Create shape
  430. JPH::Shape::ShapeResult result = settings.Create();
  431. if (result.IsValid())
  432. shape = result.Get();
  433. else
  434. ... // Error handling
  435. }
  436. </pre><p>Note that after you call Create, the shape is cached and <a class="el" href="class_shape_settings.html">ShapeSettings</a> keeps a reference to your shape (see <a class="el" href="#memory-management">Memory Management</a>). If you call Create again, the same shape will be returned regardless of what changed to the settings object (unless you call <a class="el" href="class_shape_settings.html#aa965a759e6c4cbc43ebf0aa8bd1f2d30">ClearCachedResult</a> to clear the cache).</p>
  437. <h3><a class="anchor" id="saving-shapes"></a>
  438. Saving Shapes</h3>
  439. <p>There are two ways of serializing data:</p>
  440. <ul>
  441. <li>The uncooked data can be serialized using the <a class="el" href="class_object_stream.html">ObjectStream</a> system (either in <a class="el" href="class_object_stream_binary_out.html">binary</a> or in <a class="el" href="class_object_stream_text_out.html">text</a> format), data stored in this way is likely to be compatible with future versions of the library (although there is no 100% guarantee of this).</li>
  442. <li>The cooked data can be serialized using the <a class="el" href="class_shape.html#a0035a8aa07e9e071f6a64edb45146363">SaveBinaryState</a> interface that various objects provide. Data stored in this way is optimized for simulation performance and loading speed but is very likely to change between versions of the library, so this should never be your primary data format.</li>
  443. </ul>
  444. <p>An example of saving a shape in binary format: </p><pre class="fragment">// Create a sphere of radius 1
  445. JPH::Ref&lt;Shape&gt; sphere = new JPH::SphereShape(1.0f);
  446. // For this example we'll be saving the shape in a STL string stream, but if you implement StreamOut you don't have to use STL.
  447. // Note that this will be storing a binary string of bytes that can contain 0-bytes, it is not an ASCII string!
  448. stringstream data;
  449. JPH::StreamOutWrapper stream_out(data);
  450. // Save the shape (note this function handles CompoundShape too).
  451. // The maps are there to avoid saving the same shape twice (it will assign an ID to each shape the first time it encounters them).
  452. // If you don't want certain shapes to be saved, add them to the map and give them an ID.
  453. // You can save many shapes to the same stream by repeatedly calling SaveWithChildren on different shapes.
  454. JPH::Shape::ShapeToIDMap shape_to_id;
  455. JPH::Shape::MaterialToIDMap material_to_id;
  456. sphere-&gt;SaveWithChildren(stream_out, shape_to_id, material_to_id);
  457. // Wrap the STL stream in a StreamIn
  458. JPH::StreamInWrapper stream_in(data);
  459. // Load the shape
  460. // If you have assigned custom ID's on save, you need to ensure that the shapes exist in this map on restore too.
  461. JPH::Shape::IDToShapeMap id_to_shape;
  462. JPH::Shape::IDToMaterialMap id_to_material;
  463. JPH::Shape::ShapeResult result = JPH::Shape::sRestoreWithChildren(stream_in, id_to_shape, id_to_material);
  464. JPH::Ref&lt;Shape&gt; restored_shape;
  465. if (result.IsValid())
  466. restored_shape = result.Get();
  467. else
  468. ... // Error handling
  469. </pre><p>As the library does not offer an exporter from content creation packages and since most games will have their own content pipeline, we encourage you to store data in your own format, cook data while cooking the game data and store the result using the SaveBinaryState interface (and provide a way to force a re-cook when the library is updated).</p>
  470. <p>A possible pattern for serializing binary data in your own engine could be:</p>
  471. <ul>
  472. <li>EngineBody at runtime creates a <a class="el" href="class_body.html">Body</a>. Note that the prefix 'Engine' means that it's a class in your own engine.</li>
  473. <li>It links to an EngineShape, which wraps a <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a>.</li>
  474. <li>EngineShape comes in different flavors, e.g. EngineMeshShape, EngineSphereShape etc.</li>
  475. <li>EngineMeshShape contains the uncompressed mesh data (in a format that's editable in your tools).</li>
  476. <li>When 'cooking' the game data:<ul>
  477. <li>Create a <a class="el" href="class_mesh_shape.html">MeshShape</a>.</li>
  478. <li>Save it using <a class="el" href="class_shape.html#a29511616de01507e714e8187686bc9f1" title="Save this shape, all its children and its materials. Pass in an empty map in ioShapeMap / ioMaterialM...">Shape::SaveWithChildren</a> in a binary blob that's associated with the EngineMeshShape (could be in an attribute that's an array of bytes).</li>
  479. <li>Throw away the uncompressed mesh data.</li>
  480. </ul>
  481. </li>
  482. <li>When loading the EngineMeshShape using your own serialization system, also restore the <a class="el" href="class_mesh_shape.html">MeshShape</a> from the binary blob using <a class="el" href="class_shape.html#a439b98c1569fb5d44570446306823f5e" title="Restore a shape, all its children and materials. Pass in an empty map in ioShapeMap / ioMaterialMap o...">Shape::sRestoreWithChildren</a>.</li>
  483. <li>Your serialization system should take care that the pointer between EngineBody and EngineShape is restored.</li>
  484. <li>There are some tricks for sharing Shapes, e.g. an EngineCompoundShape links to multiple child EngineShapes:<ul>
  485. <li>At cooking time create a <a class="el" href="class_static_compound_shape.html">StaticCompoundShape</a>.</li>
  486. <li>Before writing the shape to the binary blob with <a class="el" href="class_shape.html#a29511616de01507e714e8187686bc9f1" title="Save this shape, all its children and its materials. Pass in an empty map in ioShapeMap / ioMaterialM...">Shape::SaveWithChildren</a> it inserts all leaf shapes (the <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a> associated with the child EngineShape) in the <a class="el" href="class_shape.html#a5944ae14aeacc70bb42a38d7c3a31220">Shape::ShapeToIDMap</a> so they won't be included in the binary blob.</li>
  487. <li>Before loading the binary blob with <a class="el" href="class_shape.html#a439b98c1569fb5d44570446306823f5e" title="Restore a shape, all its children and materials. Pass in an empty map in ioShapeMap / ioMaterialMap o...">Shape::sRestoreWithChildren</a> prepopulate the <a class="el" href="class_shape.html#a06ba83cf87213a408c508acbc786d2fe">Shape::IDToShapeMap</a> with the pointers to the restored <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a>'s from the child EngineShapes (this again assumes that your own serialization system is capable of restoring the pointers between EngineCompoundShape and the child EntityShapes).</li>
  488. </ul>
  489. </li>
  490. </ul>
  491. <h3><a class="anchor" id="convex-radius"></a>
  492. Convex Radius</h3>
  493. <p>In order to speed up the collision detection system, all convex shapes use a convex radius. The provided shape will first be shrunken by the convex radius and then inflated again by the same amount, resulting in a rounded off shape:</p>
  494. <div class="image">
  495. <img src="ConvexRadius.jpg" alt=""/>
  496. <div class="caption">
  497. In this example a box (green) was created with a fairly large convex radius. The shape is shrunken first (dashed green line) and then inflated again equally on all sides. The resulting shape as seen by the collision detection system is shown in blue. A larger convex radius results in better performance but a less accurate simulation. A convex radius of 0 is allowed.</div></div>
  498. <h3><a class="anchor" id="center-of-mass"></a>
  499. Center of Mass</h3>
  500. <p><b>Beware: When a shape is created, it will automatically recenter itself around its center of mass.</b> The center of mass can be obtained by calling <a class="el" href="class_shape.html#a7e34b0626a40c31db0b2a761922adb1a">Shape::GetCenterOfMass</a> and most functions operate in this Center of Mass (COM) space. Some functions work in the original space the shape was created in, they usually have World Space (WS) or <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a> Space (SS) in their name (or documentation).</p>
  501. <div class="image">
  502. <img src="ShapeCenterOfMass.jpg" alt=""/>
  503. <div class="caption">
  504. Shape Center of Mass</div></div>
  505. <p>As an example, say we create a box and then translate it: </p><pre class="fragment">// Create box of 2x2x2 m (you specify half the side)
  506. JPH::BoxShapeSettings box(JPH::Vec3(1, 1, 1));
  507. JPH::Ref&lt;Shape&gt; box_shape = box.Create().Get();
  508. // Offset it by 10 m
  509. JPH::RotatedTranslatedShapeSettings translated_box(JPH::Vec3(10, 0, 0), JPH::Quat::sIdentity(), box_shape);
  510. JPH::Ref&lt;Shape&gt; translated_box_shape = translated_box.Create().Get();
  511. // Cast a ray against the offset box (WRONG!)
  512. JPH::RayCast ray;
  513. ray.mOrigin = JPH::Vec3(10, 2, 0);
  514. ray.mDirection = JPH::Vec3(0, -2, 0);
  515. // Cast ray
  516. JPH::RayCastResult hit;
  517. bool had_hit = translated_box_shape-&gt;CastRay(ray, JPH::SubShapeIDCreator(), hit);
  518. JPH_ASSERT(!had_hit); // There's no hit because we did not correct for COM!
  519. // Convert the ray to center of mass space for the shape (CORRECT!)
  520. ray.mOrigin -= translated_box_shape-&gt;GetCenterOfMass();
  521. // Cast ray
  522. had_hit = translated_box_shape-&gt;CastRay(ray, JPH::SubShapeIDCreator(), hit);
  523. JPH_ASSERT(had_hit); // Ray was in COM space, now there's a hit!
  524. </pre><p>In the same way calling: </p><pre class="fragment">translated_box_shape-&gt;GetLocalBounds();
  525. </pre><p>will return a box of size 2x2x2 centered around the origin, so in order to get it back to the space in which it was originally created you need to offset the bounding box: </p><pre class="fragment">JPH::AABox shape_bounds = translated_box_shape-&gt;GetLocalBounds();
  526. shape_bounds.Translate(translated_box_shape-&gt;GetCenterOfMass());
  527. JPH_ASSERT(shape_bounds == JPH::AABox(JPH::Vec3(9, -1, -1), JPH::Vec3(11, 1, 1))); // Now we have the box relative to how we created it
  528. </pre><p>Note that when you work with interface of <a class="el" href="class_broad_phase_query.html">BroadPhaseQuery</a>, <a class="el" href="class_narrow_phase_query.html">NarrowPhaseQuery</a> or <a class="el" href="class_transformed_shape.html">TransformedShape</a> this transformation is done for you.</p>
  529. <h3><a class="anchor" id="scaling-shapes"></a>
  530. Scaling Shapes</h3>
  531. <p>Shapes can be scaled using the <a class="el" href="class_scaled_shape.html">ScaledShape</a> class. You can scale a shape like: </p><pre class="fragment">JPH::RefConst&lt;Shape&gt; my_scaled_shape = new JPH::ScaledShape(my_non_scaled_shape, JPH::Vec3(x_scale, y_scale, z_scale));
  532. </pre><p>Not all scales are valid for every shape. Use <a class="el" href="class_shape.html#a59f32110193561295a7d721909e07adc">Shape::IsValidScale</a> to check if a scale is valid for a particular shape (the documentation for this function also lists the rules for all shape types).</p>
  533. <p>A safer way of scaling shapes is provided by the <a class="el" href="class_shape.html#ae4a0954ec23eabd48f0961b16eff750a">Shape::ScaleShape</a> function: </p><pre class="fragment">JPH::Shape::ShapeResult my_scaled_shape = my_non_scaled_shape-&gt;ScaleShape(JPH::Vec3(x_scale, y_scale, z_scale));
  534. </pre><p>This function will check if a scale is valid for a particular shape and if a scale is not valid, it will produce the closest scale that is valid. For example, if you scale a <a class="el" href="class_compound_shape.html" title="Base class for a compound shape.">CompoundShape</a> that has rotated sub shapes, a non-uniform scale would cause shearing. In that case the <a class="el" href="class_shape.html#ae4a0954ec23eabd48f0961b16eff750a">Shape::ScaleShape</a> function will create a new compound shape and scale the sub shapes (losing the shear) rather than creating a <a class="el" href="class_scaled_shape.html" title="A shape that scales a child shape in local space of that shape. The scale can be non-uniform and can ...">ScaledShape</a> around the entire <a class="el" href="class_compound_shape.html" title="Base class for a compound shape.">CompoundShape</a>.</p>
  535. <p>Updating scaling after a body is created is also possible, but should be done with care. Imagine a sphere in a pipe, scaling the sphere so that it becomes bigger than the pipe creates an impossible situation as there is no way to resolve the collision anymore. Please take a look at the <a href="https://github.com/jrouwe/JoltPhysics/blob/master/Samples/Tests/ScaledShapes/DynamicScaledShape.cpp">DynamicScaledShape</a> demo. The reason that no ScaledShape::SetScale function exists is to ensure thread safety when collision queries are being executed while shapes are modified.</p>
  536. <p>Note that there are many functions that take a scale in Jolt (e.g. <a class="el" href="class_collision_dispatch.html#a29634d08db5d24ce7c0d5c44b547c075">CollisionDispatch::sCollideShapeVsShape</a>), usually the shape is scaled relative to its center of mass. The <a class="el" href="class_shape.html#ae4a0954ec23eabd48f0961b16eff750a">Shape::ScaleShape</a> function scales the shape relative to the origin of the shape.</p>
  537. <h3><a class="anchor" id="creating-custom-shapes"></a>
  538. Creating Custom Shapes</h3>
  539. <p>If the defined <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a> classes are not sufficient, or if your application can make a more efficient implementation because it has specific domain knowledge, it is possible to create a custom collision shape:</p>
  540. <ul>
  541. <li>Derive a new class from <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a> (e.g. MyShape). If your shape is convex you can consider deriving from <a class="el" href="class_convex_shape.html" title="Base class for all convex shapes. Defines a virtual interface.">ConvexShape</a>, if it contains multiple sub shapes you can derive from <a class="el" href="class_compound_shape.html" title="Base class for a compound shape.">CompoundShape</a> or if it wraps a single other shape it can be derived from <a class="el" href="class_decorated_shape.html" title="Base class for shapes that decorate another shape with extra functionality (e.g. scale,...">DecoratedShape</a>.</li>
  542. <li>Create a settings class that configures your shape (e.g. MyShapeSettings) and inherit it from the corresponding settings class (e.g. <a class="el" href="class_shape_settings.html">ShapeSettings</a>, <a class="el" href="class_compound_shape_settings.html" title="Base class settings to construct a compound shape.">CompoundShapeSettings</a> or <a class="el" href="class_decorated_shape_settings.html" title="Class that constructs a DecoratedShape.">DecoratedShapeSettings</a>).</li>
  543. <li>Override the <code>MyShapeSettings::Create</code> function to construct an instance of MyShape.</li>
  544. <li>If you want to serialize the settings class, register it with the factory: <code><a class="el" href="class_factory.html#afdbac3e3e59f7981d7dec696e914e69f" title="Singleton factory instance.">Factory::sInstance</a>-&gt;Register(RTTI_OF(MyShapeSettings))</code></li>
  545. <li>If you inherited from <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a> you need to select a shape type, use e.g. <code><a class="el" href="_shape_8h.html#ad64a1c665070a3100e456e54073554a5a6b908b785fdba05a6446347dae08d8c5">EShapeType::User1</a></code></li>
  546. <li>In all cases you will need to specify a sub shape type, use e.g. <code><a class="el" href="_shape_8h.html#aa332e0529e75b83aad91881c8d32551ba6b908b785fdba05a6446347dae08d8c5">EShapeSubType::User1</a></code></li>
  547. <li>If you inherited from <a class="el" href="class_convex_shape.html" title="Base class for all convex shapes. Defines a virtual interface.">ConvexShape</a> you can also specify a convex sub shape type, e.g. <code><a class="el" href="_shape_8h.html#aa332e0529e75b83aad91881c8d32551ba56ee3e0d63e9daae01eaf439a3dafab4">EShapeSubType::UserConvex1</a></code>, in which case you don't need to implement or register the collision detection functions mentioned below.</li>
  548. <li>Implement the virtual functions that your selected base class exposes. Some functions could be implemented as a dummy if you don't care about the functionality, e.g. if you don't care about buoyancy then GetSubmergedVolume does not need to be implemented.</li>
  549. <li>Create a <code>MyShape::sRegister()</code> function to register all collision functions, make sure you call this function after calling <code><a class="el" href="_register_types_8h.html#a033e662bc8b7d5a8acd9adcc692b7cb4">RegisterTypes()</a></code>, see <a class="el" href="class_mesh_shape.html#a7c65cb780134f5d289b977dab3993e5b">MeshShape::sRegister</a> for an example.</li>
  550. <li>Now write collision detection functions to test collision with all other shape types that this shape could collide with and register them with <a class="el" href="class_collision_dispatch.html#a20d56fd7360a0b72be7803eef2d616ed">CollisionDispatch::sRegisterCollideShape</a> and <a class="el" href="class_collision_dispatch.html#a211b05424a9e6e7bff777af77edad6be">CollisionDispatch::sRegisterCastShape</a>. This can be a lot of work, but there are some helper functions that you can use to reduce the work:<ul>
  551. <li>If you have implemented a collision test for type A vs B then you can register <a class="el" href="class_collision_dispatch.html#a559aa7de19de882317f52329f88182ea">CollisionDispatch::sReversedCastShape</a> and <a class="el" href="class_collision_dispatch.html#a931dfb0bf6aeeed8acc7d6c6907f903b">CollisionDispatch::sReversedCollideShape</a> for B vs A.</li>
  552. <li>If your shape is triangle based, you can forward the testing of a shape vs a single triangle to the <a class="el" href="class_collide_convex_vs_triangles.html">CollideConvexVsTriangles</a> and <a class="el" href="class_cast_convex_vs_triangles.html">CastConvexVsTriangles</a> classes.</li>
  553. <li>If your shape contains sub shapes and you have determined that the shape intersects with one of the sub shapes you can forward the sub shape to the collision dispatch again through <a class="el" href="class_collision_dispatch.html#a29634d08db5d24ce7c0d5c44b547c075">CollisionDispatch::sCollideShapeVsShape</a> and <a class="el" href="class_collision_dispatch.html#a684c783f79569805d64cd436800b1d2a">CollisionDispatch::sCastShapeVsShapeLocalSpace</a>.</li>
  554. </ul>
  555. </li>
  556. </ul>
  557. <h2><a class="anchor" id="sensors"></a>
  558. Sensors</h2>
  559. <p>Sensors are normal rigid bodies that report contacts with other Dynamic or Kinematic bodies through the <a class="el" href="class_contact_listener.html">ContactListener</a> interface. Any detected penetrations will however not be resolved. Sensors can be used to implement triggers that detect when an object enters their area.</p>
  560. <p>The cheapest sensor has a Static motion type. This type of sensor will only detect active bodies entering their area. As soon as a body goes to sleep, the contact will be lost. Note that you can still move a Static sensor around using <a class="el" href="class_body_interface.html#a19838143d494d7d0ddb4fb0226ca2cad">BodyInterface::SetPosition</a>.</p>
  561. <p>When you make a sensor Kinematic or Dynamic and activate it, it will also detect collisions with sleeping bodies, albeit with a higher run-time cost.</p>
  562. <p>To create a sensor, either set <a class="el" href="class_body_creation_settings.html#ad327b3b479e63fe5bfbecf0510d69d44">BodyCreationSettings::mIsSensor</a> to true when constructing a body or set it after construction through <a class="el" href="class_body.html#a5d8e1f66eed163868a633cdb93859f77">Body::SetIsSensor</a>. A sensor can only use the discrete motion quality type at this moment.</p>
  563. <p>To make sensors detect collisions with static objects, set the <a class="el" href="class_body_creation_settings.html#a824e71e8ce2673afc3a7716411016ee6">BodyCreationSettings::mCollideKinematicVsNonDynamic</a> to true or call <a class="el" href="class_body.html#adefe521957195c57e06a905431160d10">Body::SetCollideKinematicVsNonDynamic</a>. Note that it can place a large burden on the collision detection system if you have a large sensor intersect with e.g. a large mesh terrain or a height field as you will get many contact callbacks and these contacts will take up a lot of space in the contact cache. Ensure that your sensor is in an object layer that collides with as few static bodies as possible.</p>
  564. <p>To temporarily disable a sensor, choose between:</p>
  565. <ul>
  566. <li>Remove the sensor by calling <a class="el" href="class_body_interface.html#a522d341ddd68225e12eb510f072399f9" title="Remove body from the physics system. Note that you need to add a body to the physics system before yo...">BodyInterface::RemoveBody</a> and re-add it later again with <a class="el" href="class_body_interface.html#a4ba54993b7bbc05f1a6ffccbc46f0397">BodyInterface::AddBody</a>.</li>
  567. <li>Change the collision layer using <a class="el" href="class_body_interface.html#a2c1a6660958d7f52b37e45587ccbab92" title="The collision layer this body belongs to (determines if two objects can collide)">BodyInterface::SetObjectLayer</a> to a layer that doesn't collide with anything (possibly also in a <a class="el" href="class_broad_phase_layer.html">BroadPhaseLayer</a> that doesn't collide with anything)</li>
  568. </ul>
  569. <h2><a class="anchor" id="sleeping-bodies"></a>
  570. Sleeping</h2>
  571. <p>During the simulation step, bodies are divided in 'islands'. Each island consists of a set of dynamic bodies that are either in contact with each other, or that are connected through a constraint:</p>
  572. <div class="image">
  573. <img src="SimulationIsland.jpg" alt=""/>
  574. <div class="caption">
  575. Simulation islands are enclosed by a red box. Note that the floor is static so not part of an island.</div></div>
  576. <p>At the end of each step, all the bodies in an island are checked to see if they have come to rest, if this is the case then the entire island is put to sleep. When a body is sleeping, it can still detect collisions with other objects that are not sleeping, but it will not move or otherwise participate in the simulation to conserve CPU cycles. Sleeping bodies wake up automatically when they're in contact with non-sleeping objects or they can be explicitly woken through an API call like <a class="el" href="class_body_interface.html#ab6ccbc72a1df04bd16c5dc5dee7bdf30">BodyInterface::ActivateBody</a>. Unlike some other physics engines, removing a <a class="el" href="class_body.html">Body</a> from the world doesn't wake up any surrounding bodies. If you want this you can call <a class="el" href="class_body_interface.html#a0397e4e0c43023b4c55d171d944dc430">BodyInterface::ActivateBodiesInAABox</a> with the bounding box of the removed body (or the combined bounding box if you're removing multiple bodies). Also, things like setting the velocity through <a class="el" href="class_body.html#a603b71ad2f5dbb76fd80fa9dff8be7f9">Body::SetLinearVelocity</a> will not wake up the <a class="el" href="class_body.html">Body</a>, use <a class="el" href="class_body_interface.html#a49831752041e13262dff231f4e404302">BodyInterface::SetLinearVelocity</a> instead. You can configure the definition of a body 'at rest' through <a class="el" href="struct_physics_settings.html#a0bd7d6eb98c547488f874a9577fff451" title="Time before object is allowed to go to sleep (unit: seconds)">PhysicsSettings::mTimeBeforeSleep</a> and <a class="el" href="struct_physics_settings.html#aae6093b99380ed5b72f5af1cc6529785">PhysicsSettings::mPointVelocitySleepThreshold</a>.</p>
  577. <h2><a class="anchor" id="soft-bodies"></a>
  578. Soft Bodies</h2>
  579. <p>Soft bodies (also known as deformable bodies) can be used to create e.g. a soft ball or a piece of cloth. They are created in a very similar way to normal rigid bodies:</p>
  580. <ul>
  581. <li>First allocate a new <a class="el" href="class_soft_body_shared_settings.html">SoftBodySharedSettings</a> object on the heap. This object will contain the initial positions of all particles and the constraints between the particles. This object can be shared between multiple soft bodies and should remain constant during its lifetime.</li>
  582. <li>Then create a <a class="el" href="class_soft_body_creation_settings.html">SoftBodyCreationSettings</a> object (e.g. on the stack) and fill in the desired properties of the soft body.</li>
  583. <li>Finally construct the body and add it to the world through <a class="el" href="class_body_interface.html#a0424b908e93229e76b8e2577931abe3f">BodyInterface::CreateAndAddSoftBody</a>.</li>
  584. </ul>
  585. <p>Soft bodies use the <a class="el" href="class_body.html">Body</a> class just like rigid bodies but can be identified by checking <a class="el" href="class_body.html#a454781f1340576ad7f752b51dd8a179d" title="Check if this body is a soft body.">Body::IsSoftBody</a>. To get to the soft body state, cast the result of <a class="el" href="class_body.html#a0d39987255227c4221fcea66cb1fc041" title="Access to the motion properties.">Body::GetMotionProperties</a> to <a class="el" href="class_soft_body_motion_properties.html" title="This class contains the runtime information of a soft body.">SoftBodyMotionProperties</a> and use its API.</p>
  586. <p>Soft bodies try to implement as much as possible of the normal <a class="el" href="class_body.html">Body</a> interface, but this interface provides a simplified version of reality, e.g. <a class="el" href="class_body.html#a6451197a038f1d99b4b92beae4656842" title="Get world space linear velocity of the center of mass (unit: m/s)">Body::GetLinearVelocity</a> will return the average particle speed and <a class="el" href="class_body.html#adce53bad2dc9f79804d6a01d435c06e0" title="World space position of the body.">Body::GetPosition</a> returns the average particle position. During simulation, a soft body will never update its rotation. Internally it stores particle velocities in local space, so if you rotate a soft body e.g. by calling <a class="el" href="class_body_interface.html#a199aec558e03ec611fc32e2e4fcbfc07">BodyInterface::SetRotation</a>, the body will rotate but its velocity will as well.</p>
  587. <h3><a class="anchor" id="soft-body-contact-listener"></a>
  588. Soft Body Contact Listeners</h3>
  589. <p>Soft Bodies provide contacts with other bodies through the <a class="el" href="class_soft_body_contact_listener.html">SoftBodyContactListener</a> class. This contact listener works a little bit different from the normal contact listener as you will not receive a contact callback per colliding vertex.</p>
  590. <p>After the broad phase has detected an overlap and the normal layer / collision group filters have had a chance to reject the collision, you will receive a <a class="el" href="class_soft_body_contact_listener.html#a88fe3a41025942d5e4c1f144b20bfbd9">SoftBodyContactListener::OnSoftBodyContactValidate</a> callback. This callback allows you to specify how the vertices of the soft body should interact with the other body. You can override the mass for both bodies and you can turn the contact into a sensor contact.</p>
  591. <p>The simulation will then proceed to do all collision detection and response and after that is finished, you will receive a <a class="el" href="class_soft_body_contact_listener.html#a5b875d9411f869298407501bc3d98199">SoftBodyContactListener::OnSoftBodyContactAdded</a> callback that allows you to inspect all collisions that happened during the simulation step. In order to do this a <a class="el" href="class_soft_body_manifold.html" title="An interface to query which vertices of a soft body are colliding with other bodies.">SoftBodyManifold</a> is provided which allows you to loop over the vertices and ask each vertex what it collided with.</p>
  592. <p>Note that at the time of the callback, multiple threads are operating at the same time. The soft body is stable and can be safely read. The other body that is collided with is not stable however, so you cannot safely read its position/orientation and velocity as it may be modified by another soft body collision at the same time.</p>
  593. <h3><a class="anchor" id="skinning-soft-bodies"></a>
  594. Skinning Soft Bodies</h3>
  595. <p>Using the <a class="el" href="class_soft_body_shared_settings_1_1_skinned.html">skinning</a> constraints, a soft body can be (partially) skinned to joints. This can be used e.g. to partially drive cloth with a character animation. The <a class="el" href="struct_soft_body_shared_settings_1_1_vertex.html#aefc61e301f8ba7f7ad8209a69dabeeb1">vertices</a> of the soft body need to be placed in the neutral pose of the character and the joints for this pose need to be calculated in model space (relative to these vertices). The inverted matrices of this neutral pose need to be stored as the <a class="el" href="class_soft_body_shared_settings_1_1_inv_bind.html">inverse bind matrices</a> and the skinning constraints can then be <a class="el" href="class_soft_body_shared_settings_1_1_skin_weight.html">weighted</a> to these joints. <a class="el" href="class_soft_body_shared_settings.html#a4a2fd7676a705063111d0f429d2bdce9" title="Calculate information needed to be able to calculate the skinned constraint normals at run-time.">SoftBodySharedSettings::CalculateSkinnedConstraintNormals</a> must be called to gather information needed to calculate the face normals at run-time.</p>
  596. <p>At run-time, you need to provide the animated joints every simulation step through the <a class="el" href="class_soft_body_motion_properties.html#a790161d0d5a2b34be8b3ab40376a62c6">SoftBodyMotionProperties::SkinVertices</a> call. During simulation, each skinned vertex will calculate its position and this position will be used to limit the movement of its simulated counterpart.</p>
  597. <div class="image">
  598. <img src="SoftBodySkinnedConstraint.jpg" alt=""/>
  599. <div class="caption">
  600. A Skinned Constraint</div></div>
  601. <p>The adjacent faces of the soft body will be used to calculate the normal of each vertex (shown in red), the vertex is then free to move inside the sphere formed by the skinned vertex position with radius <a class="el" href="class_soft_body_shared_settings_1_1_skinned.html#a1e576b87460323a5a79528381102e513">MaxDistance</a> (green sphere). To prevent the vertex from intersecting with the character, it is possible to specify a <a class="el" href="class_soft_body_shared_settings_1_1_skinned.html#a2f3d49c4f3fff9becd3fe72d890f738e">BackStopDistance</a> and <a class="el" href="class_soft_body_shared_settings_1_1_skinned.html#a0a64d6d45114dfd3ba4b54c821a6d678">BackStopRadius</a>, together these form the red sphere. The vertex is not allowed to move inside this sphere.</p>
  602. <h3><a class="anchor" id="soft-body-wip"></a>
  603. Soft Body Work In Progress</h3>
  604. <p>Soft bodies are currently in development, please note the following:</p>
  605. <ul>
  606. <li>Soft bodies can only collide with rigid bodies, collisions between soft bodies are not implemented yet.</li>
  607. <li>AddTorque/SetLinearVelocity/SetLinearVelocityClamped/SetAngularVelocity/SetAngularVelocityClamped/AddImpulse/AddAngularImpulse have no effect on soft bodies as the velocity is stored per particle rather than per body.</li>
  608. <li>Buoyancy calculations have not been implemented yet.</li>
  609. <li>Constraints cannot operate on soft bodies, set the inverse mass of a particle to zero and move it by setting a velocity to constrain a soft body to something else.</li>
  610. <li>When calculating friction / restitution an empty <a class="el" href="class_sub_shape_i_d.html" title="A sub shape id contains a path to an element (usually a triangle or other primitive type) of a compou...">SubShapeID</a> will be passed to the <a class="el" href="class_contact_constraint_manager.html#ad0b40a0f57d994f32b069744541fce56">ContactConstraintManager::CombineFunction</a> because this is called once per body pair rather than once per sub shape as is common for rigid bodies.</li>
  611. </ul>
  612. <h1><a class="anchor" id="constraints"></a>
  613. Constraints</h1>
  614. <p>Bodies can be connected to each other using constraints (<a class="el" href="class_constraint.html">Constraint</a>).</p>
  615. <p>The following constraints are available:</p>
  616. <ul>
  617. <li><a class="el" href="class_fixed_constraint_settings.html">FixedConstraint</a> - Will attach a body to another without any degrees of freedom.</li>
  618. <li><a class="el" href="class_distance_constraint_settings.html">DistanceConstraint</a> - Will attach two bodies with a stick (removing 1 degree of freedom).</li>
  619. <li><a class="el" href="class_point_constraint_settings.html">PointConstraint</a> - Will attach two bodies in a single point (removing 3 degrees of freedom)</li>
  620. <li><a class="el" href="class_hinge_constraint_settings.html">HingeConstraint</a> - Will attach two bodies through a hinge.</li>
  621. <li><a class="el" href="class_cone_constraint_settings.html">ConeConstraint</a> - Attaches two bodies in a point and will limit the rotation within a cone.</li>
  622. <li><a class="el" href="class_slider_constraint_settings.html">SliderConstraint</a> - Attaches two bodies and allows only movement in a single translation axis (also known as prismatic constraint).</li>
  623. <li><a class="el" href="class_swing_twist_constraint_settings.html">SwingTwistConstraint</a> - Attaches two bodies using a point constraint and a swing-twist constraint which approximates the shoulder joint of a human.</li>
  624. <li><a class="el" href="class_six_d_o_f_constraint_settings.html">SixDOFConstraint</a> - The most configurable joint allows specifying per translation axis and rotation axis what the limits are.</li>
  625. <li><a class="el" href="class_path_constraint_settings.html">PathConstraint</a> - This constraint allows attaching two bodies connected through a Hermite spline path.</li>
  626. <li><a class="el" href="class_gear_constraint_settings.html">GearConstraint</a> - This constraint connects to two hinge joints and constrains them to connect two gears.</li>
  627. <li><a class="el" href="class_rack_and_pinion_constraint_settings.html">RackAndPinionConstraint</a> - This constraint connects a hinge and a slider constraint to connect a rack and pinion.</li>
  628. <li><a class="el" href="class_pulley_constraint_settings.html">PulleyConstraint</a> - This constraint connects two bodies through two fixed points creating something that behaves like two bodies connected through a rope.</li>
  629. <li><a class="el" href="class_vehicle_constraint_settings.html">VehicleConstraint</a> - This constraint adds virtual wheels or tracks to a body and allows it to behave as a vehicle.</li>
  630. </ul>
  631. <p>If you want to constrain a dynamic object to the unmovable 'world' you can use <a class="el" href="class_body.html#a8dd9a53f984efe2ced2f73ee084f636a">Body::sFixedToWorld</a> instead of creating a static body.</p>
  632. <p>Bodies do not keep track of the constraints that are connected to them. This means that you're responsible for removing any constraints attached to a body before removing the body from the <a class="el" href="class_physics_system.html">PhysicsSystem</a>.</p>
  633. <p>Adding and removing constraints can be done from multiple threads, but the constraints themselves do not have any protection against concurrent access. We assume that constraints are owned by some object (e.g. a <a class="el" href="class_ragdoll.html" title="Runtime ragdoll information.">Ragdoll</a>) and that object ensures that it only modifies its own constraints and contains its own synchronization logic. Constraints can be freely modified except during the physics simulation step.</p>
  634. <p>Contact constraints (when bodies collide) are not handled through the <a class="el" href="class_constraint.html">Constraint</a> class but through the <a class="el" href="class_contact_constraint_manager.html">ContactConstraintManager</a> which is considered an internal class.</p>
  635. <h2><a class="anchor" id="constraint-motors"></a>
  636. Constraint Motors</h2>
  637. <p>Most of the constraints support motors (see <a class="el" href="class_motor_settings.html">MotorSettings</a>) which allow you to apply forces/torques on two constrained bodies to drive them to a relative position/orientation. There are two types of motors:</p><ul>
  638. <li>Linear motors: These motors drive the relative position between two bodies. A linear motor would, for example, slide a body along a straight line when you use a slider constraint.</li>
  639. <li>Angular motors: These motors drive the relative rotation between two bodies. An example is a hinge constraint. The motor drives the rotation along the hinge axis.</li>
  640. </ul>
  641. <p>Motors can have three states (see <a class="el" href="_motor_settings_8h.html#a691a2387946263d993fa8e1c9488bc2b">EMotorState</a> or e.g. <a class="el" href="class_slider_constraint.html#aa1c23dfc17c263c4d67d42913844a6f3">SliderConstraint::SetMotorState</a>):</p><ul>
  642. <li>Off: The motor is not doing any work.</li>
  643. <li>Velocity: This type of motor drives the relative velocity between bodies. For a slider constraint, you would push the bodies towards/away from each other with constant velocity. For a hinge constraint, you would rotate the bodies relative to each other with constant velocity. Set the target velocity through e.g. <a class="el" href="class_slider_constraint.html#ad28c19b7263229a90d9514c23a816d82">SliderConstraint::SetTargetVelocity</a> / <a class="el" href="class_hinge_constraint.html#a8f17d0facd91bdaba60f9ac473db1b2f" title="rad/s">HingeConstraint::SetTargetAngularVelocity</a>.</li>
  644. <li>Position: This type of motor drives the relative position between bodies. For a slider constraint, you can specify the relative distance you want to achieve between the bodies. For a hinge constraint you can specify the relative angle you want to achieve between the bodies. Set the target position through e.g. <a class="el" href="class_slider_constraint.html#aea6e58150ae68060810e6b1e6246b7a2">SliderConstraint::SetTargetPosition</a> / <a class="el" href="class_hinge_constraint.html#ac2efec9945040fae41af37498ba5f357" title="rad">HingeConstraint::SetTargetAngle</a>.</li>
  645. </ul>
  646. <p>Motors apply a force (when driving position) or torque (when driving angle) every simulation step to achieve the desired velocity or position. You can control the maximum force/torque that the motor can apply through <a class="el" href="class_motor_settings.html#ac8b066324ceb0052a8ff637e77d4e9c1" title="Minimum force to apply in case of a linear constraint (N). Usually this is -mMaxForceLimit unless you...">MotorSettings::mMinForceLimit</a>, <a class="el" href="class_motor_settings.html#aacf73d5d1dc3d729ed505b01f2b91425" title="Maximum force to apply in case of a linear constraint (N). Not used when motor is an angular motor.">MotorSettings::mMaxForceLimit</a>, <a class="el" href="class_motor_settings.html#a7073ab453c838bef080a3386da6927bd" title="Minimum torque to apply in case of a angular constraint (N m). Usually this is -mMaxTorqueLimit unles...">MotorSettings::mMinTorqueLimit</a> and <a class="el" href="class_motor_settings.html#a53921d266a57d01aa6833ca3fe09c3a7" title="Maximum torque to apply in case of a angular constraint (N m). Not used when motor is a position moto...">MotorSettings::mMaxTorqueLimit</a>. Note that if a motor is driving to a position, the torque limits are not used. If a constraint is driving to an angle, the force limits are not used.</p>
  647. <p>Usually the limits are symmetric, so you would set -mMinForceLimit = mMaxForceLimit. This way the motor can push at an equal rate as it can pull. If you would set the range to e.g. [0, FLT_MAX] then the motor would only be able to push in the positive direction. The units for the force limits are Newtons and the values can get pretty big. If your motor doesn't seem to do anything, chances are that you have set the value too low. Since Force = Mass * Acceleration you can calculate the approximate force that a motor would need to supply in order to be effective. Usually the range is set to [-FLT_MAX, FLT_MAX] which lets the motor achieve its target as fast as possible.</p>
  648. <p>For an angular motor, the units are Newton Meters. The formula is Torque = Inertia * Angular Acceleration. Inertia of a solid sphere is 2/5 * Mass * Radius^2. You can use this to get a sense of the amount of torque needed to get the angular acceleration you want. Again, you'd usually set the range to [-FLT_MAX, FLT_MAX] to not limit the motor.</p>
  649. <p>When settings the force or torque limits to [-FLT_MAX, FLT_MAX] a velocity motor will accelerate the bodies to the desired relative velocity in a single time step (if no other forces act on those bodies).</p>
  650. <p>Position motors have two additional parameters: Frequency (MotorSettings::mSpringSettings.mFrequency, Hz) and damping (MotorSettings::mSpringSettings.mDamping, no units). They are implemented as described in <a href="https://box2d.org/files/ErinCatto_SoftConstraints_GDC2011.pdf">Soft Constraints: Reinventing The Spring - Erin Catto - GDC 2011</a>.</p>
  651. <p>You can see a position motor as a spring between the target position and the rigid body. The force applied to reach the target is linear with the distance between current position and target position. When there is no damping, the position motor will cause the rigid body to oscillate around its target.</p>
  652. <div class="image">
  653. <img src="MotorFrequency.jpg" alt=""/>
  654. <div class="caption">
  655. A rigid body on a slider constraint. The body starts at 1 and is driven to 0 with a position motor. Two different motor frequencies are shown. The higher the frequency, the faster the motor will reach its target, but without damping it will overshoot and oscillate forever.</div></div>
  656. <p>Valid frequencies are in the range (0, 0.5 * simulation frequency]. A frequency of 0 results in no force being applied, a frequency larger than half of the physics simulation frequency will result in instability. For a 60 Hz physics simulation, 20 is a good value for a stiff spring (without damping it will reach its target in 1/(4 * 20) = 0.0125 s), 2 is good for a soft spring (will reach its target in 1/(4 * 2) = 0.125 s).</p>
  657. <p>In order to prevent the motor from overshooting its target, we use damping.</p>
  658. <div class="image">
  659. <img src="MotorDamping.jpg" alt=""/>
  660. <div class="caption">
  661. A rigid body on a slider constraint. The body starts at 1 and is driven to 0 with a position motor. The frequency of the motor is 2 Hz and the lines correspond to different damping values.</div></div>
  662. <p>Sensible values for damping are [0, 1] but higher values are also possible. When the damping is below 1, the body will still oscillate around its target, but that oscillation will die out. When the damping is 1 (called critical damping) there is no oscillation at all but it will take longer for the motor to reach its target. When damping is bigger than 1, the system is over dampened. There will not be any oscillation, but it will take even longer for the motor to reach its target.</p>
  663. <p>Because Jolt Physics uses a Symplectic Euler integrator, there will still be a small amount of damping when damping is 0, so you cannot get infinite oscillation (allowing this would make it very likely for the system to become unstable).</p>
  664. <h2><a class="anchor" id="breakable-constraints"></a>
  665. Breakable Constraints</h2>
  666. <p>Constraints can be turned on / off by calling <a class="el" href="class_constraint.html#aa6621fbefd246003aece1e9be8a169cb">Constraint::SetEnabled</a>. After every simulation step, check the total 'lambda' applied on each constraint and disable the constraint if the value goes over a certain threshold. Use e.g. <a class="el" href="class_slider_constraint.html#a7e004ec04d0e7a7fe00ba2b0a8840b6a">SliderConstraint::GetTotalLambdaPosition</a> / <a class="el" href="class_hinge_constraint.html#a69121251820ce4c305f3275b15242f7a">HingeConstraint::GetTotalLambdaRotation</a>. You can see 'lambda' as the linear/angular impulse applied at the constraint in the last physics step to keep the constraint together.</p>
  667. <h1><a class="anchor" id="collision-detection"></a>
  668. Collision Detection</h1>
  669. <p>Collision detection can be performed through various interfaces:</p>
  670. <ul>
  671. <li>Coarse collision detection against the world, using only the bounding box of each body is done through the <a class="el" href="class_broad_phase_query.html">BroadPhaseQuery</a> interface (see <a class="el" href="class_physics_system.html#a3d621cc72c69b73cdcc13bdb3b0dddc4" title="Access to the broadphase interface that allows coarse collision queries.">PhysicsSystem::GetBroadPhaseQuery</a>).</li>
  672. <li>Detailed collision detection against the world is done through <a class="el" href="class_narrow_phase_query.html">NarrowPhaseQuery</a> interface (see <a class="el" href="class_physics_system.html#a1ced58861f3fbb7cfea901128bb7a84d" title="Interface that allows fine collision queries against first the broad phase and then the narrow phase.">PhysicsSystem::GetNarrowPhaseQuery</a>).</li>
  673. <li>Checking collisions with a single body is done through <a class="el" href="class_transformed_shape.html">TransformedShape</a> (see <a class="el" href="class_body.html#ab29a0e2490187a1e08d21c4e9235f2a3" title="Get the transformed shape of this body, which can be used to do collision detection outside of a body...">Body::GetTransformedShape</a>)</li>
  674. <li>Checking collisions against a single shape is done through various interfaces on the <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a> class (see e.g. <a class="el" href="class_shape.html#a955ec1953bc94c6c910dc4dc16114732">Shape::CastRay</a>) or through the <a class="el" href="class_collision_dispatch.html" title="Dispatch function, main function to handle collisions between shapes.">CollisionDispatch</a> interface.</li>
  675. </ul>
  676. <p>The most common collision tests are:</p>
  677. <ul>
  678. <li>Casting a ray: <a class="el" href="class_broad_phase_query.html#a1c74037652396c3584021f9b99341397" title="Cast a ray and add any hits to ioCollector.">BroadPhaseQuery::CastRay</a>, <a class="el" href="class_narrow_phase_query.html#a820937ebfc2c8ab46daade8e007f2269">NarrowPhaseQuery::CastRay</a>, <a class="el" href="class_transformed_shape.html#acd5399c06080e74de7f1ad8c61f9465a">TransformedShape::CastRay</a>, <a class="el" href="class_shape.html#a955ec1953bc94c6c910dc4dc16114732">Shape::CastRay</a>.</li>
  679. <li>Colliding a shape (e.g. a sphere) in a static position: <a class="el" href="class_narrow_phase_query.html#a6874ff06a6884c2706a1bbf8ed2590a8">NarrowPhaseQuery::CollideShape</a>, <a class="el" href="class_transformed_shape.html#ad302129a3ff14b43463ec6514a79f988">TransformedShape::CollideShape</a>, <a class="el" href="class_collision_dispatch.html#a29634d08db5d24ce7c0d5c44b547c075">CollisionDispatch::sCollideShapeVsShape</a>.</li>
  680. <li>Casting a shape (sweeping it from a start to an end position and finding collisions along the way): <a class="el" href="class_narrow_phase_query.html#a5d9ab53431ed38e7d143d5cab9df08cb">NarrowPhaseQuery::CastShape</a>, <a class="el" href="class_transformed_shape.html#ab9b03e726e2992e5a4ca1df568d5ae75">TransformedShape::CastShape</a>, <a class="el" href="class_collision_dispatch.html#a50ed5fc6de2aa13d6f48ab29f6cf0b7f">CollisionDispatch::sCastShapeVsShapeWorldSpace</a>.</li>
  681. <li>Checking if a shape contains a point: <a class="el" href="class_broad_phase_query.html#a191877420623144ad7ba7a78db56baa9" title="Get bodies intersecting with a point and any hits to ioCollector.">BroadPhaseQuery::CollidePoint</a>, <a class="el" href="class_narrow_phase_query.html#afcfabe1320517d1bdc956cded95f0f8a">NarrowPhaseQuery::CollidePoint</a>, <a class="el" href="class_transformed_shape.html#ad589cfe7574f79645c39f917e15aff08">TransformedShape::CollidePoint</a>, <a class="el" href="class_shape.html#af6e77d16736434769d72152bf059a126">Shape::CollidePoint</a>.</li>
  682. </ul>
  683. <p>The following sections describe the collision detection system in more detail.</p>
  684. <h2><a class="anchor" id="broad-phase"></a>
  685. Broad Phase</h2>
  686. <p>When bodies are added to the <a class="el" href="class_physics_system.html">PhysicsSystem</a>, they are inserted in the broad phase (<a class="el" href="class_broad_phase_quad_tree.html">BroadPhaseQuadTree</a>). This provides quick coarse collision detection based on the axis aligned bounding box (AABB) of a body.</p>
  687. <div class="image">
  688. <img src="EllipsoidAABB.png" alt=""/>
  689. <div class="caption">
  690. To quickly test if two objects overlap you can check if their axis aligned bounding boxes overlap. If they do, a check between the actual shapes is needed to be sure.</div></div>
  691. <p>Our broad phase is a quad tree, which means each node has 4 children. In the following image you see a random collection of spheres and triangles and a possible way to split the tree.</p>
  692. <div class="image">
  693. <img src="QuadTreeExample.png" alt=""/>
  694. <div class="caption">
  695. QuadTree Example</div></div>
  696. <p>At the highest level we split all objects in 4 mostly disjoint sets. Note that nodes are allowed to overlap, but for efficiency reasons we want the amount of overlap to be minimal. The example split here is indicated by a red, blue, green and yellow box and you can see them appear in the tree on the right. Three out of four nodes: blue, yellow and red, have 4 or less shapes in them, so the tree can directly point at the shapes rather than at a next node. One node: green, has more than 4 shapes in it so needs a further split. The three shapes can be added directly to the node and we need to create a new node, dotted green, to hold the last two shapes. The reason why we pick 4 children is that modern CPUs support doing 4 math operations in a single instruction, so when we walk the tree from top to bottom during a collision query, we can handle 4 children at the same time and quickly get to a minimal set of colliding objects.</p>
  697. <p>Since we want to access bodies concurrently the broad phase has special behavior. When a body moves, all nodes in the AABB tree from root to the node where the body resides will be expanded using a lock-free approach. This way multiple threads can move bodies at the same time without requiring a lock on the broad phase. Nodes that have been expanded are marked and during the next physics step a new tight-fitting tree will be built in the background while the physics step is running. This new tree will replace the old tree before the end of the simulation step. This is possible since no bodies can be added/removed during the physics step. For more information about this see the <a href="https://jrouwe.nl/architectingjolt/ArchitectingJoltPhysics_Rouwe_Jorrit_Notes.pdf">GDC 2022 talk</a>.</p>
  698. <p>The broad phase is divided in layers (<a class="el" href="class_broad_phase_layer.html">BroadPhaseLayer</a>), each broad phase layer has an AABB quad tree associated with it. A standard setup would be to have at least 2 broad phase layers: One for all static bodies (which is infrequently updated but is expensive to update since it usually contains most bodies) and one for all dynamic bodies (which is updated every simulation step but cheaper to update since it contains fewer objects). In general you should only have a few broad phase layers as there is overhead in querying and maintaining many different broad phase trees.</p>
  699. <p>When doing a query against the broad phase (<a class="el" href="class_broad_phase_query.html">BroadPhaseQuery</a>), you generally will get a body ID for intersecting objects. If a collision query takes a long time to process the resulting bodies (e.g. across multiple simulation steps), you can safely keep using the body ID's as specified in the <a class="el" href="#bodies">Bodies</a> section.</p>
  700. <h2><a class="anchor" id="narrow-phase"></a>
  701. Narrow Phase</h2>
  702. <p>A narrow phase query (<a class="el" href="class_narrow_phase_query.html">NarrowPhaseQuery</a>) will first query the broad phase for intersecting bodies and will under the protection of a body lock construct a transformed shape (<a class="el" href="class_transformed_shape.html">TransformedShape</a>) object. This object contains the transform, a reference counted shape and a body ID. Since the shape will not be deleted until you destroy the <a class="el" href="class_transformed_shape.html">TransformedShape</a> object, it is a consistent snapshot of the collision information of the body. This ensures that the body is only locked for a short time frame and makes it possible to do the bulk of the collision detection work outside the protection of a lock.</p>
  703. <p>For very long running jobs (e.g. navigation mesh creation) it is possible to query all transformed shapes in an area and then do the processing work using a long running thread without requiring additional locks (see <a class="el" href="class_narrow_phase_query.html#a9cb6ed9faecacb191cb15088e6c0de1e">NarrowPhaseQuery::CollectTransformedShapes</a>).</p>
  704. <p>The narrow phase queries are all handled through the <a class="el" href="class_g_j_k_closest_point.html">GJK</a> and <a class="el" href="class_e_p_a_penetration_depth.html">EPA</a> algorithms.</p>
  705. <h2><a class="anchor" id="collision-filtering"></a>
  706. Collision Filtering</h2>
  707. <p>Each <a class="el" href="class_body.html">Body</a> is in an <a class="el" href="_object_layer_8h.html#a960eb396e2803ddad87bf25e0dcb4470">ObjectLayer</a>. If two object layers don't collide, the bodies inside those layers cannot collide. You can define object layers in any way you like, it could be a simple number from 0 to N or it could be a bitmask. Jolt supports 16 or 32 bit ObjectLayers through the JPH_OBJECT_LAYER_BITS define and you're free to define as many as you like as they don't incur any overhead in the system.</p>
  708. <p>When constructing the <a class="el" href="class_physics_system.html">PhysicsSystem</a> you need to provide a number of filtering interfaces:</p><ul>
  709. <li><a class="el" href="class_broad_phase_layer_interface.html" title="Interface that the application should implement to allow mapping object layers to broadphase layers.">BroadPhaseLayerInterface</a>: This class defines a mapping from ObjectLayer to <a class="el" href="class_broad_phase_layer.html">BroadPhaseLayer</a> through the <a class="el" href="class_broad_phase_layer_interface.html#a5007c9b9beab5c16af36e89b48cd06cb" title="Convert an object layer to the corresponding broadphase layer.">BroadPhaseLayerInterface::GetBroadPhaseLayer</a> function. Each <a class="el" href="class_body.html">Body</a> can only be in 1 <a class="el" href="class_broad_phase_layer.html">BroadPhaseLayer</a> so an ObjectLayer maps to 1 BroadphaseLayer. In general there will be multiple ObjectLayers mapping to the same <a class="el" href="class_broad_phase_layer.html">BroadPhaseLayer</a> (because each broad phase layer comes at a cost). If there are multiple object layers in a single broad phase layer, they are stored in the same tree. When a query visits the tree it will visit all objects whose AABB overlaps with the query and only when the overlap is detected, the actual object layer will be checked. This means that you should carefully design which object layers end up in which broad phase layer, balancing the requirement of having few broad phase layers with the number of needless objects that are visited because multiple object layers share the same broad phase layer. You can define JPH_TRACK_BROADPHASE_STATS to let Jolt print out some statistics about the query patterns your application is using. In general it is wise to start with only 2 broad phase layers as listed in the <a class="el" href="#broad-phase">Broad Phase</a> section.</li>
  710. <li><a class="el" href="class_object_vs_broad_phase_layer_filter.html" title="Class to test if an object can collide with a broadphase layer. Used while finding collision pairs.">ObjectVsBroadPhaseLayerFilter</a>: This class defines a <a class="el" href="class_object_vs_broad_phase_layer_filter.html#a6004607941fda1b8c6a88471440e0e86" title="Returns true if an object layer should collide with a broadphase layer.">ObjectVsBroadPhaseLayerFilter::ShouldCollide</a> function that checks if an ObjectLayer collides with objects that reside in a particular <a class="el" href="class_broad_phase_layer.html">BroadPhaseLayer</a>. ObjectLayers can collide with as many BroadPhaseLayers as needed, so it is possible for a collision query to visit multiple broad phase trees.</li>
  711. <li><a class="el" href="class_object_layer_pair_filter.html" title="Filter class to test if two objects can collide based on their object layer. Used while finding colli...">ObjectLayerPairFilter</a>: This class defines a <a class="el" href="class_object_layer_pair_filter.html#a81cbe75cceb74bc262199206ac129c88" title="Returns true if two layers can collide.">ObjectLayerPairFilter::ShouldCollide</a> function that checks if an ObjectLayer collides with another ObjectLayer.</li>
  712. </ul>
  713. <p>As an example we will use a simple enum as ObjectLayer:</p><ul>
  714. <li>NON_MOVING - Layer for all static objects.</li>
  715. <li>MOVING - Layer for all regular dynamic bodies.</li>
  716. <li>DEBRIS - Layer for all debris dynamic bodies, we want to test these only against the static geometry because we want to save some simulation cost.</li>
  717. <li>BULLET - Layer for high detail collision bodies that we co-locate with regular dynamic bodies. These are bodies that are not used for simulation but are moved to follow the dynamic bodies and provide more precise geometry for ray tests to simulate shooting bullets. See <a class="el" href="#level-of-detail">Level of Detail</a> for more information.</li>
  718. <li>WEAPON - This is a query layer so we don't create any bodies with this layer but we use it when doing ray cast querying for our weapon system.</li>
  719. </ul>
  720. <p>We define the following object layers to collide:</p><ul>
  721. <li>MOVING vs NON_MOVING, MOVING vs MOVING - These are for our regular dynamic objects that need to collide with the static world and with each other.</li>
  722. <li>DEBRIS vs NON_MOVING - As said, we only want debris to collide with the static world and not with anything else.</li>
  723. <li>WEAPON vs BULLET, WEAPON vs NON_MOVING - We want our weapon ray cast to hit the high detail BULLET collision instead of the normal MOVING collision and we want bullets to be blocked by the static world (obviously the static world could also have a high detail version, but not in this example).</li>
  724. </ul>
  725. <p>This means that we need to implement a <a class="el" href="class_object_layer_pair_filter.html#a81cbe75cceb74bc262199206ac129c88" title="Returns true if two layers can collide.">ObjectLayerPairFilter::ShouldCollide</a> that returns true for the permutations listed above. Note that if ShouldCollide(A, B) returns true, ShouldCollide(B, A) should return true too.</p>
  726. <p>We define the following broad phase layers:</p><ul>
  727. <li>BP_NON_MOVING - For everything static (contains object layer: NON_MOVING).</li>
  728. <li>BP_MOVING - The default layer for dynamic objects (contains object layers: MOVING, BULLET).</li>
  729. <li>BP_DEBRIS - An extra layer that contains only debris (contains object layers: DEBRIS).</li>
  730. </ul>
  731. <p>This means we now implement a <a class="el" href="class_broad_phase_layer_interface.html#a5007c9b9beab5c16af36e89b48cd06cb" title="Convert an object layer to the corresponding broadphase layer.">BroadPhaseLayerInterface::GetBroadPhaseLayer</a> that maps: NON_MOVING -&gt; BP_NON_MOVING, MOVING -&gt; BP_MOVING, BULLET -&gt; BP_MOVING and DEBRIS -&gt; BP_DEBRIS. We can map WEAPON to anything as we won't create any objects with this layer.</p>
  732. <p>We also need to implement a <a class="el" href="class_object_vs_broad_phase_layer_filter.html#a6004607941fda1b8c6a88471440e0e86" title="Returns true if an object layer should collide with a broadphase layer.">ObjectVsBroadPhaseLayerFilter::ShouldCollide</a> that determines which object layer should collide with what broad phase layers, these can be deduced from the two lists above:</p><ul>
  733. <li>NON_MOVING: BP_MOVING, BP_DEBRIS</li>
  734. <li>MOVING: BP_NON_MOVING, BP_MOVING</li>
  735. <li>DEBRIS: BP_NON_MOVING</li>
  736. <li>BULLET: None (these are not simulated so need no collision with other objects)</li>
  737. <li>WEAPON: BP_NON_MOVING, BP_MOVING</li>
  738. </ul>
  739. <p>So you can see now that when we simulate DEBRIS we only need to visit a single broad phase tree to check for collision, we did this because in our example we know that there are going to be 1000s of debris objects so it is important that their queries are as fast as possible. We could have moved the BULLET layer to its own broad phase layer too because now BP_MOVING contains a lot of bodies that WEAPON is not interested in, but in this example we didn't because we know that there are not enough of these objects for this to be a performance problem.</p>
  740. <p>For convenience two filtering implementations are provided:</p><ul>
  741. <li><a class="el" href="class_object_layer_pair_filter_table.html">ObjectLayerPairFilterTable</a>, <a class="el" href="class_object_vs_broad_phase_layer_filter_table.html">ObjectVsBroadPhaseLayerFilterTable</a> and <a class="el" href="class_broad_phase_layer_interface_table.html">BroadPhaseLayerInterfaceTable</a>: These three implement collision layers as a simple table. You construct <a class="el" href="class_object_layer_pair_filter_table.html">ObjectLayerPairFilterTable</a> with a fixed number of object layers and then call <a class="el" href="class_object_layer_pair_filter_table.html#a92530da6280163ab73c27304dd911167" title="Enable collision between two object layers.">ObjectLayerPairFilterTable::EnableCollision</a> or <a class="el" href="class_object_layer_pair_filter_table.html#a24646de71a6a06550b0db5addf81b78e" title="Disable collision between two object layers.">ObjectLayerPairFilterTable::DisableCollision</a> to selectively enable or disable collisions between layers. <a class="el" href="class_broad_phase_layer_interface_table.html">BroadPhaseLayerInterfaceTable</a> is constructed with a number of broad phase layers. You can then map each object layer to a broad phase layer through <a class="el" href="class_broad_phase_layer_interface_table.html#a1c93b211dfb3e39b7c4cfed49ce961ad">BroadPhaseLayerInterfaceTable::MapObjectToBroadPhaseLayer</a>.</li>
  742. <li><a class="el" href="class_object_layer_pair_filter_mask.html">ObjectLayerPairFilterMask</a>, <a class="el" href="class_object_vs_broad_phase_layer_filter_mask.html">ObjectVsBroadPhaseLayerFilterMask</a> and <a class="el" href="class_broad_phase_layer_interface_mask.html">BroadPhaseLayerInterfaceMask</a>: These split an ObjectLayer in an equal amount of bits for group and mask. Two objects collide if (object1.group &amp; object2.mask) != 0 &amp;&amp; (object2.group &amp; object1.mask) != 0. This behavior is similar to e.g. Bullet. In order to map groups to broad phase layers, you call <a class="el" href="class_broad_phase_layer_interface_mask.html#a01a9ec0c57462e3cda401b73edbf3573">BroadPhaseLayerInterfaceMask::ConfigureLayer</a> for each broad phase layer. You determine which groups can be put in that layer and which group must be excluded from that layer. E.g. a broad phase layer could include everything that has the STATIC group but should exclude everything that has the SENSOR group, so that if an object has both STATIC and SENSOR bits set, this broad phase layer will not be used. The broad phase layers are checked one by one and the first one that meets the condition is the one that the body will be put in. If you use this implementation, consider setting the cmake option OBJECT_LAYER_BITS to 32 to get a 32-bit ObjectLayer instead of a 16-bit one.</li>
  743. </ul>
  744. <p>Now that we know about the basics, we list the order in which the collision detection pipeline goes through the various collision filters:</p>
  745. <div class="image">
  746. <img src="CollisionFlow.jpg" alt=""/>
  747. <div class="caption">
  748. Collision engine flow.</div></div>
  749. <ul>
  750. <li>Broadphase layer: At this stage, the object layer is tested against the broad phase trees that are relevant by checking the <a class="el" href="class_object_vs_broad_phase_layer_filter.html">ObjectVsBroadPhaseLayerFilter</a>.</li>
  751. <li>Object layer: Once the broad phase layer test succeeds, we will test object layers vs object layers through <a class="el" href="class_object_layer_pair_filter.html">ObjectLayerPairFilter</a> (used for simulation) and <a class="el" href="class_object_layer_filter.html">ObjectLayerFilter</a> (used for collision queries). The default implementation of <a class="el" href="class_object_layer_filter.html" title="Filter class for object layers.">ObjectLayerFilter</a> is <a class="el" href="class_default_object_layer_filter.html" title="Default filter class that uses the pair filter in combination with a specified layer to filter layers...">DefaultObjectLayerFilter</a> and uses <a class="el" href="class_object_layer_pair_filter.html" title="Filter class to test if two objects can collide based on their object layer. Used while finding colli...">ObjectLayerPairFilter</a> so the behavior is consistent between simulation and collision queries.</li>
  752. <li><a class="el" href="class_group_filter.html">GroupFilter</a>: Used only during simulation and runs after bounding boxes have found to be overlapping. Allows you fine tune collision e.g. by discarding collisions between bodies connected by a constraint. See e.g. <a class="el" href="class_group_filter_table.html">GroupFilterTable</a> which implements filtering for bodies within a ragdoll.</li>
  753. <li><a class="el" href="class_body_filter.html">BodyFilter</a>: This filter is used instead of the group filter if you do collision queries like CastRay.</li>
  754. <li><a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a> filter: This filter is used both during queries (<a class="el" href="class_shape_filter.html">ShapeFilter</a>) and simulation (<a class="el" href="class_sim_shape_filter.html">SimShapeFilter</a>) and can be used to filter out individual shapes of a compound. To set the shape filter for the simulation use <a class="el" href="class_physics_system.html#aa5e3d3dc2758b0ca0bcb6eb8e77bd379">PhysicsSystem::SetSimShapeFilter</a>.</li>
  755. <li><a class="el" href="class_contact_listener.html">ContactListener</a>: During simulation, after all collision detection work has been performed you can still choose to discard a contact point. This is a very expensive way of rejecting collisions as most of the work is already done.</li>
  756. </ul>
  757. <p>To avoid work, try to filter out collisions as early as possible.</p>
  758. <h2><a class="anchor" id="level-of-detail"></a>
  759. Level of Detail</h2>
  760. <p>Bodies can only exist in a single layer. If you want a body with a low detail collision shape for simulation (in the example above: MOVING layer) and a high detail collision shape for collision detection (BULLET layer), you'll need to create 2 Bodies. The low detail body should be dynamic. The high detail body should be kinematic, or if it doesn't interact with other dynamic objects it can also be static. After calling <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a>, you'll need to loop over these dynamic bodies and call <a class="el" href="class_body_interface.html#a511b9da7dae147b6d8d3227f30724334" title="Set velocity of body such that it will be positioned at inTargetPosition/Rotation in inDeltaTime seco...">BodyInterface::MoveKinematic</a> in case the high detail body is kinematic, or <a class="el" href="class_body_interface.html#a369e907b665f5814d864790173062d7f">BodyInterface::SetPositionAndRotation</a> in case the high detail body is static.</p>
  761. <p>Alternatively, you can put a high detail and a low detail shape in a <a class="el" href="class_static_compound_shape.html">StaticCompoundShape</a> and use <a class="el" href="class_physics_system.html#aa5e3d3dc2758b0ca0bcb6eb8e77bd379">PhysicsSystem::SetSimShapeFilter</a> to filter out the high detail shape during simulation. Another <a class="el" href="class_shape_filter.html" title="Filter class.">ShapeFilter</a> would filter out the low detail shape during collision queries (e.g. through <a class="el" href="class_narrow_phase_query.html">NarrowPhaseQuery</a>). You can use <a class="el" href="class_shape.html#a7146c658ddb5c7b0fec4489535ca664f" title="User data (to be used freely by the application)">Shape::GetUserData</a> to determine if a shape is a high or a low detail shape.</p>
  762. <h2><a class="anchor" id="continuous-collision-detection"></a>
  763. Continuous Collision Detection</h2>
  764. <p>Each body has a motion quality setting (<a class="el" href="_motion_quality_8h.html#af43db3453103c2e62526f54dd8542d3a">EMotionQuality</a>). By default the motion quality is <a class="el" href="_motion_quality_8h.html#af43db3453103c2e62526f54dd8542d3aa4984667940802dedc139aa7a430a6553">Discrete</a>. This means that at the beginning of each simulation step we will perform collision detection and if no collision is found, the body is free to move according to its velocity. This usually works fine for big or slow moving objects. Fast and small objects can easily 'tunnel' through thin objects because they can completely move through them in a single time step. For these objects there is the motion quality <a class="el" href="_motion_quality_8h.html#af43db3453103c2e62526f54dd8542d3aa38f63d197afcc4a4965d98f9401c36e0">LinearCast</a>. Objects that have this motion quality setting will do the same collision detection at the beginning of the simulation step, but once their new position is known, they will do an additional CastShape to check for any collisions that may have been missed. If this is the case, the object is placed back to where the collision occurred and will remain there until the next time step. This is called 'time stealing' and has the disadvantage that an object may appear to move much slower for a single time step and then speed up again. The alternative, back stepping the entire simulation, is computationally heavy so was not implemented.</p>
  765. <div class="image">
  766. <img src="MotionQuality.jpg" alt=""/>
  767. <div class="caption">
  768. With the Discrete motion quality the blue object tunnels through the green object in a single time step. With motion quality LinearCast it doesn't.</div></div>
  769. <p>Fast rotating long objects are also to be avoided, as the LinearCast motion quality will fully rotate the object at the beginning of the time step and from that orientation perform the CastShape, there is a chance that the object misses a collision because it rotated through it.</p>
  770. <div class="image">
  771. <img src="LongAndThin.jpg" alt=""/>
  772. <div class="caption">
  773. Even with the LinearCast motion quality the blue object rotates through the green object in a single time step.</div></div>
  774. <h2><a class="anchor" id="ghost-collisions"></a>
  775. Ghost Collisions</h2>
  776. <p>A ghost collision can occur when a body slides over another body and hits an internal edge of that body. The most common case is where a body hits an edge of a triangle in a mesh shape but it can also happen on 2 box shapes as shown below.</p>
  777. <div class="image">
  778. <img src="GhostCollision.jpg" alt=""/>
  779. <div class="caption">
  780. A blue box sliding over 2 green boxes. Because the blue box can sink into the green box a little bit, it can hit the edge between the two boxes. This will cause the box to stop or jump up.</div></div>
  781. <p>There are a couple of ways to avoid ghost collisions in Jolt. <a class="el" href="class_mesh_shape.html">MeshShape</a> and <a class="el" href="class_height_field_shape.html">HeightFieldShape</a> keep track of active edges during construction.</p>
  782. <div class="image">
  783. <img src="ActiveEdge.jpg" alt=""/>
  784. <div class="caption">
  785. An inactive edge (concave) and an active edge (convex, angle &gt; threshold angle).</div></div>
  786. <p>Whenever a body hits an inactive edge, the contact normal is the face normal. When it hits an active edge, it can be somewhere in between the connecting face normals so the movement of the body is impeded in the scenario below.</p>
  787. <div class="image">
  788. <img src="ActiveVsInactiveContactNormal.jpg" alt=""/>
  789. <div class="caption">
  790. Contact normal (red) of hitting an active vs an inactive edge.</div></div>
  791. <p>By tweaking <a class="el" href="class_mesh_shape_settings.html#ae9cfeaf937adb172ad5fff81997beede">MeshShapeSettings::mActiveEdgeCosThresholdAngle</a> or <a class="el" href="class_height_field_shape_settings.html#ac600befce41089e57309054090c889c8">HeightFieldShapeSettings::mActiveEdgeCosThresholdAngle</a> you can determine the angle at which an edge is considered an active edge. By default this is 5 degrees, making this bigger reduces the amount of ghost collisions but can create simulation artifacts if you hit the edge straight on.</p>
  792. <p>To further reduce ghost collisions, you can turn on <a class="el" href="class_body_creation_settings.html#a3ff57f2892a515d062718701434601c9" title="Set to indicate that extra effort should be made to try to remove ghost contacts (collisions with int...">BodyCreationSettings::mEnhancedInternalEdgeRemoval</a>. When enabling this setting, additional checks will be made at run-time to detect if an edge is active or inactive based on all of the contact points between the two bodies. Beware that this algorithm only considers 2 bodies at a time, so if the two green boxes above belong to two different bodies, the ghost collision can still occur. Use a <a class="el" href="class_static_compound_shape.html">StaticCompoundShape</a> to combine the boxes in a single body to allow the system to eliminate ghost collisions between the blue and the two green boxes. You can also use this functionality for your custom collision tests by making use of <a class="el" href="class_internal_edge_removing_collector.html">InternalEdgeRemovingCollector</a>.</p>
  793. <h1><a class="anchor" id="character-controllers"></a>
  794. Character Controllers</h1>
  795. <p>The <a class="el" href="class_character.html">Character</a> and <a class="el" href="class_character_virtual.html">CharacterVirtual</a> classes can be used to create a character controller. These are usually used to represent the player as a simple capsule or tall box and perform collision detection while the character navigates through the world.</p>
  796. <p>The <a class="el" href="class_character.html">Character</a> class is the simplest controller and is essentially a rigid body that has been configured to only allow translation (and no rotation so it stays upright). It is simulated together with the other rigid bodies so it properly reacts to them. Because it is simulated, it is usually not the best solution for a player as the player usually requires a lot of behavior that is non-physical. This character controller is cheap so it is recommended for e.g. simple AI characters. After every <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> call you must call <a class="el" href="class_character.html#a6fd02888e30d3a718e81680857ca3968">Character::PostSimulation</a> to update the ground contacts.</p>
  797. <p>Characters are usually driven in a kinematic way (i.e. by calling <a class="el" href="class_character.html#a03d43dd12da2501fbb643bdbe7daef46" title="Set the linear velocity of the character (m / s)">Character::SetLinearVelocity</a> or <a class="el" href="class_character_virtual.html#a25da7eb8e9ff5316e357cbf59027b57e" title="Set the linear velocity of the character (m / s)">CharacterVirtual::SetLinearVelocity</a> before their update).</p>
  798. <p>The <a class="el" href="class_character_virtual.html">CharacterVirtual</a> class is much more advanced. It is implemented using collision detection functionality only (through <a class="el" href="class_narrow_phase_query.html">NarrowPhaseQuery</a>) and is simulated when <a class="el" href="class_character_virtual.html#ab9ce165035699a776a9d0b3e570def01">CharacterVirtual::Update</a> is called. Since the character is not 'added' to the world, it is not visible to rigid bodies and it only interacts with them during the <a class="el" href="class_character_virtual.html#ab9ce165035699a776a9d0b3e570def01">CharacterVirtual::Update</a> function by applying impulses. This does mean there can be some update order artifacts, like the character slightly hovering above an elevator going down, because the characters moves at a different time than the other rigid bodies. Separating it has the benefit that the update can happen at the appropriate moment in the game code. Multiple CharacterVirtuals can update concurrently, so it is not an issue if the game code is parallelized.</p>
  799. <p><a class="el" href="class_character_virtual.html">CharacterVirtual</a> has the following extra functionality:</p><ul>
  800. <li>Sliding along walls</li>
  801. <li>Interaction with elevators and moving platforms</li>
  802. <li>Enhanced steep slope detection (standing in a funnel whose sides are too steep to stand on will not be considered as too steep)</li>
  803. <li>Stair stepping through the <a class="el" href="class_character_virtual.html#ae03c43c12e8eb6496b8c8044c70b591f">CharacterVirtual::ExtendedUpdate</a> call</li>
  804. <li>Sticking to the ground when walking down a slope through the <a class="el" href="class_character_virtual.html#ae03c43c12e8eb6496b8c8044c70b591f">CharacterVirtual::ExtendedUpdate</a> call</li>
  805. <li>Support for specifying a local coordinate system that allows e.g. <a href="https://github.com/jrouwe/JoltPhysics/blob/master/Samples/Tests/Character/CharacterSpaceShipTest.cpp">walking around in a flying space ship</a> that is equipped with 'inertial dampers' (a sci-fi concept often used in games).</li>
  806. </ul>
  807. <p><a class="el" href="class_character_virtual.html">CharacterVirtual</a> should provide everything that <a class="el" href="class_character.html">Character</a> provides. Since it is not a rigid body, it requires some extra consideration:</p><ul>
  808. <li>Collision callbacks are passed through the <a class="el" href="class_character_contact_listener.html">CharacterContactListener</a> instead of the <a class="el" href="class_contact_listener.html">ContactListener</a> class</li>
  809. <li><a class="el" href="class_character_virtual.html">CharacterVirtual</a> vs sensor contacts are also passed through this listener, you will not receive them through the regular <a class="el" href="class_contact_listener.html">ContactListener</a></li>
  810. <li><a class="el" href="class_character_virtual.html">CharacterVirtual</a> vs <a class="el" href="class_character_virtual.html">CharacterVirtual</a> collisions can be handled through the <a class="el" href="class_character_vs_character_collision.html">CharacterVsCharacterCollision</a> interface</li>
  811. <li>Collision checks (e.g. CastRay) do not collide with <a class="el" href="class_character_virtual.html">CharacterVirtual</a>. Use e.g. <code>NarrowPhaseQuery::CastRay(..., collector)</code> followed by <code><a class="el" href="class_character_virtual.html#a181bbafd30966b7ecc4313283c3a1252" title="Get the transformed shape that represents the volume of the character, can be used for collision chec...">CharacterVirtual::GetTransformedShape()</a>.CastRay(..., collector)</code> to include the collision results.</li>
  812. </ul>
  813. <p>You can create a hybrid between these two by setting <a class="el" href="class_character_virtual_settings.html#a894dfc1bbdcf975b2878430ed7df33ec">CharacterVirtualSettings::mInnerBodyShape</a>. This will create an inner rigid body that follows the movement of the <a class="el" href="class_character_virtual.html">CharacterVirtual</a>. This inner rigid body will be detected by sensors and regular collision tests.</p>
  814. <p>To get started take a look at the <a href="https://github.com/jrouwe/JoltPhysics/blob/master/Samples/Tests/Character/CharacterTest.cpp">Character</a> and <a href="https://github.com/jrouwe/JoltPhysics/blob/master/Samples/Tests/Character/CharacterVirtualTest.cpp">CharacterVirtual</a> examples.</p>
  815. <h1><a class="anchor" id="the-simulation-step"></a>
  816. The Simulation Step</h1>
  817. <p>The simulation step <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> uses jobs (<a class="el" href="class_job_system.html">JobSystem</a>) to perform the needed work. This allows spreading the workload across multiple CPU's. We use a Sequential Impulse solver with warm starting as described in <a href="https://box2d.org/files/ErinCatto_ModelingAndSolvingConstraints_GDC2009.pdf">Modeling and Solving Constraints - Erin Catto</a></p>
  818. <p>Each physics step can be divided into multiple collision steps. So if you run the simulation at 60 Hz with 2 collision steps we run:</p>
  819. <ul>
  820. <li>Collision (1/120s)</li>
  821. <li>Integration (1/120s)</li>
  822. <li>Collision (1/120s)</li>
  823. <li>Integration (1/120s)</li>
  824. </ul>
  825. <p>In general, the system is stable when running at 60 Hz with 1 collision step.</p>
  826. <h1><a class="anchor" id="conventions-and-limits"></a>
  827. Conventions and Limits</h1>
  828. <p>Jolt Physics uses a right handed coordinate system with Y-up. It is easy to use another axis as up axis by changing the gravity vector using <a class="el" href="class_physics_system.html#ad09c12009bbcb0d0e6dbfd9582593be4">PhysicsSystem::SetGravity</a>. Some shapes like the <a class="el" href="class_height_field_shape_settings.html">HeightFieldShape</a> will need an additional <a class="el" href="class_rotated_translated_shape_settings.html">RotatedTranslatedShape</a> to rotate it to the new up axis and vehicles (<a class="el" href="class_vehicle_constraint_settings.html">VehicleConstraint</a>) and characters (<a class="el" href="class_character_base_settings.html">CharacterBaseSettings</a>) will need their new up-axis specified too.</p>
  829. <p>We use column-major vectors and matrices, this means that to transform a point you need to multiply it on the right hand side: TransformedPoint = <a class="el" href="class_matrix.html" title="Templatized matrix class.">Matrix</a> * Point.</p>
  830. <p>Note that the physics simulation works best if you use SI units (meters, radians, seconds, kg). In order for the simulation to be accurate, dynamic objects should be in the order [0.1, 10] meters long, have speeds in the order of [0, 500] m/s and have gravity in the order of [0, 10] m/s^2. Static object should be in the order [0.1, 2000] meter long. If you are using different units, consider scaling the objects before passing them on to the physics simulation.</p>
  831. <h1><a class="anchor" id="big-worlds"></a>
  832. Big Worlds</h1>
  833. <p>By default the library compiles using floats. This means that the simulation gets less accurate the further you go from the origin. If all simulation takes place within roughly 5 km from the origin, floating point precision is accurate enough.</p>
  834. <p>If you have a bigger world, you may want to compile the library using the JPH_DOUBLE_PRECISION define. When you do this, all positions will be stored as doubles, which will make the simulation accurate even at thousands of kilometers away from the origin.</p>
  835. <p>Calculations with doubles are much slower than calculations with floats. A naive implementation that changes all calculations to doubles has been measured to run more than 2x slower than the same calculations using floats. Because of this, Jolt Physics will only use doubles where necessary and drop down to floats as soon as possible. In order to do this, many of the collision query functions will need a 'base offset'. All collision results will be returned as floats relative to this base offset. By choosing the base offset wisely (i.e. close to where collision results are expected) the results will be accurate. Make sure your base offset is not kilometers away from the collision result.</p>
  836. <p>Keep in mind that:</p>
  837. <ul>
  838. <li>There are a lot of 'epsilons' in the code that have been tuned for objects of sizes/speeds as described in the <a class="el" href="#conventions-and-limits">Conventions and Limits</a> section. Try to keep the individual objects to the specified scale even if they're really far from the origin.</li>
  839. <li>When the collision results of a single query are kilometers apart, precision will suffer as they will be far away from the 'base offset'.</li>
  840. <li>The effectiveness of the broad phase (which works in floats) will become less at large distances from the origin, e.g. at 10000 km from the origin, the resolution of the broad phase is reduced to 1 m which means that everything that's closer than 1 m will be considered colliding. This will not impact the quality of the simulation but it will result in extra collision tests in the narrow phase so will hurt performance.</li>
  841. </ul>
  842. <p>Because of the minimal use of doubles, the simulation runs 5-10% slower in double precision mode compared to float precision mode.</p>
  843. <h1><a class="anchor" id="space-simulations"></a>
  844. Space Simulations</h1>
  845. <p>There are a number of things that make Jolt not immediately suitable for space simulations:</p>
  846. <ul>
  847. <li>The broadphase uses floats internally so will become less accurate at large distances from the origin. This limits its efficiency.</li>
  848. <li>Jolt stores velocities in floats, so the large velocities that are common in space will become inaccurate. This will especially be visible if you create an object with constraints (e.g. a ragdoll) and make it move at high speeds. The relative velocities between the bodies will be too low for a float to represent accurately, which means that the constraints will not be solved properly.</li>
  849. <li>Rotations (<a class="el" href="class_quat.html">Quat</a>) are tracked in floats. If you intend to rotate a planet and expect objects on the surface of the planet to stay on the surface, you'll run into accuracy issues. For this reason it is not possible to rotate a RVec3 by a <a class="el" href="class_quat.html">Quat</a>.</li>
  850. </ul>
  851. <p>It is possible to work around this limitations to create a space simulation with Jolt as <a href="https://store.steampowered.com/app/392160/X4_Foundations/">X4 Foundations</a> has demonstrated.</p>
  852. <p>First of all, everything mentioned in the <a class="el" href="#big-worlds">Big Worlds</a> section is applicable.</p>
  853. <p>Secondly, split the universe into multiple PhysicsSystems and keep objects in each <a class="el" href="class_physics_system.html">PhysicsSystem</a> close to the origin and with low velocities. E.g.:</p><ul>
  854. <li>A ship that is traveling near light speed can happen in a <a class="el" href="class_physics_system.html">PhysicsSystem</a> that is traveling at near light speed. The ship would be near static in this <a class="el" href="class_physics_system.html">PhysicsSystem</a> so that any constrained parts move at low velocities. Note that Jolt will be unaware of the speed of the <a class="el" href="class_physics_system.html">PhysicsSystem</a>.</li>
  855. <li>A planet exists in its own <a class="el" href="class_physics_system.html">PhysicsSystem</a> where it is static. Rotation of the planet around its axis or around its sun is not modeled in Jolt but applied as an additional matrix transform when rendering the world. This has the advantage that the objects on the planet are completely static so that there is no constant overhead of updating the transforms of bodies.</li>
  856. <li>Consider representing objects at different scales in different ways. E.g. a ship can be simplified to a simple shape when flying through an asteroid field, this means it can move at much higher speeds while still providing reasonably accurate collision than when it consists of multiple bodies connected with constraints.</li>
  857. </ul>
  858. <p>The consequence of this approach is that objects may need to be moved between PhysicsSystems as e.g. a ship enters the atmosphere of a planet. You can use <a class="el" href="class_body.html#aad1ce1d84e95cab008fb239465b3496f" title="Debug function to convert a body back to a body creation settings object to be able to save/recreate ...">Body::GetBodyCreationSettings</a> to get the settings of a <a class="el" href="class_body.html">Body</a> and create it in the other world in the normal way. For Constraints there is <a class="el" href="class_constraint.html#a2cb32f0fbbc03050fd09c975e01277d2" title="Debug function to convert a constraint to its settings, note that this will not save to which bodies ...">Constraint::GetConstraintSettings</a>.</p>
  859. <h1><a class="anchor" id="deterministic-simulation"></a>
  860. Deterministic Simulation</h1>
  861. <p>The physics simulation is deterministic provided that:</p>
  862. <ul>
  863. <li>The APIs that modify the simulation are called in exactly the same order. For example, bodies and constraints need to be added/removed/modified in exactly the same order so that the state at the beginning of a simulation step is exactly the same for both simulations (<a class="el" href="#sloppy-determinism">exceptions</a>).</li>
  864. <li>The same binary code is used to run the simulation. For example, when you run the simulation on Windows it doesn't matter if you have an AMD or Intel processor.</li>
  865. </ul>
  866. <p>If you want cross platform determinism then please turn on the CROSS_PLATFORM_DETERMINISTIC option in CMake. This will make the library approximately 8% slower but the simulation will be deterministic regardless of:</p>
  867. <ul>
  868. <li>Compiler used to compile the library (tested MSVC2022, clang, gcc and emscripten)</li>
  869. <li>Configuration (Debug, Release or Distribution)</li>
  870. <li>OS (tested Windows, macOS, Linux)</li>
  871. <li>Architecture (x86 or ARM).</li>
  872. </ul>
  873. <p>Some caveats:</p>
  874. <ul>
  875. <li>The same source code must be used to compile the library on all platforms.</li>
  876. <li>The source code must be compiled with the same defines, e.g. you can't have one platform using JPH_DOUBLE_PRECISION and another not.</li>
  877. <li>Broadphase queries (<a class="el" href="class_broad_phase_query.html">BroadPhaseQuery</a>) are NOT deterministic because the broad phase can be modified from multiple threads. As bodies are modified, their bounding boxes get widened until the next maintenance update. This may be several calls to <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> later. If you want to do a broadphase query determinisically then create a custom <a class="el" href="class_collision_collector.html" title="Virtual interface that allows collecting multiple collision results.">CollisionCollector</a> that in its AddHit function repeats the query against the actual bounding box of the body (<a class="el" href="class_body.html#a2be34f0150bb5f520f21330ee6b7cb41" title="Get world space bounding box.">Body::GetWorldSpaceBounds</a>) and accept only hits that collide with this bounding box. Also ensure that you order the results consistently.</li>
  878. <li>Narrowphase queries (<a class="el" href="class_narrow_phase_query.html">NarrowPhaseQuery</a>) will return consistent results, but the order in which the results are received can change. This is again due the fact that the broadphase can be modified from multiple threads.</li>
  879. </ul>
  880. <p>It is quite difficult to verify cross platform determinism, so this feature is less tested than other features. With every build, the following architectures are verified to produce the same results:</p>
  881. <ul>
  882. <li>Windows MSVC x86 64-bit with AVX2</li>
  883. <li>Windows MSVC x86 32-bit with SSE2</li>
  884. <li>macOS clang ARM 64-bit with NEON</li>
  885. <li>Linux clang x86 64-bit with AVX2</li>
  886. <li>Linux clang ARM 64-bit with NEON</li>
  887. <li>Linux clang ARM 32-bit</li>
  888. <li>Linux gcc x86 64-bit with AVX2</li>
  889. <li>Linux gcc ARM 64-bit with NEON</li>
  890. <li>Linux gcc RISC-V 64-bit</li>
  891. <li>Linux gcc PowerPC (Little Endian) 64-bit</li>
  892. <li>Linux gcc LoongArch 64-bit</li>
  893. <li>WASM32 emscripten running in nodejs</li>
  894. <li>WASM64 emscripten running in nodejs</li>
  895. </ul>
  896. <p>The most important things to look out for in your own application:</p>
  897. <ul>
  898. <li>Compile your application mode in Precise mode (clang: -ffp-model=precise, MSVC: /fp:precise)</li>
  899. <li>Turn off floating point contract operations (clang: -ffp-contract=off)</li>
  900. <li>Make sure the FPU state is consistent across platforms / threads. Check the floating point rounding behavior (should be nearest). Check that the denormals are zero (DAZ) and flush to zero (FTZ) flags are set consistently.</li>
  901. <li>Do not use the standard trigonometry functions (<code>sin</code>, <code>cos</code> etc.) as they have different implementations on different platforms, use Jolt's functions (<a class="el" href="_trigonometry_8h.html#a89091907eb3da97f690e324849d773cb">Sin</a>, <a class="el" href="_trigonometry_8h.html#a40fafb1c427199b6855d704fc79cd1cf">Cos</a> etc.).</li>
  902. <li>Do not use <code>std::sort</code> as it has a different implementation on different platforms, use <a class="el" href="_quick_sort_8h.html#a09973cb7cb8a1e98a51005ecedaf6eff">QuickSort</a> instead.</li>
  903. <li>Do not use <code>std::push_heap</code> and <code>std::pop_heap</code> as it has a different implementation on different platforms when elements are equal, use <a class="el" href="_binary_heap_8h.html#ad87bf12de089dabad479dd7535aa997e">BinaryHeapPush</a>/<a class="el" href="_binary_heap_8h.html#aa90b54155ed2d5a542d7d693dc73e89b">BinaryHeapPop</a> instead.</li>
  904. <li>Do not use <code>std::hash</code> as it is also platform dependent, use <a class="el" href="struct_hash.html">Hash</a> instead.</li>
  905. </ul>
  906. <p>When running the Samples Application you can press ESC, Physics Settings and check the 'Check Determinism' checkbox. Before every simulation step we will record the state using the <a class="el" href="class_state_recorder.html">StateRecorder</a> interface, rewind the simulation and do the step again to validate that the simulation runs deterministically. Some of the tests (e.g. the MultiThreaded) test will explicitly disable the check because they randomly add/remove bodies from different threads. This violates the rule that the API calls must be done in the same order so will not result in a deterministic simulation.</p>
  907. <h1><a class="anchor" id="rolling-back-a-simulation"></a>
  908. Rolling Back a Simulation</h1>
  909. <p>When synchronizing two simulations via a network, it is possible that a change that needed to be applied at frame N is received at frame N + M. This will require rolling back the simulation to the state of frame N and repeating the simulation with the new inputs. This can be implemented by saving the physics state using <a class="el" href="class_physics_system.html#ae13975e609ff125fa02b922795777824">SaveState</a> at every frame. To roll back, call <a class="el" href="class_physics_system.html#a09379b63a92e2e0f449f1665d2aa00be">RestoreState</a> with the state at frame N. SaveState only records the state that the physics engine modifies during its update step (positions, velocities etc.), so if you change anything else you need to restore this yourself. E.g. if you did a <a class="el" href="class_body.html#af3576faa64307d6d9318a7c0dad47d21">SetFriction</a> on frame N + 2 then, when rewinding, you need to restore the friction to what is was on frame N and update it again on frame N + 2 when you replay. If you start adding/removing objects (e.g. bodies or constraints) during these frames, the RestoreState function will not work. If you added a body on frame N + 1, you'll need to remove it when rewinding and then add it back on frame N + 1 again (with the proper initial position/velocity etc. because it won't be contained in the snapshot at frame N). The <a class="el" href="class_physics_system.html#ae13975e609ff125fa02b922795777824">SaveState</a> function comes with a <a class="el" href="class_state_recorder_filter.html" title="User callbacks that allow determining which parts of the simulation should be saved by a StateRecorde...">StateRecorderFilter</a> interface that you can use to selectively save state. E.g. <a class="el" href="class_state_recorder_filter.html#af6eb66653cea36732871dbc269e8a59c">ShouldSaveBody</a> could simply return false for all static or inactive bodies which can be used to limit the size of the snapshot.</p>
  910. <p>If you wish to share saved state between server and client, you need to ensure that all APIs that modify the state of the world are called in the exact same order. So if the client creates physics objects for player 1 then 2 and the server creates the objects for 2 then 1 you already have a problem (the body IDs will be different, which will render the save state snapshots incompatible). When rolling back a simulation, you'll also need to ensure that the BodyIDs are kept the same, so you need to remove/add the body from/to the physics system instead of destroy/re-create them or you need to create bodies with the same ID on both sides using <a class="el" href="class_body_interface.html#a6ce6c1e2646429777f65e66e7a21e05b">BodyInterface::CreateBodyWithID</a>.</p>
  911. <h1><a class="anchor" id="sloppy-determinism"></a>
  912. Being Sloppy While Still Being Deterministic</h1>
  913. <p>If you do things in the same order it is guaranteed to be deterministic, but if you know what you're doing you can take some liberties. E.g. doing <code>BodyA.SetFriction(...); BodyB.SetFriction(...);</code> or <code>BodyB.SetFriction(...); BodyA.SetFriction(...);</code> doesn't matter for determinism, the main thing you need to ensure is that when you do a <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> that the binary state is the same. Also adding body A then B is the same as B then A as long as the BodyIDs of A and B are consistent. For constraints, adding A then B or B then A is equivalent as long as <a class="el" href="class_constraint_settings.html#ab01ba90506d17f415054bfa6208a4939">ConstraintSettings::mConstraintPriority</a> is unique per constraint so that it defines a consistent ordering (in this case all constraints in the system must have a unique number). Note though that <a class="el" href="class_physics_system.html#ae13975e609ff125fa02b922795777824" title="Saving state for replay.">PhysicsSystem::SaveState</a> relies on the ordering of constraints, so you'll have to skip serializing constraints by not setting <a class="el" href="_state_recorder_8h.html#ac746db0a34def4dfd77ccd487ae36eb4aa5d083fbfc0611e061663c6b1a8ba698" title="Save the state of constraints.">EStateRecorderState::Constraints</a> and call <a class="el" href="class_constraint.html#a829eb3dda397de5cc7a7799ce959cc8b" title="Saving state for replay.">Constraint::SaveState</a> / <a class="el" href="class_constraint.html#a9a8b58f759bee231ebbfc7147041a0b7" title="Restoring state for replay.">Constraint::RestoreState</a> directly yourself.</p>
  914. <h1><a class="anchor" id="working-with-multiple-physics-systems"></a>
  915. Working With Multiple Physics Systems</h1>
  916. <p>You can create, simulate and interact with multiple PhysicsSystems at the same time provided that you do not share any objects (bodies, constraints) between the systems. When a <a class="el" href="class_body.html">Body</a> is created it receives a <a class="el" href="class_body_i_d.html" title="ID of a body. This is a way of reasoning about bodies in a multithreaded simulation while avoiding ra...">BodyID</a> that is unique for the <a class="el" href="class_physics_system.html">PhysicsSystem</a> that it was created for, so it cannot be shared. The only object that can be shared between PhysicsSystems is a <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a>. If you want to move a body from one <a class="el" href="class_physics_system.html">PhysicsSystem</a> to another, use <a class="el" href="class_body.html#aad1ce1d84e95cab008fb239465b3496f" title="Debug function to convert a body back to a body creation settings object to be able to save/recreate ...">Body::GetBodyCreationSettings</a> to get the settings needed to create the body in the other <a class="el" href="class_physics_system.html">PhysicsSystem</a>.</p>
  917. <p>PhysicsSystems are not completely independent:</p>
  918. <ul>
  919. <li>There is only 1 <a class="el" href="class_r_t_t_i.html">RTTI</a> factory (<a class="el" href="class_factory.html#afdbac3e3e59f7981d7dec696e914e69f" title="Singleton factory instance.">Factory::sInstance</a>).</li>
  920. <li>There is only 1 default material (<a class="el" href="class_physics_material.html#af51825c643c3cafc49e007d8ca1c14cd" title="Default material that is used when a shape has no materials defined.">PhysicsMaterial::sDefault</a>).</li>
  921. <li>There is only 1 debug renderer (<a class="el" href="class_debug_renderer.html#ab03458cbd419bc22da1d176b27ce74ea" title="Singleton instance.">DebugRenderer::sInstance</a>) although many functions take a custom <a class="el" href="class_debug_renderer.html">DebugRenderer</a> for drawing.</li>
  922. <li>Custom shapes and <a class="el" href="class_collision_dispatch.html" title="Dispatch function, main function to handle collisions between shapes.">CollisionDispatch</a> functions are shared.</li>
  923. <li>The custom memory allocation functions (e.g. Allocate), Trace and AssertFailed functions are shared.</li>
  924. </ul>
  925. <p>These functions / systems need to be registered in advance.</p>
  926. <h1><a class="anchor" id="debug-rendering"></a>
  927. Debug Rendering</h1>
  928. <p>When the define JPH_DEBUG_RENDERER is defined (which by default is defined in Debug and Release but not Distribution), Jolt is able to render its internal state. To integrate this into your own application you must inherit from the <a class="el" href="class_debug_renderer.html">DebugRenderer</a> class and implement the pure virtual functions <a class="el" href="class_debug_renderer.html#acea9470f13a1d50b677e2aaaeb9eeaed" title="Draw line.">DebugRenderer::DrawLine</a>, <a class="el" href="class_debug_renderer.html#afc6b62590e5a26de8cbd98a29bf8b1a3" title="Draw a single back face culled triangle.">DebugRenderer::DrawTriangle</a>, <a class="el" href="class_debug_renderer.html#a9537e347fe16d3d0c55e8409299a1979" title="Create a batch of triangles that can be drawn efficiently.">DebugRenderer::CreateTriangleBatch</a>, <a class="el" href="class_debug_renderer.html#a9542e23f59dcb2dbe19d5cc870e1efcf">DebugRenderer::DrawGeometry</a> and <a class="el" href="class_debug_renderer.html#a0caa614c01a9879eed46e55755884c75" title="Draw text.">DebugRenderer::DrawText3D</a>. The CreateTriangleBatch is used to prepare a batch of triangles to be drawn by a single DrawGeometry call, which means that Jolt can render a complex scene much more efficiently than when each triangle in that scene would have been drawn through DrawTriangle. At run-time create an instance of your <a class="el" href="class_debug_renderer.html">DebugRenderer</a> which will internally assign itself to <a class="el" href="class_debug_renderer.html#ab03458cbd419bc22da1d176b27ce74ea" title="Singleton instance.">DebugRenderer::sInstance</a>. Finally call for example <a class="el" href="class_physics_system.html#a8d4eda1c25d2c2e57a6964167870fe93" title="Draw the state of the bodies (debugging purposes)">PhysicsSystem::DrawBodies</a> or <a class="el" href="class_physics_system.html#a4fa500f710dcc423062fd1514fe07780" title="Draw the constraints only (debugging purposes)">PhysicsSystem::DrawConstraints</a> to draw the state of the simulation. For an example implementation see <a href="https://github.com/jrouwe/JoltPhysics/blob/master/TestFramework/Renderer/DebugRendererImp.h">the DebugRenderer from the Samples application</a> or to get started quickly take a look at <a class="el" href="class_debug_renderer_simple.html">DebugRendererSimple</a>.</p>
  929. <h1><a class="anchor" id="memory-management"></a>
  930. Memory Management</h1>
  931. <p>Jolt uses reference counting for a number of its classes (everything that inherits from <a class="el" href="class_ref_target.html">RefTarget</a>). The most important classes are:</p>
  932. <ul>
  933. <li><a class="el" href="class_shape_settings.html">ShapeSettings</a></li>
  934. <li><a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a></li>
  935. <li><a class="el" href="class_constraint_settings.html" title="Class used to store the configuration of a constraint. Allows run-time creation of constraints.">ConstraintSettings</a></li>
  936. <li><a class="el" href="class_constraint.html" title="Base class for all physics constraints. A constraint removes one or more degrees of freedom for a rig...">Constraint</a></li>
  937. <li><a class="el" href="class_physics_material.html">PhysicsMaterial</a></li>
  938. <li><a class="el" href="class_group_filter.html" title="Abstract class that checks if two CollisionGroups collide.">GroupFilter</a></li>
  939. <li><a class="el" href="class_physics_scene.html" title="Contains the creation settings of a set of bodies.">PhysicsScene</a></li>
  940. <li><a class="el" href="class_soft_body_shared_settings.html">SoftBodySharedSettings</a></li>
  941. <li><a class="el" href="class_vehicle_collision_tester.html" title="Class that does collision detection between wheels and ground.">VehicleCollisionTester</a></li>
  942. <li><a class="el" href="class_vehicle_controller.html" title="Runtime data for interface that controls acceleration / deceleration of the vehicle.">VehicleController</a></li>
  943. <li><a class="el" href="class_wheel_settings.html" title="Base class for wheel settings, each VehicleController can implement a derived class of this.">WheelSettings</a></li>
  944. <li><a class="el" href="class_character_base_settings.html" title="Base class for configuration of a character.">CharacterBaseSettings</a></li>
  945. <li><a class="el" href="class_character_base.html" title="Base class for character class.">CharacterBase</a></li>
  946. <li><a class="el" href="class_ragdoll_settings.html" title="Contains the structure of a ragdoll.">RagdollSettings</a></li>
  947. <li><a class="el" href="class_ragdoll.html" title="Runtime ragdoll information.">Ragdoll</a></li>
  948. <li><a class="el" href="class_skeleton.html" title="Resource that contains the joint hierarchy for a skeleton.">Skeleton</a></li>
  949. <li><a class="el" href="class_skeletal_animation.html" title="Resource for a skinned animation.">SkeletalAnimation</a></li>
  950. <li><a class="el" href="class_skeleton_mapper.html" title="Class that is able to map a low detail (ragdoll) skeleton to a high detail (animation) skeleton and v...">SkeletonMapper</a></li>
  951. </ul>
  952. <p>Reference counting objects start with a reference count of 0. If you want to keep ownership of the object, you need to call <a class="el" href="class_ref_target.html#acf02c18a343bc9de9d6afb7c966f0363">object-&gt;AddRef()</a>, this will increment the reference count. If you want to release ownership you call <a class="el" href="class_ref_target.html#a0451661dd5d85b01f969319e767993eb">object-&gt;ReleaseRef()</a>, this will decrement the reference count and if the reference count reaches 0 the object will be destroyed. If, after newing, you pass a reference counted object on to another object (e.g. a <a class="el" href="class_shape_settings.html">ShapeSettings</a> to a <a class="el" href="class_compound_shape_settings.html" title="Base class settings to construct a compound shape.">CompoundShapeSettings</a> or a <a class="el" href="class_shape.html" title="Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...">Shape</a> to a <a class="el" href="class_body.html">Body</a>) then that other object will take a reference, in that case it is not needed take a reference yourself beforehand so you can skip the calls to <code>AddRef/Release</code>. Note that it is also possible to do <code>auto x = new XXX</code> followed by <code>delete x</code> for a reference counted object if no one ever took a reference. The safest way of working with reference counting objects is to use the <a class="el" href="class_ref.html">Ref</a> or <a class="el" href="class_ref_const.html">RefConst</a> classes, these automatically manage the reference count for you when assigning a new value or on destruction:</p>
  953. <div class="fragment"><div class="line">// Calls &#39;AddRef&#39; to keep a reference the shape</div>
  954. <div class="line">JPH::Ref&lt;Shape&gt; shape = new JPH::SphereShape(1.0f);</div>
  955. <div class="line"> </div>
  956. <div class="line">// Calls &#39;Release&#39; to release and delete the shape (note that this also happens if JPH::Ref goes out of scope)</div>
  957. <div class="line">shape = nullptr;</div>
  958. </div><!-- fragment --><p>The <a class="el" href="class_body.html">Body</a> class is a special case, it is destroyed through <a class="el" href="class_body_interface.html#a43fb4ffc35661c67642ffa804d1dad8a">BodyInterface::DestroyBody</a> (which internally destroys the <a class="el" href="class_body.html">Body</a>).</p>
  959. <p>Jolt also supports routing all of its internal allocations through a custom allocation function. See: <a class="el" href="_memory_8cpp.html#a409c61ab5ebd84e8aee6d9f930175a00">Allocate</a>, <a class="el" href="_memory_8cpp.html#ac6c32afa44df59108c68ef07ce8919bd">Reallocate</a>, <a class="el" href="_memory_8cpp.html#acb8618ad315c24ed37db3ad6b2ff60fc">Free</a>, <a class="el" href="_memory_8cpp.html#ae8854fb6cfcc5836d8e9f6103a3a6c68">AlignedAllocate</a> and <a class="el" href="_memory_8cpp.html#add39c49c5cd22c9ddbc25aae2c01b5f3">AlignedFree</a>.</p>
  960. <h1><a class="anchor" id="the-simulation-step-in-detail"></a>
  961. The Simulation Step in Detail</h1>
  962. <p>The job graph looks like this:</p>
  963. <div class="image">
  964. <object type="image/svg+xml" data="PhysicsSystemUpdate.svg" style="pointer-events: none;"></object>
  965. <div class="caption">
  966. Job Graph Physics Step</div></div>
  967. <p>Note that each job indicates if it reads/writes positions/velocities and if it deactivates/activates bodies. We do not allow jobs to read/write the same data concurrently. The arrows indicate the order in which jobs are executed. Yellow blocks mean that there are multiple jobs of this type. Dotted arrows have special meaning and are explained below.</p>
  968. <h2><a class="anchor" id="broad-phase-update-prepare"></a>
  969. Broad Phase Update Prepare</h2>
  970. <p>This job will refit the AABBs of the broad phase. It does this by building a new tree while keeping the old one available as described in the <a class="el" href="#broad-phase">Broad Phase</a> section.</p>
  971. <h2><a class="anchor" id="broad-phase-update-finalize"></a>
  972. Broad Phase Update Finalize</h2>
  973. <p>This job will simply swap the new tree with the old tree. The old tree will be discarded at the beginning of the next <a class="el" href="class_physics_system.html#a4cdc76b2486dfaecfc9319d040e5e5f3">PhysicsSystem::Update</a> call so that any broad phase query can continue to run.</p>
  974. <h2><a class="anchor" id="step-listeners-update"></a>
  975. Step Listeners</h2>
  976. <p>You can register one or more step listeners (See <a class="el" href="class_physics_system.html#a0964d49514b7447981dcc7438876e988">PhysicsSystem::AddStepListener</a>). This job will call <a class="el" href="class_physics_step_listener.html#ab4de6bf7f8150c3e4b3d4667c61674ea">PhysicsStepListener::OnStep</a> for every listener. This can be used to do work that needs to be done at the beginning of each step, e.g. set velocities on ragdoll bodies.</p>
  977. <h2><a class="anchor" id="apply-gravity-update"></a>
  978. Apply Gravity</h2>
  979. <p>A number of these jobs run in parallel. Each job takes a batch of active bodies and applies gravity and damping (updating linear and angular velocity).</p>
  980. <h2><a class="anchor" id="determine-active-constraints"></a>
  981. Determine Active Constraints</h2>
  982. <p>This job will go through all non-contact constraints and determine which constraints are active based on if the bodies that the constraint connects to are active.</p>
  983. <h2><a class="anchor" id="build-islands-from-constraints"></a>
  984. Build Islands from Constraints</h2>
  985. <p>This job will go through all non-contact constraints and assign the involved bodies and constraint to the same island. Since we allow concurrent insertion/removal of bodies we do not want to keep island data across multiple simulation steps, so we recreate the islands from scratch every simulation step. The operation is lock-free and O(N) where N is the number of constraints.</p>
  986. <p>If a constraint connects an active and a non-active body, the non-active body is woken up. One find collisions job will not start until this job has finished in order to pick up any collision testing for newly activated bodies.</p>
  987. <h2><a class="anchor" id="find-collisions"></a>
  988. Find Collisions</h2>
  989. <p>This job will do broad and narrow phase checks. Initially a number of jobs are started based on the amount of active bodies. The job will do the following:</p>
  990. <ul>
  991. <li>Take a batch of active bodies and collide them against the broadphase.</li>
  992. <li>When a collision pair is found it is inserted in a lock free queue to be processed later.</li>
  993. <li>If the queue is full, it will be processed immediately (more Find Collisions jobs are spawned if not all CPU cores are occupied yet as the queue starts to fill up).</li>
  994. <li>If there are no more active bodies to process, the job will start to perform narrow phase collision detection and set up contact constraints if any collisions are found.</li>
  995. <li>As soon as a narrow phase pair is processed it will recheck if there are new active bodies to be processed (active bodies can be generated by an active body colliding with an inactive body) and if so process them.</li>
  996. <li>When there are no more active bodies to test and no more collision pairs to be processed the job terminates.</li>
  997. </ul>
  998. <p>Note that this job cannot start until apply gravity is done because the velocity needs to be known for elastic collisions to be calculated properly.</p>
  999. <p>The contact points between the two bodies will be determined by the <a class="el" href="class_g_j_k_closest_point.html">GJK</a> and <a class="el" href="class_e_p_a_penetration_depth.html">EPA</a> algorithms. For each contact point we will calculate the face that belongs to that contact point. The faces of both bodies are clipped against each other (<a class="el" href="_manifold_between_two_faces_8cpp.html#a123ae234f8ce70366ab39456d853f522">ManifoldBetweenTwoFaces</a>) so that we have a polygon (or point / line) that represents the contact between the two bodies (contact manifold).</p>
  1000. <p>Multiple contact manifolds with similar normals are merged together (PhysicsSystem::ProcessBodyPair::ReductionCollideShapeCollector). After this the contact constraints are created in the <a class="el" href="class_contact_constraint_manager.html">ContactConstraintManager</a> and their Jacobians / effective masses calculated.</p>
  1001. <p>Contacting bodies are also linked together to form islands. This is the same operation as described in the <a class="el" href="#build-islands-from-constraints">Build Islands from Constraints</a> section.</p>
  1002. <p>The narrow phase makes use of a lock free contact cache. We have 2 caches, one that is used for reading (which contains the contacts from the previous step) and one for writing new contact pairs. When a contact point is preserved from the last simulation step, it will be copied from the read cache to the write cache.</p>
  1003. <h2><a class="anchor" id="setup-velocity-constraints"></a>
  1004. Setup Velocity Constraints</h2>
  1005. <p>This job will go through all non-contact constraints and prepare them for execution. This involves calculating Jacobians and effective masses for each constraint part.</p>
  1006. <h2><a class="anchor" id="finalize-islands"></a>
  1007. Finalize Islands</h2>
  1008. <p>This job will finalize the building of the simulation islands. Each island contains bodies that interact with each other through a contact point or through a constraint. These islands will be simulated separately in different jobs later. The finalization of the islands is an O(N) operation where N is the amount of active bodies (see <a class="el" href="class_island_builder.html#af8e0ac69b3e021ab24317116ded1c622">IslandBuilder::Finalize</a>).</p>
  1009. <h2><a class="anchor" id="set-body-island-idx"></a>
  1010. Set Body Island Idx</h2>
  1011. <p>This job does some housekeeping work that can be executed concurrent to the solver:</p>
  1012. <ul>
  1013. <li>It will assign the island ID to all bodies (which is mainly used for debugging purposes)</li>
  1014. </ul>
  1015. <h2><a class="anchor" id="solve-velocity-constraints"></a>
  1016. Solve Velocity Constraints</h2>
  1017. <p>A number of these jobs will run in parallel. Each job takes the next unprocessed island and will run the iterative constraint solver for that island. It will first apply the impulses applied from the previous simulation step (which are stored in the contact cache) to warm start the solver. It will then repeatedly iterate over all contact and non-contact constraints until either the applied impulses are too small or a max iteration count is reached (<a class="el" href="struct_physics_settings.html#a66af679ba7f202b402bb23d0a0e117ad">PhysicsSettings::mNumVelocitySteps</a>). The result will be that the new velocities are known for all active bodies. The applied impulses are stored in the contact cache for the next step.</p>
  1018. <p>When an island consists of more than <a class="el" href="class_large_island_splitter.html#a86a79602d9b93ec4a0c5837465a70b0a" title="If the number of constraints + contacts in an island is larger than this, we will try to split the is...">LargeIslandSplitter::cLargeIslandTreshold</a> contacts plus constraints it is considered a large island. In order to not do all work on a single thread, this island will be split up by the <a class="el" href="class_large_island_splitter.html">LargeIslandSplitter</a>. This follows an algorithm described in High-Performance Physical Simulations on Next-Generation Architecture with Many Cores by Chen et al. This is basically a greedy algorithm that tries to group contacts and constraints into groups where no contact or constraint affects the same body. Within a group, the order of execution does not matter since every memory location is only read/written once, so we can parallelize the update. At the end of each group, we need to synchronize the CPU cores before starting on the next group. When the number of groups becomes too large, a final group is created that contains all other contacts and constraints and these are solved on a single thread. The groups are processed <a class="el" href="struct_physics_settings.html#a66af679ba7f202b402bb23d0a0e117ad">PhysicsSettings::mNumVelocitySteps</a> times so the end result is almost the same as an island that was not split up (only the evaluation order changes in a consistent way).</p>
  1019. <h2><a class="anchor" id="pre-integrate"></a>
  1020. Pre Integrate</h2>
  1021. <p>This job prepares the CCD buffers.</p>
  1022. <h2><a class="anchor" id="integrate-and-clamp-velocities"></a>
  1023. Integrate &amp; Clamp Velocities</h2>
  1024. <p>This job will integrate the velocity and update the position. It will clamp the velocity to the max velocity.</p>
  1025. <p>Depending on the motion quality (<a class="el" href="_motion_quality_8h.html#af43db3453103c2e62526f54dd8542d3a">EMotionQuality</a>) of the body, it will schedule a body for continuous collision detection (CCD) if its movement is bigger than some threshold based on the <a class="el" href="class_shape.html#a249fa4e0fc7fdd25071be9f45db6a25a">inner radius</a>) of the shape.</p>
  1026. <h2><a class="anchor" id="post-integrate"></a>
  1027. Post Integrate</h2>
  1028. <p>Find CCD Contact jobs are created on the fly depending on how many CCD bodies were found. If there are no CCD bodies it will immediately start Resolve CCD Contacts.</p>
  1029. <h2><a class="anchor" id="find-ccd-contacts"></a>
  1030. Find CCD Contacts</h2>
  1031. <p>A number of jobs will run in parallel and pick up bodies that have been scheduled for CCD and will do a linear cast to detect the first collision. It always allows movement of the object by a fraction if its inner radius in order to prevent it from getting fully stuck.</p>
  1032. <h2><a class="anchor" id="resolve-ccd-contacts"></a>
  1033. Resolve CCD Contacts</h2>
  1034. <p>This job will take the collision results from the previous job and update position and velocity of the involved bodies. If an object hits another object, its time will be 'stolen' (it will move less far than it should according to its velocity).</p>
  1035. <h2><a class="anchor" id="finalize-contact-cache"></a>
  1036. Finalize Contact Cache, Contact Removed Callbacks</h2>
  1037. <p>This job will:</p>
  1038. <ul>
  1039. <li>Swap the read/write contact cache and prepare the contact cache for the next step.</li>
  1040. <li>It will detect all contacts that existed previous step and do not exist anymore to fire callbacks for them through the <a class="el" href="class_contact_listener.html">ContactListener</a> interface.</li>
  1041. </ul>
  1042. <h2><a class="anchor" id="solve-position-constraints"></a>
  1043. Solve Position Constraints, Update Bodies Broad Phase</h2>
  1044. <p>A number of these jobs will run in parallel. Each job takes the next unprocessed island and run the position based constraint solver. This fixes numerical drift that may have caused constrained bodies to separate (remember that the constraints are solved in the velocity domain, so errors get introduced when doing a linear integration step). It will run until either the applied position corrections are too small or until the max amount of iterations is reached (<a class="el" href="struct_physics_settings.html#a3724f8c1ef9269076dac93c4d7b7cfdb">PhysicsSettings::mNumPositionSteps</a>). Here there is also support for large islands, the island splits that were calculated in the Solve Velocity Constraints job are reused to solve partial islands in the same way as before.</p>
  1045. <p>It will also notify the broad phase of the new body positions / AABBs.</p>
  1046. <p>When objects move too little the body will be put to sleep. This is detected by taking the biggest two axis of the local space bounding box of the shape together with the center of mass of the shape (all points in world space) and keep track of 3 bounding spheres for those points over time. If the bounding spheres become too big, the bounding spheres are reset and the timer restarted. When the timer reaches a certain time, the object has is considered non-moving and is put to sleep.</p>
  1047. <h2><a class="anchor" id="soft-body-prepare"></a>
  1048. Soft Body Prepare</h2>
  1049. <p>If there are any active soft bodies, this job will create the Soft <a class="el" href="class_body.html">Body</a> Collide, Simulate and Finalize Jobs. It will also create a list of sorted SoftBodyUpdateContext objects that forms the context for those jobs.</p>
  1050. <h2><a class="anchor" id="soft-body-collide"></a>
  1051. Soft Body Collide</h2>
  1052. <p>These jobs will do broadphase checks for all of the soft bodies. A thread picks up a single soft body and uses the bounding box of the soft body to find intersecting rigid bodies. Once found, information will be collected about that rigid body so that Simulate can run in parallel.</p>
  1053. <h2><a class="anchor" id="soft-body-simulate"></a>
  1054. Soft Body Simulate</h2>
  1055. <p>These jobs will do the actual simulation of the soft bodies. They first collide batches of soft body vertices with the rigid bodies found during the Collide job (multiple threads can work on a single soft body) and then perform the simulation using XPBD (also partially distributing a single soft body on multiple threads).</p>
  1056. <h2><a class="anchor" id="soft-body-finalize"></a>
  1057. Soft Body Finalize</h2>
  1058. <p>This job writes back all the rigid body velocity changes and updates the positions and velocities of the soft bodies. It can activate/deactivate bodies as needed. </p>
  1059. </div></div><!-- PageDoc -->
  1060. <a href="doxygen_crawl.html"></a>
  1061. </div><!-- contents -->
  1062. </div><!-- doc-content -->
  1063. <!-- start footer part -->
  1064. <div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  1065. <ul>
  1066. <li class="footer">Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.12.0 </li>
  1067. </ul>
  1068. </div>
  1069. </body>
  1070. </html>