webgl_physics_terrain.html 12 KB

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