1
0

physics_ammo_terrain.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Ammo.js terrain heightfield demo</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. color: #333;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="container"></div>
  16. <div id="info">Ammo.js physics terrain heightfield demo</div>
  17. <script src="js/libs/ammo.wasm.js"></script>
  18. <script type="module">
  19. import * as THREE from '../build/three.module.js';
  20. import Stats from './jsm/libs/stats.module.js';
  21. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  22. // Heightfield parameters
  23. const terrainWidthExtents = 100;
  24. const terrainDepthExtents = 100;
  25. const terrainWidth = 128;
  26. const terrainDepth = 128;
  27. const terrainHalfWidth = terrainWidth / 2;
  28. const terrainHalfDepth = terrainDepth / 2;
  29. const terrainMaxHeight = 8;
  30. const terrainMinHeight = - 2;
  31. // Graphics variables
  32. let container, stats;
  33. let camera, scene, renderer;
  34. let terrainMesh;
  35. const clock = new THREE.Clock();
  36. // Physics variables
  37. let collisionConfiguration;
  38. let dispatcher;
  39. let broadphase;
  40. let solver;
  41. let physicsWorld;
  42. const dynamicObjects = [];
  43. let transformAux1;
  44. let heightData = null;
  45. let ammoHeightData = null;
  46. let time = 0;
  47. const objectTimePeriod = 3;
  48. let timeNextSpawn = time + objectTimePeriod;
  49. const maxNumObjects = 30;
  50. Ammo().then( function ( AmmoLib ) {
  51. Ammo = AmmoLib;
  52. init();
  53. animate();
  54. } );
  55. function init() {
  56. heightData = generateHeight( terrainWidth, terrainDepth, terrainMinHeight, terrainMaxHeight );
  57. initGraphics();
  58. initPhysics();
  59. }
  60. function initGraphics() {
  61. container = document.getElementById( 'container' );
  62. renderer = new THREE.WebGLRenderer();
  63. renderer.setPixelRatio( window.devicePixelRatio );
  64. renderer.setSize( window.innerWidth, window.innerHeight );
  65. renderer.shadowMap.enabled = true;
  66. container.appendChild( renderer.domElement );
  67. stats = new Stats();
  68. stats.domElement.style.position = 'absolute';
  69. stats.domElement.style.top = '0px';
  70. container.appendChild( stats.domElement );
  71. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  72. scene = new THREE.Scene();
  73. scene.background = new THREE.Color( 0xbfd1e5 );
  74. camera.position.y = heightData[ terrainHalfWidth + terrainHalfDepth * terrainWidth ] * ( terrainMaxHeight - terrainMinHeight ) + 5;
  75. camera.position.z = terrainDepthExtents / 2;
  76. camera.lookAt( 0, 0, 0 );
  77. const controls = new OrbitControls( camera, renderer.domElement );
  78. controls.enableZoom = false;
  79. const geometry = new THREE.PlaneGeometry( terrainWidthExtents, terrainDepthExtents, terrainWidth - 1, terrainDepth - 1 );
  80. geometry.rotateX( - Math.PI / 2 );
  81. const vertices = geometry.attributes.position.array;
  82. for ( let i = 0, j = 0, l = vertices.length; i < l; i ++, j += 3 ) {
  83. // j + 1 because it is the y component that we modify
  84. vertices[ j + 1 ] = heightData[ i ];
  85. }
  86. geometry.computeVertexNormals();
  87. const groundMaterial = new THREE.MeshPhongMaterial( { color: 0xC7C7C7 } );
  88. terrainMesh = new THREE.Mesh( geometry, groundMaterial );
  89. terrainMesh.receiveShadow = true;
  90. terrainMesh.castShadow = true;
  91. scene.add( terrainMesh );
  92. const textureLoader = new THREE.TextureLoader();
  93. textureLoader.load( "textures/grid.png", function ( texture ) {
  94. texture.wrapS = THREE.RepeatWrapping;
  95. texture.wrapT = THREE.RepeatWrapping;
  96. texture.repeat.set( terrainWidth - 1, terrainDepth - 1 );
  97. groundMaterial.map = texture;
  98. groundMaterial.needsUpdate = true;
  99. } );
  100. const light = new THREE.DirectionalLight( 0xffffff, 1 );
  101. light.position.set( 100, 100, 50 );
  102. light.castShadow = true;
  103. const dLight = 200;
  104. const sLight = dLight * 0.25;
  105. light.shadow.camera.left = - sLight;
  106. light.shadow.camera.right = sLight;
  107. light.shadow.camera.top = sLight;
  108. light.shadow.camera.bottom = - sLight;
  109. light.shadow.camera.near = dLight / 30;
  110. light.shadow.camera.far = dLight;
  111. light.shadow.mapSize.x = 1024 * 2;
  112. light.shadow.mapSize.y = 1024 * 2;
  113. scene.add( light );
  114. window.addEventListener( 'resize', onWindowResize );
  115. }
  116. function onWindowResize() {
  117. camera.aspect = window.innerWidth / window.innerHeight;
  118. camera.updateProjectionMatrix();
  119. renderer.setSize( window.innerWidth, window.innerHeight );
  120. }
  121. function initPhysics() {
  122. // Physics configuration
  123. collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
  124. dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  125. broadphase = new Ammo.btDbvtBroadphase();
  126. solver = new Ammo.btSequentialImpulseConstraintSolver();
  127. physicsWorld = new Ammo.btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration );
  128. physicsWorld.setGravity( new Ammo.btVector3( 0, - 6, 0 ) );
  129. // Create the terrain body
  130. const groundShape = createTerrainShape();
  131. const groundTransform = new Ammo.btTransform();
  132. groundTransform.setIdentity();
  133. // Shifts the terrain, since bullet re-centers it on its bounding box.
  134. groundTransform.setOrigin( new Ammo.btVector3( 0, ( terrainMaxHeight + terrainMinHeight ) / 2, 0 ) );
  135. const groundMass = 0;
  136. const groundLocalInertia = new Ammo.btVector3( 0, 0, 0 );
  137. const groundMotionState = new Ammo.btDefaultMotionState( groundTransform );
  138. const groundBody = new Ammo.btRigidBody( new Ammo.btRigidBodyConstructionInfo( groundMass, groundMotionState, groundShape, groundLocalInertia ) );
  139. physicsWorld.addRigidBody( groundBody );
  140. transformAux1 = new Ammo.btTransform();
  141. }
  142. function generateHeight( width, depth, minHeight, maxHeight ) {
  143. // Generates the height data (a sinus wave)
  144. const size = width * depth;
  145. const data = new Float32Array( size );
  146. const hRange = maxHeight - minHeight;
  147. const w2 = width / 2;
  148. const d2 = depth / 2;
  149. const phaseMult = 12;
  150. let p = 0;
  151. for ( let j = 0; j < depth; j ++ ) {
  152. for ( let i = 0; i < width; i ++ ) {
  153. const radius = Math.sqrt(
  154. Math.pow( ( i - w2 ) / w2, 2.0 ) +
  155. Math.pow( ( j - d2 ) / d2, 2.0 ) );
  156. const height = ( Math.sin( radius * phaseMult ) + 1 ) * 0.5 * hRange + minHeight;
  157. data[ p ] = height;
  158. p ++;
  159. }
  160. }
  161. return data;
  162. }
  163. function createTerrainShape() {
  164. // This parameter is not really used, since we are using PHY_FLOAT height data type and hence it is ignored
  165. const heightScale = 1;
  166. // Up axis = 0 for X, 1 for Y, 2 for Z. Normally 1 = Y is used.
  167. const upAxis = 1;
  168. // hdt, height data type. "PHY_FLOAT" is used. Possible values are "PHY_FLOAT", "PHY_UCHAR", "PHY_SHORT"
  169. const hdt = "PHY_FLOAT";
  170. // Set this to your needs (inverts the triangles)
  171. const flipQuadEdges = false;
  172. // Creates height data buffer in Ammo heap
  173. ammoHeightData = Ammo._malloc( 4 * terrainWidth * terrainDepth );
  174. // Copy the javascript height data array to the Ammo one.
  175. let p = 0;
  176. let p2 = 0;
  177. for ( let j = 0; j < terrainDepth; j ++ ) {
  178. for ( let i = 0; i < terrainWidth; i ++ ) {
  179. // write 32-bit float data to memory
  180. Ammo.HEAPF32[ ammoHeightData + p2 >> 2 ] = heightData[ p ];
  181. p ++;
  182. // 4 bytes/float
  183. p2 += 4;
  184. }
  185. }
  186. // Creates the heightfield physics shape
  187. const heightFieldShape = new Ammo.btHeightfieldTerrainShape(
  188. terrainWidth,
  189. terrainDepth,
  190. ammoHeightData,
  191. heightScale,
  192. terrainMinHeight,
  193. terrainMaxHeight,
  194. upAxis,
  195. hdt,
  196. flipQuadEdges
  197. );
  198. // Set horizontal scale
  199. const scaleX = terrainWidthExtents / ( terrainWidth - 1 );
  200. const scaleZ = terrainDepthExtents / ( terrainDepth - 1 );
  201. heightFieldShape.setLocalScaling( new Ammo.btVector3( scaleX, 1, scaleZ ) );
  202. heightFieldShape.setMargin( 0.05 );
  203. return heightFieldShape;
  204. }
  205. function generateObject() {
  206. const numTypes = 4;
  207. const objectType = Math.ceil( Math.random() * numTypes );
  208. let threeObject = null;
  209. let shape = null;
  210. const objectSize = 3;
  211. const margin = 0.05;
  212. let radius, height;
  213. switch ( objectType ) {
  214. case 1:
  215. // Sphere
  216. radius = 1 + Math.random() * objectSize;
  217. threeObject = new THREE.Mesh( new THREE.SphereGeometry( radius, 20, 20 ), createObjectMaterial() );
  218. shape = new Ammo.btSphereShape( radius );
  219. shape.setMargin( margin );
  220. break;
  221. case 2:
  222. // Box
  223. const sx = 1 + Math.random() * objectSize;
  224. const sy = 1 + Math.random() * objectSize;
  225. const sz = 1 + Math.random() * objectSize;
  226. threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), createObjectMaterial() );
  227. shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  228. shape.setMargin( margin );
  229. break;
  230. case 3:
  231. // Cylinder
  232. radius = 1 + Math.random() * objectSize;
  233. height = 1 + Math.random() * objectSize;
  234. threeObject = new THREE.Mesh( new THREE.CylinderGeometry( radius, radius, height, 20, 1 ), createObjectMaterial() );
  235. shape = new Ammo.btCylinderShape( new Ammo.btVector3( radius, height * 0.5, radius ) );
  236. shape.setMargin( margin );
  237. break;
  238. default:
  239. // Cone
  240. radius = 1 + Math.random() * objectSize;
  241. height = 2 + Math.random() * objectSize;
  242. threeObject = new THREE.Mesh( new THREE.ConeGeometry( radius, height, 20, 2 ), createObjectMaterial() );
  243. shape = new Ammo.btConeShape( radius, height );
  244. break;
  245. }
  246. threeObject.position.set( ( Math.random() - 0.5 ) * terrainWidth * 0.6, terrainMaxHeight + objectSize + 2, ( Math.random() - 0.5 ) * terrainDepth * 0.6 );
  247. const mass = objectSize * 5;
  248. const localInertia = new Ammo.btVector3( 0, 0, 0 );
  249. shape.calculateLocalInertia( mass, localInertia );
  250. const transform = new Ammo.btTransform();
  251. transform.setIdentity();
  252. const pos = threeObject.position;
  253. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  254. const motionState = new Ammo.btDefaultMotionState( transform );
  255. const rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  256. const body = new Ammo.btRigidBody( rbInfo );
  257. threeObject.userData.physicsBody = body;
  258. threeObject.receiveShadow = true;
  259. threeObject.castShadow = true;
  260. scene.add( threeObject );
  261. dynamicObjects.push( threeObject );
  262. physicsWorld.addRigidBody( body );
  263. }
  264. function createObjectMaterial() {
  265. const c = Math.floor( Math.random() * ( 1 << 24 ) );
  266. return new THREE.MeshPhongMaterial( { color: c } );
  267. }
  268. function animate() {
  269. requestAnimationFrame( animate );
  270. render();
  271. stats.update();
  272. }
  273. function render() {
  274. const deltaTime = clock.getDelta();
  275. if ( dynamicObjects.length < maxNumObjects && time > timeNextSpawn ) {
  276. generateObject();
  277. timeNextSpawn = time + objectTimePeriod;
  278. }
  279. updatePhysics( deltaTime );
  280. renderer.render( scene, camera );
  281. time += deltaTime;
  282. }
  283. function updatePhysics( deltaTime ) {
  284. physicsWorld.stepSimulation( deltaTime, 10 );
  285. // Update objects
  286. for ( let i = 0, il = dynamicObjects.length; i < il; i ++ ) {
  287. const objThree = dynamicObjects[ i ];
  288. const objPhys = objThree.userData.physicsBody;
  289. const ms = objPhys.getMotionState();
  290. if ( ms ) {
  291. ms.getWorldTransform( transformAux1 );
  292. const p = transformAux1.getOrigin();
  293. const q = transformAux1.getRotation();
  294. objThree.position.set( p.x(), p.y(), p.z() );
  295. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  296. }
  297. }
  298. }
  299. </script>
  300. </body>
  301. </html>