Browse Source

Added Rapier example (#25892)

* Added Rapier example.

* Updated screenshot.

* Fixed DeepScan issue.

* RapeirPhysics: Added world.timestep.
mrdoob 2 năm trước cách đây
mục cha
commit
1a4ed58475

+ 2 - 1
examples/files.json

@@ -391,7 +391,8 @@
 		"physics_ammo_rope",
 		"physics_ammo_terrain",
 		"physics_ammo_volume",
-		"physics_oimo_instancing"
+		"physics_oimo_instancing",
+		"physics_rapier_instancing"
 	],
 	"misc": [
 		"misc_animation_groups",

+ 237 - 0
examples/jsm/physics/RapierPhysics.js

@@ -0,0 +1,237 @@
+async function RapierPhysics( path ) {
+
+	const RAPIER = await import( path );
+	
+	await RAPIER.init();
+
+	const frameRate = 60;
+
+	// Docs: https://rapier.rs/docs/api/javascript/JavaScript3D/	
+
+	const gravity = { x: 0.0, y: - 9.81, z: 0.0 };
+    const world = new RAPIER.World( gravity );
+
+	function getCollider( geometry ) {
+
+		const parameters = geometry.parameters;
+
+		// TODO change type to is*
+
+		if ( geometry.type === 'BoxGeometry' ) {
+
+			const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
+			const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
+			const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
+
+			return RAPIER.ColliderDesc.cuboid( sx, sy, sz );
+
+		} else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
+
+			const radius = parameters.radius !== undefined ? parameters.radius : 1;
+
+			return RAPIER.ColliderDesc.ball( radius );
+
+		}
+
+		return null;
+
+	}
+
+	const meshes = [];
+	const meshMap = new WeakMap();
+
+	function addMesh( mesh, mass = 0, restitution = 0 ) {
+
+		const shape = getCollider( mesh.geometry );
+
+		if ( shape !== null ) {
+
+			shape.setMass( mass );
+			shape.setRestitution( restitution );
+	
+			if ( mesh.isInstancedMesh ) {
+
+				handleInstancedMesh( mesh, mass, shape );
+
+			} else if ( mesh.isMesh ) {
+
+				handleMesh( mesh, mass, shape );
+
+			}
+
+		}
+
+	}
+
+	function handleMesh( mesh, mass, shape ) {
+
+		const position = mesh.position;
+		const quaternion = mesh.quaternion;
+
+		const desc = mass > 0 ? RAPIER.RigidBodyDesc.dynamic() : RAPIER.RigidBodyDesc.fixed();
+		desc.setTranslation( position.x, position.y, position.z );
+		desc.setRotation( quaternion );
+
+		const body = world.createRigidBody( desc );
+		world.createCollider( shape, body );
+
+		if ( mass > 0 ) {
+
+			meshes.push( mesh );
+			meshMap.set( mesh, body );
+
+		}
+
+	}
+
+	function handleInstancedMesh( mesh, mass, shape ) {
+
+		const array = mesh.instanceMatrix.array;
+
+		const bodies = [];
+
+		for ( let i = 0; i < mesh.count; i ++ ) {
+
+			const index = i * 16;
+
+			const desc = mass > 0 ? RAPIER.RigidBodyDesc.dynamic() : RAPIER.RigidBodyDesc.fixed();
+			desc.setTranslation( array[ index + 12 ], array[ index + 13 ], array[ index + 14 ] );
+
+			const body = world.createRigidBody( desc );
+			world.createCollider( shape, body );
+
+			bodies.push( body );
+
+		}
+
+		if ( mass > 0 ) {
+
+			meshes.push( mesh );
+			meshMap.set( mesh, bodies );
+
+		}
+
+	}
+
+	const vector = { x: 0, y: 0, z: 0 };
+
+	function setMeshPosition( mesh, position, index = 0 ) {
+
+		if ( mesh.isInstancedMesh ) {
+
+			const bodies = meshMap.get( mesh );
+			const body = bodies[ index ];
+
+			body.setAngvel( vector );
+			body.setLinvel( vector );
+			body.setTranslation( position );
+
+		} else if ( mesh.isMesh ) {
+
+			const body = meshMap.get( mesh );
+
+			body.setAngvel( vector );
+			body.setLinvel( vector );
+			body.setTranslation( position );
+
+		}
+
+	}
+
+	//
+
+	let lastTime = 0;
+
+	function step() {
+
+		const time = performance.now();
+
+		if ( lastTime > 0 ) {
+
+			const delta = ( time - lastTime ) / 1000;
+
+			world.timestep = delta;
+			world.step();
+
+			for ( let i = 0, l = meshes.length; i < l; i ++ ) {
+
+				const mesh = meshes[ i ];
+
+				if ( mesh.isInstancedMesh ) {
+
+					const array = mesh.instanceMatrix.array;
+					const bodies = meshMap.get( mesh );
+
+					for ( let j = 0; j < bodies.length; j ++ ) {
+
+						const body = bodies[ j ];
+
+						const position = body.translation();
+						const quaternion = body.rotation();
+
+						compose( position, quaternion, array, j * 16 );
+
+					}
+
+					mesh.instanceMatrix.needsUpdate = true;
+					mesh.computeBoundingSphere();
+
+				} else if ( mesh.isMesh ) {
+
+					const body = meshMap.get( mesh );
+
+					mesh.position.copy( body.translation() );
+					mesh.quaternion.copy( body.rotation() );
+
+				}
+
+			}
+
+		}
+
+		lastTime = time;
+
+	}
+
+	// animate
+
+	setInterval( step, 1000 / frameRate );
+
+	return {
+		addMesh: addMesh,
+		setMeshPosition: setMeshPosition
+	};
+
+}
+
+function compose( position, quaternion, array, index ) {
+
+	const x = quaternion.x, y = quaternion.y, z = quaternion.z, w = quaternion.w;
+	const x2 = x + x, y2 = y + y, z2 = z + z;
+	const xx = x * x2, xy = x * y2, xz = x * z2;
+	const yy = y * y2, yz = y * z2, zz = z * z2;
+	const wx = w * x2, wy = w * y2, wz = w * z2;
+
+	array[ index + 0 ] = ( 1 - ( yy + zz ) );
+	array[ index + 1 ] = ( xy + wz );
+	array[ index + 2 ] = ( xz - wy );
+	array[ index + 3 ] = 0;
+
+	array[ index + 4 ] = ( xy - wz );
+	array[ index + 5 ] = ( 1 - ( xx + zz ) );
+	array[ index + 6 ] = ( yz + wx );
+	array[ index + 7 ] = 0;
+
+	array[ index + 8 ] = ( xz + wy );
+	array[ index + 9 ] = ( yz - wx );
+	array[ index + 10 ] = ( 1 - ( xx + yy ) );
+	array[ index + 11 ] = 0;
+
+	array[ index + 12 ] = position.x;
+	array[ index + 13 ] = position.y;
+	array[ index + 14 ] = position.z;
+	array[ index + 15 ] = 1;
+
+}
+
+export { RapierPhysics };

