physics_ammo_break.html 16 KB

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