physics_ammo_break.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. <html lang="en">
  2. <head>
  3. <title>Convex object breaking example</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <link type="text/css" rel="stylesheet" href="main.css">
  7. <style>
  8. body {
  9. color: #333;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <div id="info">Physics threejs demo with convex objects breaking in real time<br />Press mouse to throw balls and move the camera.</div>
  15. <div id="container"></div>
  16. <script src="js/libs/ammo.wasm.js"></script>
  17. <!-- Import maps polyfill -->
  18. <!-- Remove this when import maps will be widely supported -->
  19. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  20. <script type="importmap">
  21. {
  22. "imports": {
  23. "three": "../build/three.module.js"
  24. }
  25. }
  26. </script>
  27. <script type="module">
  28. import * as THREE from 'three';
  29. import Stats from './jsm/libs/stats.module.js';
  30. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  31. import { ConvexObjectBreaker } from './jsm/misc/ConvexObjectBreaker.js';
  32. import { ConvexGeometry } from './jsm/geometries/ConvexGeometry.js';
  33. // - Global variables -
  34. // Graphics variables
  35. let container, stats;
  36. let camera, controls, scene, renderer;
  37. let textureLoader;
  38. const clock = new THREE.Clock();
  39. const mouseCoords = new THREE.Vector2();
  40. const raycaster = new THREE.Raycaster();
  41. const ballMaterial = new THREE.MeshPhongMaterial( { color: 0x202020 } );
  42. // Physics variables
  43. const gravityConstant = 7.8;
  44. let collisionConfiguration;
  45. let dispatcher;
  46. let broadphase;
  47. let solver;
  48. let physicsWorld;
  49. const margin = 0.05;
  50. const convexBreaker = new ConvexObjectBreaker();
  51. // Rigid bodies include all movable objects
  52. const rigidBodies = [];
  53. const pos = new THREE.Vector3();
  54. const quat = new THREE.Quaternion();
  55. let transformAux1;
  56. let tempBtVec3_1;
  57. const objectsToRemove = [];
  58. for ( let i = 0; i < 500; i ++ ) {
  59. objectsToRemove[ i ] = null;
  60. }
  61. let numObjectsToRemove = 0;
  62. const impactPoint = new THREE.Vector3();
  63. const impactNormal = new THREE.Vector3();
  64. // - Main code -
  65. Ammo().then( function ( AmmoLib ) {
  66. Ammo = AmmoLib;
  67. init();
  68. animate();
  69. } );
  70. // - Functions -
  71. function init() {
  72. initGraphics();
  73. initPhysics();
  74. createObjects();
  75. initInput();
  76. }
  77. function initGraphics() {
  78. container = document.getElementById( 'container' );
  79. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  80. scene = new THREE.Scene();
  81. scene.background = new THREE.Color( 0xbfd1e5 );
  82. camera.position.set( - 14, 8, 16 );
  83. renderer = new THREE.WebGLRenderer();
  84. renderer.setPixelRatio( window.devicePixelRatio );
  85. renderer.setSize( window.innerWidth, window.innerHeight );
  86. renderer.shadowMap.enabled = true;
  87. container.appendChild( renderer.domElement );
  88. controls = new OrbitControls( camera, renderer.domElement );
  89. controls.target.set( 0, 2, 0 );
  90. controls.update();
  91. textureLoader = new THREE.TextureLoader();
  92. const ambientLight = new THREE.AmbientLight( 0x707070 );
  93. scene.add( ambientLight );
  94. const light = new THREE.DirectionalLight( 0xffffff, 1 );
  95. light.position.set( - 10, 18, 5 );
  96. light.castShadow = true;
  97. const d = 14;
  98. light.shadow.camera.left = - d;
  99. light.shadow.camera.right = d;
  100. light.shadow.camera.top = d;
  101. light.shadow.camera.bottom = - d;
  102. light.shadow.camera.near = 2;
  103. light.shadow.camera.far = 50;
  104. light.shadow.mapSize.x = 1024;
  105. light.shadow.mapSize.y = 1024;
  106. scene.add( light );
  107. stats = new Stats();
  108. stats.domElement.style.position = 'absolute';
  109. stats.domElement.style.top = '0px';
  110. container.appendChild( stats.domElement );
  111. //
  112. window.addEventListener( 'resize', onWindowResize );
  113. }
  114. function initPhysics() {
  115. // Physics configuration
  116. collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
  117. dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  118. broadphase = new Ammo.btDbvtBroadphase();
  119. solver = new Ammo.btSequentialImpulseConstraintSolver();
  120. physicsWorld = new Ammo.btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration );
  121. physicsWorld.setGravity( new Ammo.btVector3( 0, - gravityConstant, 0 ) );
  122. transformAux1 = new Ammo.btTransform();
  123. tempBtVec3_1 = new Ammo.btVector3( 0, 0, 0 );
  124. }
  125. function createObject( mass, halfExtents, pos, quat, material ) {
  126. const object = new THREE.Mesh( new THREE.BoxGeometry( halfExtents.x * 2, halfExtents.y * 2, halfExtents.z * 2 ), material );
  127. object.position.copy( pos );
  128. object.quaternion.copy( quat );
  129. convexBreaker.prepareBreakableObject( object, mass, new THREE.Vector3(), new THREE.Vector3(), true );
  130. createDebrisFromBreakableObject( object );
  131. }
  132. function createObjects() {
  133. // Ground
  134. pos.set( 0, - 0.5, 0 );
  135. quat.set( 0, 0, 0, 1 );
  136. const ground = createParalellepipedWithPhysics( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  137. ground.receiveShadow = true;
  138. textureLoader.load( 'textures/grid.png', function ( texture ) {
  139. texture.wrapS = THREE.RepeatWrapping;
  140. texture.wrapT = THREE.RepeatWrapping;
  141. texture.repeat.set( 40, 40 );
  142. ground.material.map = texture;
  143. ground.material.needsUpdate = true;
  144. } );
  145. // Tower 1
  146. const towerMass = 1000;
  147. const towerHalfExtents = new THREE.Vector3( 2, 5, 2 );
  148. pos.set( - 8, 5, 0 );
  149. quat.set( 0, 0, 0, 1 );
  150. createObject( towerMass, towerHalfExtents, pos, quat, createMaterial( 0xB03014 ) );
  151. // Tower 2
  152. pos.set( 8, 5, 0 );
  153. quat.set( 0, 0, 0, 1 );
  154. createObject( towerMass, towerHalfExtents, pos, quat, createMaterial( 0xB03214 ) );
  155. //Bridge
  156. const bridgeMass = 100;
  157. const bridgeHalfExtents = new THREE.Vector3( 7, 0.2, 1.5 );
  158. pos.set( 0, 10.2, 0 );
  159. quat.set( 0, 0, 0, 1 );
  160. createObject( bridgeMass, bridgeHalfExtents, pos, quat, createMaterial( 0xB3B865 ) );
  161. // Stones
  162. const stoneMass = 120;
  163. const stoneHalfExtents = new THREE.Vector3( 1, 2, 0.15 );
  164. const numStones = 8;
  165. quat.set( 0, 0, 0, 1 );
  166. for ( let i = 0; i < numStones; i ++ ) {
  167. pos.set( 0, 2, 15 * ( 0.5 - i / ( numStones + 1 ) ) );
  168. createObject( stoneMass, stoneHalfExtents, pos, quat, createMaterial( 0xB0B0B0 ) );
  169. }
  170. // Mountain
  171. const mountainMass = 860;
  172. const mountainHalfExtents = new THREE.Vector3( 4, 5, 4 );
  173. pos.set( 5, mountainHalfExtents.y * 0.5, - 7 );
  174. quat.set( 0, 0, 0, 1 );
  175. const mountainPoints = [];
  176. mountainPoints.push( new THREE.Vector3( mountainHalfExtents.x, - mountainHalfExtents.y, mountainHalfExtents.z ) );
  177. mountainPoints.push( new THREE.Vector3( - mountainHalfExtents.x, - mountainHalfExtents.y, mountainHalfExtents.z ) );
  178. mountainPoints.push( new THREE.Vector3( mountainHalfExtents.x, - mountainHalfExtents.y, - mountainHalfExtents.z ) );
  179. mountainPoints.push( new THREE.Vector3( - mountainHalfExtents.x, - mountainHalfExtents.y, - mountainHalfExtents.z ) );
  180. mountainPoints.push( new THREE.Vector3( 0, mountainHalfExtents.y, 0 ) );
  181. const mountain = new THREE.Mesh( new ConvexGeometry( mountainPoints ), createMaterial( 0xB03814 ) );
  182. mountain.position.copy( pos );
  183. mountain.quaternion.copy( quat );
  184. convexBreaker.prepareBreakableObject( mountain, mountainMass, new THREE.Vector3(), new THREE.Vector3(), true );
  185. createDebrisFromBreakableObject( mountain );
  186. }
  187. function createParalellepipedWithPhysics( sx, sy, sz, mass, pos, quat, material ) {
  188. const object = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), material );
  189. const shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  190. shape.setMargin( margin );
  191. createRigidBody( object, shape, mass, pos, quat );
  192. return object;
  193. }
  194. function createDebrisFromBreakableObject( object ) {
  195. object.castShadow = true;
  196. object.receiveShadow = true;
  197. const shape = createConvexHullPhysicsShape( object.geometry.attributes.position.array );
  198. shape.setMargin( margin );
  199. const body = createRigidBody( object, shape, object.userData.mass, null, null, object.userData.velocity, object.userData.angularVelocity );
  200. // Set pointer back to the three object only in the debris objects
  201. const btVecUserData = new Ammo.btVector3( 0, 0, 0 );
  202. btVecUserData.threeObject = object;
  203. body.setUserPointer( btVecUserData );
  204. }
  205. function removeDebris( object ) {
  206. scene.remove( object );
  207. physicsWorld.removeRigidBody( object.userData.physicsBody );
  208. }
  209. function createConvexHullPhysicsShape( coords ) {
  210. const shape = new Ammo.btConvexHullShape();
  211. for ( let i = 0, il = coords.length; i < il; i += 3 ) {
  212. tempBtVec3_1.setValue( coords[ i ], coords[ i + 1 ], coords[ i + 2 ] );
  213. const lastOne = ( i >= ( il - 3 ) );
  214. shape.addPoint( tempBtVec3_1, lastOne );
  215. }
  216. return shape;
  217. }
  218. function createRigidBody( object, physicsShape, mass, pos, quat, vel, angVel ) {
  219. if ( pos ) {
  220. object.position.copy( pos );
  221. } else {
  222. pos = object.position;
  223. }
  224. if ( quat ) {
  225. object.quaternion.copy( quat );
  226. } else {
  227. quat = object.quaternion;
  228. }
  229. const transform = new Ammo.btTransform();
  230. transform.setIdentity();
  231. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  232. transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
  233. const motionState = new Ammo.btDefaultMotionState( transform );
  234. const localInertia = new Ammo.btVector3( 0, 0, 0 );
  235. physicsShape.calculateLocalInertia( mass, localInertia );
  236. const rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
  237. const body = new Ammo.btRigidBody( rbInfo );
  238. body.setFriction( 0.5 );
  239. if ( vel ) {
  240. body.setLinearVelocity( new Ammo.btVector3( vel.x, vel.y, vel.z ) );
  241. }
  242. if ( angVel ) {
  243. body.setAngularVelocity( new Ammo.btVector3( angVel.x, angVel.y, angVel.z ) );
  244. }
  245. object.userData.physicsBody = body;
  246. object.userData.collided = false;
  247. scene.add( object );
  248. if ( mass > 0 ) {
  249. rigidBodies.push( object );
  250. // Disable deactivation
  251. body.setActivationState( 4 );
  252. }
  253. physicsWorld.addRigidBody( body );
  254. return body;
  255. }
  256. function createRandomColor() {
  257. return Math.floor( Math.random() * ( 1 << 24 ) );
  258. }
  259. function createMaterial( color ) {
  260. color = color || createRandomColor();
  261. return new THREE.MeshPhongMaterial( { color: color } );
  262. }
  263. function initInput() {
  264. window.addEventListener( 'pointerdown', function ( event ) {
  265. mouseCoords.set(
  266. ( event.clientX / window.innerWidth ) * 2 - 1,
  267. - ( event.clientY / window.innerHeight ) * 2 + 1
  268. );
  269. raycaster.setFromCamera( mouseCoords, camera );
  270. // Creates a ball and throws it
  271. const ballMass = 35;
  272. const ballRadius = 0.4;
  273. const ball = new THREE.Mesh( new THREE.SphereGeometry( ballRadius, 14, 10 ), ballMaterial );
  274. ball.castShadow = true;
  275. ball.receiveShadow = true;
  276. const ballShape = new Ammo.btSphereShape( ballRadius );
  277. ballShape.setMargin( margin );
  278. pos.copy( raycaster.ray.direction );
  279. pos.add( raycaster.ray.origin );
  280. quat.set( 0, 0, 0, 1 );
  281. const ballBody = createRigidBody( ball, ballShape, ballMass, pos, quat );
  282. pos.copy( raycaster.ray.direction );
  283. pos.multiplyScalar( 24 );
  284. ballBody.setLinearVelocity( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  285. } );
  286. }
  287. function onWindowResize() {
  288. camera.aspect = window.innerWidth / window.innerHeight;
  289. camera.updateProjectionMatrix();
  290. renderer.setSize( window.innerWidth, window.innerHeight );
  291. }
  292. function animate() {
  293. requestAnimationFrame( animate );
  294. render();
  295. stats.update();
  296. }
  297. function render() {
  298. const deltaTime = clock.getDelta();
  299. updatePhysics( deltaTime );
  300. renderer.render( scene, camera );
  301. }
  302. function updatePhysics( deltaTime ) {
  303. // Step world
  304. physicsWorld.stepSimulation( deltaTime, 10 );
  305. // Update rigid bodies
  306. for ( let i = 0, il = rigidBodies.length; i < il; i ++ ) {
  307. const objThree = rigidBodies[ i ];
  308. const objPhys = objThree.userData.physicsBody;
  309. const ms = objPhys.getMotionState();
  310. if ( ms ) {
  311. ms.getWorldTransform( transformAux1 );
  312. const p = transformAux1.getOrigin();
  313. const q = transformAux1.getRotation();
  314. objThree.position.set( p.x(), p.y(), p.z() );
  315. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  316. objThree.userData.collided = false;
  317. }
  318. }
  319. for ( let i = 0, il = dispatcher.getNumManifolds(); i < il; i ++ ) {
  320. const contactManifold = dispatcher.getManifoldByIndexInternal( i );
  321. const rb0 = Ammo.castObject( contactManifold.getBody0(), Ammo.btRigidBody );
  322. const rb1 = Ammo.castObject( contactManifold.getBody1(), Ammo.btRigidBody );
  323. const threeObject0 = Ammo.castObject( rb0.getUserPointer(), Ammo.btVector3 ).threeObject;
  324. const threeObject1 = Ammo.castObject( rb1.getUserPointer(), Ammo.btVector3 ).threeObject;
  325. if ( ! threeObject0 && ! threeObject1 ) {
  326. continue;
  327. }
  328. const userData0 = threeObject0 ? threeObject0.userData : null;
  329. const userData1 = threeObject1 ? threeObject1.userData : null;
  330. const breakable0 = userData0 ? userData0.breakable : false;
  331. const breakable1 = userData1 ? userData1.breakable : false;
  332. const collided0 = userData0 ? userData0.collided : false;
  333. const collided1 = userData1 ? userData1.collided : false;
  334. if ( ( ! breakable0 && ! breakable1 ) || ( collided0 && collided1 ) ) {
  335. continue;
  336. }
  337. let contact = false;
  338. let maxImpulse = 0;
  339. for ( let j = 0, jl = contactManifold.getNumContacts(); j < jl; j ++ ) {
  340. const contactPoint = contactManifold.getContactPoint( j );
  341. if ( contactPoint.getDistance() < 0 ) {
  342. contact = true;
  343. const impulse = contactPoint.getAppliedImpulse();
  344. if ( impulse > maxImpulse ) {
  345. maxImpulse = impulse;
  346. const pos = contactPoint.get_m_positionWorldOnB();
  347. const normal = contactPoint.get_m_normalWorldOnB();
  348. impactPoint.set( pos.x(), pos.y(), pos.z() );
  349. impactNormal.set( normal.x(), normal.y(), normal.z() );
  350. }
  351. break;
  352. }
  353. }
  354. // If no point has contact, abort
  355. if ( ! contact ) continue;
  356. // Subdivision
  357. const fractureImpulse = 250;
  358. if ( breakable0 && ! collided0 && maxImpulse > fractureImpulse ) {
  359. const debris = convexBreaker.subdivideByImpact( threeObject0, impactPoint, impactNormal, 1, 2, 1.5 );
  360. const numObjects = debris.length;
  361. for ( let j = 0; j < numObjects; j ++ ) {
  362. const vel = rb0.getLinearVelocity();
  363. const angVel = rb0.getAngularVelocity();
  364. const fragment = debris[ j ];
  365. fragment.userData.velocity.set( vel.x(), vel.y(), vel.z() );
  366. fragment.userData.angularVelocity.set( angVel.x(), angVel.y(), angVel.z() );
  367. createDebrisFromBreakableObject( fragment );
  368. }
  369. objectsToRemove[ numObjectsToRemove ++ ] = threeObject0;
  370. userData0.collided = true;
  371. }
  372. if ( breakable1 && ! collided1 && maxImpulse > fractureImpulse ) {
  373. const debris = convexBreaker.subdivideByImpact( threeObject1, impactPoint, impactNormal, 1, 2, 1.5 );
  374. const numObjects = debris.length;
  375. for ( let j = 0; j < numObjects; j ++ ) {
  376. const vel = rb1.getLinearVelocity();
  377. const angVel = rb1.getAngularVelocity();
  378. const fragment = debris[ j ];
  379. fragment.userData.velocity.set( vel.x(), vel.y(), vel.z() );
  380. fragment.userData.angularVelocity.set( angVel.x(), angVel.y(), angVel.z() );
  381. createDebrisFromBreakableObject( fragment );
  382. }
  383. objectsToRemove[ numObjectsToRemove ++ ] = threeObject1;
  384. userData1.collided = true;
  385. }
  386. }
  387. for ( let i = 0; i < numObjectsToRemove; i ++ ) {
  388. removeDebris( objectsToRemove[ i ] );
  389. }
  390. numObjectsToRemove = 0;
  391. }
  392. </script>
  393. </body>
  394. </html>