1
0

physics_ammo_terrain.html 12 KB

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