physics_ammo_break.html 16 KB

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