+ 171 - 0
examples/physics_rapier_instancing.html

@@ -0,0 +1,171 @@
+<!DOCTYPE html>
+<html lang="en">
+	<head>
+		<title>three.js physics - rapier3d instancing</title>
+		<meta charset="utf-8">
+		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
+		<link type="text/css" rel="stylesheet" href="main.css">
+	</head>
+	<body>
+
+		<div id="info">
+			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> physics - rapier3d instancing
+		</div>
+
+		<!-- Import maps polyfill -->
+		<!-- Remove this when import maps will be widely supported -->
+		<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
+
+		<script type="importmap">
+			{
+				"imports": {
+					"three": "../build/three.module.js",
+					"three/addons/": "./jsm/"
+				}
+			}
+		</script>
+
+		<script type="module">
+
+			import * as THREE from 'three';
+			import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+			import { RapierPhysics } from 'three/addons/physics/RapierPhysics.js';
+			import Stats from 'three/addons/libs/stats.module.js';
+
+			THREE.ColorManagement.enabled = false; // TODO: Consider enabling color management.
+
+			let camera, scene, renderer, stats;
+			let physics, position;
+
+			let boxes, spheres;
+
+			init();
+
+			async function init() {
+
+				physics = await RapierPhysics( 'https://cdn.skypack.dev/@dimforge/[email protected]' );
+				position = new THREE.Vector3();
+
+				//
+
+				camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 100 );
+				camera.position.set( - 1, 1.5, 2 );
+				camera.lookAt( 0, 0.5, 0 );
+
+				scene = new THREE.Scene();
+				scene.background = new THREE.Color( 0x666666 );
+
+				const hemiLight = new THREE.HemisphereLight();
+				hemiLight.intensity = 0.35;
+				scene.add( hemiLight );
+
+				const dirLight = new THREE.DirectionalLight();
+				dirLight.position.set( 5, 5, 5 );
+				dirLight.castShadow = true;
+				dirLight.shadow.camera.zoom = 2;
+				scene.add( dirLight );
+
+				const floor = new THREE.Mesh(
+					new THREE.BoxGeometry( 10, 5, 10 ),
+					new THREE.ShadowMaterial( { color: 0x111111 } )
+				);
+				floor.position.y = - 2.5;
+				floor.receiveShadow = true;
+				scene.add( floor );
+				physics.addMesh( floor );
+
+				//
+
+				const material = new THREE.MeshLambertMaterial();
+
+				const matrix = new THREE.Matrix4();
+				const color = new THREE.Color();
+
+				// Boxes
+
+				const geometryBox = new THREE.BoxGeometry( 0.1, 0.1, 0.1 );
+				boxes = new THREE.InstancedMesh( geometryBox, material, 100 );
+				boxes.instanceMatrix.setUsage( THREE.DynamicDrawUsage ); // will be updated every frame
+				boxes.castShadow = true;
+				boxes.receiveShadow = true;
+				scene.add( boxes );
+
+				for ( let i = 0; i < boxes.count; i ++ ) {
+
+					matrix.setPosition( Math.random() - 0.5, Math.random() * 2, Math.random() - 0.5 );
+					boxes.setMatrixAt( i, matrix );
+					boxes.setColorAt( i, color.setHex( 0xffffff * Math.random() ) );
+
+				}
+
+				physics.addMesh( boxes, 1 );
+
+				// Spheres
+
+				const geometrySphere = new THREE.IcosahedronGeometry( 0.075, 3 );
+				spheres = new THREE.InstancedMesh( geometrySphere, material, 100 );
+				spheres.instanceMatrix.setUsage( THREE.DynamicDrawUsage ); // will be updated every frame
+				spheres.castShadow = true;
+				spheres.receiveShadow = true;
+				scene.add( spheres );
+
+				for ( let i = 0; i < spheres.count; i ++ ) {
+
+					matrix.setPosition( Math.random() - 0.5, Math.random() * 2, Math.random() - 0.5 );
+					spheres.setMatrixAt( i, matrix );
+					spheres.setColorAt( i, color.setHex( 0xffffff * Math.random() ) );
+
+				}
+
+				physics.addMesh( spheres, 1 );
+
+				//
+
+				renderer = new THREE.WebGLRenderer( { antialias: true } );
+				renderer.setPixelRatio( window.devicePixelRatio );
+				renderer.setSize( window.innerWidth, window.innerHeight );
+				renderer.shadowMap.enabled = true;
+				document.body.appendChild( renderer.domElement );
+
+				stats = new Stats();
+				document.body.appendChild( stats.dom );
+
+				//
+
+				const controls = new OrbitControls( camera, renderer.domElement );
+				controls.target.y = 0.5;
+				controls.update();
+
+				animate();
+
+				setInterval( () => {
+
+					let index = Math.floor( Math.random() * boxes.count );
+
+					position.set( 0, Math.random() + 1, 0 );
+					physics.setMeshPosition( boxes, position, index );
+
+					//
+
+					index = Math.floor( Math.random() * spheres.count );
+
+					position.set( 0, Math.random() + 1, 0 );
+					physics.setMeshPosition( spheres, position, index );
+
+				}, 1000 / 60 );
+
+			}
+
+			function animate() {
+
+				requestAnimationFrame( animate );
+
+				renderer.render( scene, camera );
+
+				stats.update();
+
+			}
+
+		</script>
+	</body>
+</html>

BIN
examples/screenshots/physics_rapier_instancing.jpg


+ 1 - 0
examples/tags.json

@@ -99,6 +99,7 @@
 	"webgl2_multiple_rendertargets": [ "mrt" ],
 	"webgl2_multisampled_renderbuffers": [ "msaa" ],
 	"physics_ammo_cloth": [ "integration" ],
+	"physics_rapier_instancing": [ "external" ],
 	"misc_controls_arcball": [ "rotation" ],
 	"misc_controls_drag": [ "translate" ],
 	"misc_controls_map": [ "drag" ],