webgl_physics_terrain.html 12 KB

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