Okay, here is a basic HTML file structure using Three.js version 0.178.0, Ammo.js (with WASM), OrbitControls, and GLTFLoader. It sets up a simple scene with a floor and a falling sphere, and includes a placeholder for loading a GLTF model.
Important Notes:
- Version Specificity: CDN links are pinned to
0.178.0 for Three.js and 2.0.0 for ammo.js-wasm. Compatibility between physics and rendering libraries can sometimes be tricky, but these versions should generally work together.
- GLTF Model: You'll need to replace
'path/to/your/model.glb' with the actual path to your GLTF file. You can place the model file in the same directory as the HTML file or use a full URL. If the model fails to load, a simple sphere will remain.
- Ammo.js WASM: Ammo.js initialization is asynchronous. The code uses
Ammo().then(...) to ensure the physics engine is ready before proceeding.
- ES Modules: The script uses
type="module" to allow ES6 imports.
File: scene.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js 0.178.0 + Ammo.js WASM Scene</title>
<style>
body { margin: 0; overflow: hidden; font-family: Arial, sans-serif; }
#info {
position: absolute;
top: 10px;
left: 10px;
background-color: rgba(0,0,0,0.5);
color: white;
padding: 10px;
border-radius: 5px;
}
canvas { display: block; } /* Prevents scrollbars */
</style>
</head>
<body>
<div id="info">
Three.js 0.178.0 + Ammo.js WASM<br>
OrbitControls + GLTFLoader<br>
(Falling Sphere Demo)
</div>
<!-- Libraries -->
<!-- Three.js -->
<script type="importmap-shim">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.178.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.178.0/examples/jsm/"
}
}
</script>
<!-- Ammo.js WASM -->
<script async src="https://cdn.jsdelivr.net/npm/ammo.js-wasm@2.0.0/build/ammo.js"></script>
<!-- ImportMap Shim for older browsers -->
<script type="module" src="https://cdn.jsdelivr.net/npm/es-module-shims@1/dist/es-module-shims.min.js"></script>
<script type="module">
// --- Basic Setup ---
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// Check if Ammo is loaded
if (typeof Ammo === 'undefined') {
alert('Ammo.js WASM module not loaded. Check CDN link or network connection.');
throw new Error('Ammo.js not loaded.');
}
// --- Scene, Camera, Renderer ---
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x88ccee); // Light blue background
scene.fog = new THREE.Fog(0x88ccee, 0, 50);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 5, 10); // Adjusted initial position
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true; // Enable shadows
document.body.appendChild(renderer.domElement);
// --- Controls ---
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 2, 0); // Aim controls at the center
controls.update();
controls.enableDamping = true; // Smooth camera movement
// --- Lighting ---
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 10, 7);
directionalLight.castShadow = true;
// Configure shadow properties for better quality
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 50;
directionalLight.shadow.camera.left = -15;
directionalLight.shadow.camera.right = 15;
directionalLight.shadow.camera.top = 15;
directionalLight.shadow.camera.bottom = -15;
scene.add(directionalLight);
// --- Clock for Time ---
const clock = new THREE.Clock();
// --- Physics World Setup ---
let physicsWorld;
const rigidBodies = []; // Store { mesh, rigidBody } pairs
const gravityConstant = -9.8;
// Helper function to create physics shapes and rigid bodies
function createPhysicsObject(threeObject, mass, shapeDesc, pos, quat) {
// Ammo setup
const transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z));
transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w));
const motionState = new Ammo.btDefaultMotionState(transform);
const colShape = new Ammo.bt(shapeDesc); // Use shapeDesc directly
colShape.setLocalScaling(new Ammo.btVector3(1, 1, 1)); // Adjust if shape needs scaling
colShape.setMargin(0.05); // Margin for collision detection
let rbInfo;
if (mass !== 0) {
const btVector = new Ammo.btVector3(0, 0, 0); // Inertia vector
colShape.calculateLocalInertia(mass, btVector);
rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, colShape, btVector);
} else {
// Static object (mass = 0)
rbInfo = new Ammo.btRigidBodyConstructionInfo(0, motionState, colShape, new Ammo.btVector3(0, 0, 0));
}
const rigidBody = new Ammo.btRigidBody(rbInfo);
physicsWorld.addRigidBody(rigidBody);
// Clean up Ammo objects
// transform.delete(); // Not needed if motionState owns it
// motionState.delete(); // MotionState is owned by the RigidBody
// colShape.delete(); // RigidBody owns the shape
// rbInfo.delete(); // RigidBody owns the info
// Three.js setup
threeObject.position.copy(pos);
threeObject.quaternion.copy(quat);
threeObject.castShadow = true;
threeObject.receiveShadow = true;
scene.add(threeObject);
rigidBodies.push({ mesh: threeObject, rigidBody: rigidBody });
}
// --- Initialization ---
function init() {
// Ammo JS Initialization
const collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
const dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
const overlappingPairCache = new Ammo.btDbvtBroadphase();
const solver = new Ammo.btSequentialImpulseConstraintSolver();
physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);
physicsWorld.setGravity(new Ammo.btVector3(0, gravityConstant, 0));
physicsWorld.getSolverInfo().m_friction = 0.8; // Example: Adjust friction
// Ammo Object Cleanup Helpers (important to prevent memory leaks)
// It's often better to manage these via a class or structure if complex
// For this example, we rely on the RigidBody managing its MotionState and Shape
// --- Create Floor ---
const floorShape = new THREE.BoxGeometry(50, 1, 50);
const floorMaterial = new THREE.MeshStandardMaterial({ color: 0x408040 }); // Green floor
const floorMesh = new THREE.Mesh(floorShape, floorMaterial);
floorMesh.position.y = -0.5; // Center the floor geometry visually
floorMesh.receiveShadow = true; // Allow floor to receive shadows
floorMesh.castShadow = false;
scene.add(floorMesh);
// Physics Floor (Static)
const pos1 = {x: 0, y: -0.5, z: 0};
const quat1 = {x: 0, y: 0, z: 0, w: 1};
const floorWidth = 50;
const floorHeight = 1;
const floorDepth = 50;
const btFloorShape = new Ammo.btBoxShape(new Ammo.btVector3(floorWidth / 2, floorHeight / 2, floorDepth / 2));
createPhysicsObject(floorMesh, 0, btFloorShape, pos1, quat1); // Mass = 0 for static
// --- Create Falling Sphere ---
const sphereRadius = 0.5;
const sphereShape = new THREE.SphereGeometry(sphereRadius, 32, 16);
const sphereMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 }); // Red sphere
const sphereMesh = new THREE.Mesh(sphereShape, sphereMaterial);
sphereMesh.position.y = 5; // Start higher up
sphereMesh.castShadow = true;
sphereMesh.receiveShadow = true;
scene.add(sphereMesh);
// Physics Sphere (Dynamic)
const pos2 = {x: 0, y: 5, y: 5, z: 0}; // Starting position
const quat2 = {x: 0, y: 0, z: 0, w: 1}; // Orientation
const sphereMass = 1;
const btSphereShape = new Ammo.btSphereShape(sphereRadius);
createPhysicsObject(sphereMesh, sphereMass, btSphereShape, pos2, quat2);
// --- Load GLTF Model ---
const loader = new GLTFLoader();
const gltfPath = 'path/to/your/model.glb'; // <<<--- CHANGE THIS PATH
loader.load(gltfPath, (gltf) => {
// Position and scale the loaded model
gltf.scene.position.set(3, 1, 0); // Example position
gltf.scene.scale.set(0.5, 0.5, 0.5); // Example scale
gltf.scene.traverse((node) => {
if (node.isMesh) {
node.castShadow = true;
node.receiveShadow = true;
}
});
scene.add(gltf.scene);
// If you want the GLTF model to participate in physics,
// you'd need to:
// 1. Get its geometry (potentially complex for nested models)
// 2. Create appropriate Ammo collision shapes (btConvexHullShape, btBvhTriangleMeshShape)
// 3. Create a RigidBody for it
console.log('GLTF model loaded successfully.');
}, (xhr) => {
// Optional: Progress callback
// console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
}, (error) => {
console.error('Error loading GLTF model:', error);
// Display message if model fails to load
const errorMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const errorBox = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), errorMaterial);
errorBox.position.set(3, 1, 0);
scene.add(errorBox);
const errorText = document.createElement('div');
errorText.style.position = 'absolute';
errorText.style.top = '50px';
errorText.style.left = '10px';
errorText.style.color = 'red';
errorText.textContent = `Failed to load GLTF model at: ${gltfPath}. Showing placeholder.`;
document.body.appendChild(errorText);
});
// Handle window resize
window.addEventListener('resize', onWindowResize, false);
animate();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
const deltaTime = clock.getDelta();
// Step the physics world
if (physicsWorld) {
physicsWorld.stepSimulation(deltaTime, 10); // 10 = max substeps
// Update Three.js meshes based on physics simulation results
for (let i = 0; i < rigidBodies.length; i++) {
const { mesh, rigidBody } = rigidBodies[i];
const motionState = rigidBody.getMotionState();
if (motionState) {
const transform = new Ammo.btTransform();
motionState.getWorldTransform(transform);
const origin = transform.getOrigin();
mesh.position.set(origin.x(), origin.y(), origin.z());
const rotation = transform.getRotation();
mesh.quaternion.set(rotation.x(), rotation.y(), rotation.z(), rotation.w());
// Clean up temporary Ammo objects
// transform.delete(); // RigidBody likely manages this internally via motionState
}
}
}
// Update controls (needed for damping)
controls.update();
// Render the scene
renderer.render(scene, camera);
}
// Start the application after Ammo.js is loaded
window.addEventListener('load', () => {
if (typeof Ammo !== 'undefined') {
init();
} else {
console.error("Ammo.js WASM failed to load. Please check the console and network connection.");
}
});
</script>
</body>
</html>
How to Use:
- Save: Save the code above as an HTML file (e.g.,
scene.html).
- GLTF Model: Place your
.glb or .gltf model file in a location accessible by the browser. Update the gltfPath variable inside the script (const gltfPath = 'path/to/your/model.glb';) to point to your file. If you put the model in the same folder, you can just use its filename (e.g., const gltfPath = 'my_model.glb';).
- Open: Open the
scene.html file in your web browser.
Explanation:
- HTML Structure: Sets up the basic page, includes some simple CSS for layout, and placeholders for information.
- CSS: Styles the page, removing default margins and hiding overflow. The
#info div provides basic usage text.
- Import Maps: The
importmap-shim script and <script type="importmap-shim"> tag configure how ES module specifiers (three, three/addons/...) are resolved to the CDN URLs. This is crucial for using imports with CDN-hosted modules.
- Library Loading: Includes Three.js,
ammo.js-wasm, and the es-module-shims library using <script> tags. async is used for Ammo.js to allow the HTML to parse while it loads.
- Module Script: The main JavaScript logic is within
<script type="module">.
- Imports: Imports the necessary
THREE namespace, OrbitControls, and GLTFLoader.
- Ammo Check: Verifies that the
Ammo global object is available.
- Three.js Setup: Initializes the
Scene, PerspectiveCamera, and WebGLRenderer. Sets background color, enables shadows, and appends the renderer's canvas to the document.
- OrbitControls: Attaches OrbitControls to the camera and renderer canvas for interactive viewing.
enableDamping makes the movement smoother.
- Lighting: Adds ambient and directional light. The directional light is configured to cast shadows.
- Clock: Used to get the time delta for physics simulation steps.
- Physics World: Creates the core Ammo.js physics world (
btDiscreteDynamicsWorld) with necessary components (collision configuration, dispatcher, broadphase, solver) and sets gravity.
createPhysicsObject Function: A helper function to streamline the creation of both Three.js meshes and corresponding Ammo.js rigid bodies (including shapes, motion states, and rigid body construction). It links the physics object and the visual mesh.
- Floor Creation: Creates a large static plane using
BoxGeometry for Three.js and a btBoxShape for Ammo.js.
- Sphere Creation: Creates a dynamic red sphere using
SphereGeometry for Three.js and a for Ammo.js. It's given a mass and initial position.