webgl_physics_terrain.html 12 KB

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