webgl_physics_terrain.html 12 KB

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