1
0

physics_rapier_terrain.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Rapier.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">Rapier.js physics terrain heightfield demo</div>
  17. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.module.js",
  21. "three/addons/": "./jsm/"
  22. }
  23. }
  24. </script>
  25. <script type="module">
  26. import * as THREE from 'three';
  27. import Stats from 'three/addons/libs/stats.module.js';
  28. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  29. import { RapierPhysics } from 'three/addons/physics/RapierPhysics.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 timer = new THREE.Timer();
  44. timer.connect( document );
  45. // Physics variables
  46. let physics;
  47. const dynamicObjects = [];
  48. let heightData = null;
  49. let time = 0;
  50. const objectTimePeriod = 3;
  51. let timeNextSpawn = time + objectTimePeriod;
  52. const maxNumObjects = 30;
  53. init();
  54. async function init() {
  55. heightData = generateHeight( terrainWidth, terrainDepth, terrainMinHeight, terrainMaxHeight );
  56. initGraphics();
  57. await initPhysics();
  58. // Start animation loop only after physics is initialized
  59. renderer.setAnimationLoop( animate );
  60. }
  61. function initGraphics() {
  62. container = document.getElementById( 'container' );
  63. renderer = new THREE.WebGLRenderer( { antialias: true } );
  64. renderer.setPixelRatio( window.devicePixelRatio );
  65. renderer.setSize( window.innerWidth, window.innerHeight );
  66. // Remove setAnimationLoop from here since we'll start it after physics init
  67. renderer.shadowMap.enabled = true;
  68. container.appendChild( renderer.domElement );
  69. stats = new Stats();
  70. stats.domElement.style.position = 'absolute';
  71. stats.domElement.style.top = '0px';
  72. container.appendChild( stats.domElement );
  73. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  74. scene = new THREE.Scene();
  75. scene.background = new THREE.Color( 0xbfd1e5 );
  76. camera.position.y = heightData[ terrainHalfWidth + terrainHalfDepth * terrainWidth ] * ( terrainMaxHeight - terrainMinHeight ) + 5;
  77. camera.position.z = terrainDepthExtents / 2;
  78. camera.lookAt( 0, 0, 0 );
  79. const controls = new OrbitControls( camera, renderer.domElement );
  80. controls.enableZoom = false;
  81. const geometry = new THREE.PlaneGeometry( terrainWidthExtents, terrainDepthExtents, terrainWidth - 1, terrainDepth - 1 );
  82. geometry.rotateX( - Math.PI / 2 );
  83. const vertices = geometry.attributes.position.array;
  84. for ( let i = 0, j = 0, l = vertices.length; i < l; i ++, j += 3 ) {
  85. vertices[ j + 1 ] = heightData[ i ];
  86. }
  87. geometry.computeVertexNormals();
  88. const groundMaterial = new THREE.MeshPhongMaterial( { color: 0xC7C7C7 } );
  89. terrainMesh = new THREE.Mesh( geometry, groundMaterial );
  90. terrainMesh.receiveShadow = true;
  91. terrainMesh.castShadow = true;
  92. scene.add( terrainMesh );
  93. const textureLoader = new THREE.TextureLoader();
  94. textureLoader.load( 'textures/grid.png', function ( texture ) {
  95. texture.wrapS = THREE.RepeatWrapping;
  96. texture.wrapT = THREE.RepeatWrapping;
  97. texture.repeat.set( terrainWidth - 1, terrainDepth - 1 );
  98. groundMaterial.map = texture;
  99. groundMaterial.needsUpdate = true;
  100. } );
  101. const ambientLight = new THREE.AmbientLight( 0xbbbbbb );
  102. scene.add( ambientLight );
  103. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  104. light.position.set( 100, 100, 50 );
  105. light.castShadow = true;
  106. const dLight = 200;
  107. const 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 );
  118. }
  119. function onWindowResize() {
  120. camera.aspect = window.innerWidth / window.innerHeight;
  121. camera.updateProjectionMatrix();
  122. renderer.setSize( window.innerWidth, window.innerHeight );
  123. }
  124. async function initPhysics() {
  125. physics = await RapierPhysics();
  126. // Create the terrain body using RapierPhysics module
  127. physics.addHeightfield( terrainMesh, terrainWidth - 1, terrainDepth - 1, heightData, { x: terrainWidthExtents, y: 1.0, z: terrainDepthExtents } );
  128. // Continue with adding other dynamic objects as needed
  129. }
  130. function generateHeight( width, depth, minHeight, maxHeight ) {
  131. const size = width * depth;
  132. const data = new Float32Array( size );
  133. const hRange = maxHeight - minHeight;
  134. const w2 = width / 2;
  135. const d2 = depth / 2;
  136. const phaseMult = 12;
  137. let p = 0;
  138. for ( let j = 0; j < depth; j ++ ) {
  139. for ( let i = 0; i < width; i ++ ) {
  140. const radius = Math.sqrt( Math.pow( ( i - w2 ) / w2, 2.0 ) + Math.pow( ( j - d2 ) / d2, 2.0 ) );
  141. const height = ( Math.sin( radius * phaseMult ) + 1 ) * 0.5 * hRange + minHeight;
  142. data[ p ] = height;
  143. p ++;
  144. }
  145. }
  146. return data;
  147. }
  148. function generateObject() {
  149. const numTypes = 3; // cones not working
  150. const objectType = Math.ceil( Math.random() * numTypes );
  151. let threeObject = null;
  152. const objectSize = 3;
  153. let radius, height;
  154. switch ( objectType ) {
  155. case 1: // Sphere
  156. radius = 1 + Math.random() * objectSize;
  157. threeObject = new THREE.Mesh( new THREE.SphereGeometry( radius, 20, 20 ), createObjectMaterial() );
  158. break;
  159. case 2: // Box
  160. const sx = 1 + Math.random() * objectSize;
  161. const sy = 1 + Math.random() * objectSize;
  162. const sz = 1 + Math.random() * objectSize;
  163. threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), createObjectMaterial() );
  164. break;
  165. case 3: // Cylinder
  166. radius = 1 + Math.random() * objectSize;
  167. height = 1 + Math.random() * objectSize;
  168. threeObject = new THREE.Mesh( new THREE.CylinderGeometry( radius, radius, height, 20, 1 ), createObjectMaterial() );
  169. break;
  170. default: // Cone
  171. radius = 1 + Math.random() * objectSize;
  172. height = 2 + Math.random() * objectSize;
  173. threeObject = new THREE.Mesh( new THREE.ConeGeometry( radius, height, 20, 2 ), createObjectMaterial() );
  174. break;
  175. }
  176. // Position objects higher and with more randomization to prevent clustering
  177. threeObject.position.set(
  178. ( Math.random() - 0.5 ) * terrainWidth * 0.6,
  179. terrainMaxHeight + objectSize + 15 + Math.random() * 5, // Even higher with randomization
  180. ( Math.random() - 0.5 ) * terrainDepth * 0.6
  181. );
  182. const mass = objectSize * 5;
  183. const restitution = 0.3; // Add some bounciness
  184. // Add to scene first
  185. scene.add( threeObject );
  186. // Add physics to the object
  187. physics.addMesh( threeObject, mass, restitution );
  188. // Store the object for later reference
  189. dynamicObjects.push( threeObject );
  190. // Force a small delay before adding the next object
  191. timeNextSpawn = time + 0.5;
  192. threeObject.receiveShadow = true;
  193. threeObject.castShadow = true;
  194. }
  195. function createObjectMaterial() {
  196. const c = Math.floor( Math.random() * ( 1 << 24 ) );
  197. return new THREE.MeshPhongMaterial( { color: c } );
  198. }
  199. function animate() {
  200. timer.update();
  201. render();
  202. stats.update();
  203. }
  204. function render() {
  205. const deltaTime = timer.getDelta();
  206. // Generate new objects with a delay between them
  207. if ( dynamicObjects.length < maxNumObjects && time > timeNextSpawn ) {
  208. // Generate object directly in this frame
  209. generateObject();
  210. // timeNextSpawn is now set in generateObject()
  211. }
  212. // Clean up objects that have fallen off the terrain
  213. for ( let i = dynamicObjects.length - 1; i >= 0; i -- ) {
  214. const obj = dynamicObjects[ i ];
  215. if ( obj.position.y < terrainMinHeight - 10 ) {
  216. // Remove from scene and physics world
  217. scene.remove( obj );
  218. dynamicObjects.splice( i, 1 );
  219. }
  220. }
  221. updatePhysics();
  222. renderer.render( scene, camera );
  223. time += deltaTime;
  224. }
  225. function updatePhysics() {
  226. // Check for objects that might need help with physics
  227. for ( let i = 0, il = dynamicObjects.length; i < il; i ++ ) {
  228. const objThree = dynamicObjects[ i ];
  229. // If object is not moving but should be (based on height), try to fix it
  230. if ( objThree.position.y > 1.0 ) {
  231. // Check if physics body exists
  232. if ( objThree.userData && objThree.userData.physics && objThree.userData.physics.body ) {
  233. const body = objThree.userData.physics.body;
  234. // Make sure body is awake
  235. if ( typeof body.wakeUp === 'function' ) {
  236. body.wakeUp();
  237. }
  238. // Check velocity and apply impulse if needed
  239. if ( typeof body.linvel === 'function' ) {
  240. const velocity = body.linvel();
  241. const speed = Math.sqrt( velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z );
  242. // If object is very slow, give it a stronger impulse
  243. if ( speed < 0.5 ) {
  244. body.applyImpulse( { x: 0, y: - 2.0, z: 0 }, true );
  245. }
  246. }
  247. } else {
  248. // If the object doesn't have a physics body but should, recreate it
  249. const mass = 5; // Default mass
  250. const restitution = 0.3; // Default restitution
  251. // Recreate physics for the object
  252. physics.addMesh( objThree, mass, restitution );
  253. }
  254. }
  255. }
  256. }
  257. </script>
  258. </body>
  259. </html>
粤ICP备19079148号