physics_ammo_terrain.html 12 KB

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