Three.js FPS: Technical Development Plan
I'll provide a comprehensive architectural blueprint for pushing Three.js to its limits. This plan balances ambition with feasibility, emphasizing systems that can be built incrementally while maintaining playable performance.
1. Core Architecture Overview
Engine Structure
┌─────────────────────────────────────────────────────────────┐
│ GAME LOOP (60 FPS) │
├─────────────────────────────────────────────────────────────┤
│ Input → PlayerController → PhysicsWorld → SceneUpdate │
│ ↓ │
│ ┌────────────────────┼────────────────────┐ │
│ ↓ ↓ ↓ │
│ TerrainLOD ProceduralAssets ParticleFX │
│ ↑ ↑ ↑ │
│ └────────────────────┼────────────────────┘ │
│ ↓ │
│ Renderer (WebGL2) │
│ ┌────────────────────┼────────────────────┐ │
│ ↓ ↓ ↓ │
│ CustomShaders PostProcessing GPUCompute │
└─────────────────────────────────────────────────────────────┘
Technology Stack
| Component | Technology | Justification |
|---|
| Renderer | WebGL2 via Three.js r158+ | Compute shaders, 3D textures, instancing |
| Physics | Cannon-es + Custom raycast vehicle | Lightweight, integrates well with Three.js |
| Procedural Gen | Custom noise lib + GPU compute | Fast, controllable, no external deps |
| Audio | Web Audio API + Howler.js | Spatial audio essential for FPS |
| State Management | Zustand (lightweight) | Minimal overhead, React optional |
| Build Tool | Vite | Fast HMR, optimized builds |
2. Procedural Content Systems
2.1 Procedural Models & Textures
Approach Comparison
| Method | Pros | Cons | Verdict |
|---|
| CPU Noise + Geometry | Full control, easy debugging | Slow for large datasets, main thread blocking | Use for hero assets only |
| GPU Compute Shaders | Massive parallelism, fast | Complex debugging, WebGL2 required | Primary method |
| SDF Raymarching | Infinite detail, unique visuals | Expensive per-pixel, hard to integrate with raster | Use for specific effects |
| Texture Synthesis (GAN) | Realistic results | Heavy, requires ML runtime | Out of scope |
Implementation Strategy
Terrain Mesh Generation (GPU-Driven)
// Compute shader generates heightmap → vertex shader displaces plane
const terrainWorkflow = {
// 1. GPU Noise Generation (2048x2048 heightmap)
computePass: `
// Simplex noise layers for terrain
// Layer 1: Continental (low freq, high amp)
// Layer 2: Hills (med freq, med amp)
// Layer 3: Detail (high freq, low amp)
// Layer 4: Erosion simulation (hydraulic map)
`,
// 2. Vertex displacement in shader
vertexShader: `
uniform sampler2D heightmap;
varying vec2 vUv;
void main() {
vUv = uv;
float height = texture2D(heightmap, uv).r;
vec3 pos = position + normal * height * uHeightScale;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,
// 3. Normal calculation from heightmap derivatives
normalCalculation: 'analytical_in_shader' // Faster than geometry.computeVertexNormals()
};
Procedural Materials (Runtime Generated)
class ProceduralMaterialGenerator {
// Generates textures on GPU using fragment shaders
generateRockMaterial() {
return {
albedo: this.generateTexture('rock_albedo_frag'),
normal: this.generateTexture('rock_normal_frag'),
roughness: this.generateTexture('rock_roughness_frag'),
ao: this.generateTexture('rock_ao_frag')
};
}
// Texture bombing for surface detail without unique UVs
textureBombedMaterial() {
// Reduces tiling artifacts through stochastic sampling
}
}
Trade-off Resolution:
- Hero terrain: GPU compute heightmap + LOD chunks
- Rock formations: Instanced SDF-derived meshes (low poly, generated once)
- Surface detail: Texture bombing + triplanar mapping (no UV unwrapping needed)
2.2 Procedural Skies & Volumetric Clouds
Approach Comparison
| Technique | Visual Quality | Performance | Complexity |
|---|
| 2D Cloud Layers | Low | Fast | Simple |
| Billboard Particles | Medium | Medium | Medium |
| Raymarched Volumetrics | High | Heavy | Complex |
| Voxel Clouds | High | Medium-Heavy | Complex |
| Shell Texturing (Our Choice) | High | Medium | Moderate |
Selected: Hybrid Shell Texturing + Raymarched Detail
Core Concept: Use concentric transparent shells for bulk cloud volume, raymarched detail for edges.
// Vertex shader: Billboard cloud volume
uniform float uTime;
uniform vec3 uWindDirection;
void main() {
// Shell layers create volume illusion
float shellOffset = float(gl_InstanceID) * SHELL_THICKNESS;
vec3 worldPos = instanceMatrix * vec4(position, 1.0);
// Wind animation via vertex displacement
worldPos += uWindDirection * uTime * windSpeedAtAltitude(worldPos.y);
// LOD: Fewer shells at distance
gl_Position = projectionMatrix * viewMatrix * vec4(worldPos, 1.0);
}
// Fragment shader: Density modeling
float cloudDensity(vec3 worldPos) {
// Base shape from 3D worley noise
float base = worleyNoise(worldPos * 0.001);
// Detail from fbm
float detail = fbm(worldPos * 0.01);
// Height gradient (fluffy tops, flat bottoms)
float heightGradient = smoothstep(0.0, 0.3, worldPos.y) *
(1.0 - smoothstep(0.6, 1.0, worldPos.y));
// Coverage map from weather texture
float coverage = texture2D(weatherMap, worldPos.xz * 0.0001).r;
return max(0.0, base * detail * heightGradient - (1.0 - coverage));
}
void main() {
vec3 rayOrigin = cameraPosition;
vec3 rayDir = normalize(worldPos - cameraPosition);
// Short raymarch for edge detail (8 steps max)
float density = 0.0;
for(int i = 0; i < 8; i++) {
density += cloudDensity(rayOrigin + rayDir * float(i) * STEP_SIZE);
}
// Beer-Lambert lighting
vec3 lightColor = computeLightTransmittance(worldPos, sunDirection);
gl_FragColor = vec4(lightColor, density * shellAlpha);
}
Performance Optimizations:
- Temporal reprojection: Reuse previous frame's raymarch results
- Adaptive step size: Larger steps in dense regions
- LOD system: 3 shell layers near player, 1 layer at distance
- Culling: Cloud volumes outside frustum completely skipped
3. World & Environment
3.1 Island Terrain System (Far Cry Style)
Technical Architecture
┌──────────────────────────────────────────────────────────────┐
│ TERRAIN SYSTEM │
├──────────────────────────────────────────────────────────────┤
│ Chunk Manager │
│ ├── Active Zone (9 chunks, high detail) │
│ ├── Transition Zone (16 chunks, medium detail) │
│ └── Distant Zone (25 chunks, low detail / impostors) │
├──────────────────────────────────────────────────────────────┤
│ LOD Levels │
│ ├── LOD0: 256x256 verts, full shaders, collisions │
│ ├── LOD1: 128x128 verts, simplified shaders │
│ ├── LOD2: 64x64 verts, baked normal map │
│ └── LOD3: 16x16 verts, vertex colors only, no collision │
├──────────────────────────────────────────────────────────────┤
│ Generation Pipeline │
│ 1. Base Height (Simplex FBM) │
│ 2. Island Mask (Distance from center + noise) │
│ 3. Erosion Simulation (Hydraulic + Thermal) │
│ 4. Feature Placement (Rivers, cliffs, beaches) │
│ 5. Biome Assignment (Altitude + Slope + Moisture) │
└──────────────────────────────────────────────────────────────┘
Heightmap Generation (Compute Shader)
// Multi-stage GPU pipeline
const terrainGeneration = {
stage1_baseNoise: `
// Multi-octave simplex for continental shape
float height = fbm(pos * 0.001, 4, 2.0, 0.5) * 500.0;
`,
stage2_erosion: `
// Hydraulic erosion simulation
// Flow map calculation
// Sediment deposition
// 50 iterations for believable results
`,
stage3_features: `
// River carving using priority flood fill
// Cliff detection via slope analysis
// Beach generation via slope + height thresholds
`,
stage4_biomes: `
// Output: Albedo tint, roughness, vegetation density
// Biome = f(temperature, moisture, altitude)
`
};
Memory Budget:
- Heightmap: 2048x2048x4 bytes = 16MB
- Normal map: 2048x2048x12 bytes = 48MB (can be calculated in shader)
- Splat map (material blending): 2048x2048x16 bytes = 64MB
- Total per terrain: ~128MB GPU memory
3.2 Water & Shoreline System
Approach Comparison
| Method | Visuals | Performance | Implementation |
|---|
| Gerstner Waves | Good | Fast | Simple |
| FFT Ocean (Tessendorf) | Excellent | Heavy | Complex |
| Heightfield + Particles | Good | Medium | Moderate |
| Our Hybrid | Very Good | Fast-Medium | Moderate |
Selected: LOD-Based Water System
// Water vertex shader with LOD-aware complexity
uniform float uTime;
uniform sampler2D displacementMap; // FFT or baked
void main() {
vec3 pos = position;
// Distance-based LOD
float dist = distance(cameraPosition, pos);
if (dist < 50.0) {
// Near: Full FFT displacement or multiple Gerstner waves
pos += gerstnerWave(pos, uTime, wave1);
pos += gerstnerWave(pos, uTime, wave2);
pos += gerstnerWave(pos, uTime, wave3);
} else if (dist < 200.0) {
// Medium: Simplified waves
pos += gerstnerWave(pos, uTime * 0.5, wave1);
} else {
// Far: Vertex-only displacement, no normal recalculation
pos.y += sin(pos.x * 0.1 + uTime) * 0.5;
}
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
Shoreline Effects:
// Fragment shader shoreline
void main() {
// Depth-based foam
float depth = getLinearDepth(screenCoord);
float waterDepth = depth - waterSurfaceDepth;
// Shore foam
float foam = smoothstep(0.0, 2.0, waterDepth) *
noise(worldPos.xz * 10.0 + uTime);
// Wet sand extension
float wetSand = smoothstep(0.0, 5.0, waterDepth);
// Refraction with chromatic aberration
vec2 refractUV = screenCoord + normal.xz * refractionStrength;
vec3 refractColor = texture2D(sceneTexture, refractUV).rgb;
// Combine
vec3 finalColor = mix(refractColor, foamColor, foam);
finalColor = mix(finalColor, waterColor, waterOpacity);
gl_FragColor = vec4(finalColor, 1.0);
}
4. Gameplay Systems
4.1 Physics Architecture (Half-Life Inspired)
Engine Selection
| Option | Integration | Features | Performance | Verdict |
|---|
| Ammo.js | Good | Full Bullet | Heavy | Overkill |
| Cannon-es | Excellent | Rigidbody, vehicles, constraints | Good | Selected |
| Oimo.js | Good | Lightweight | Very Good | Alternative |
| Custom | Native | Limited | Fast | For specific systems |
Integration Design
class PhysicsWorld {
constructor() {
this.world = new CANNON.World();
this.world.gravity.set(0, -9.82, 0);
this.world.broadphase = new CANNON.SAPBroadphase();
this.world.solver.iterations = 10;
// Material interactions
this.materials = {
player: new CANNON.Material(),
terrain: new CANNON.Material(),
vehicle: new CANNON.Material(),
prop: new CANNON.Material()
};
// Contact materials for realistic friction
this.setupContactMaterials();
}
// Physics body pooling for projectiles
projectilePool = new ObjectPool(() => {
return new CANNON.Body({
mass: 0.1,
shape: new CANNON.Sphere(0.05),
linearDamping: 0.1
});
}, 100);
step(deltaTime) {
// Fixed timestep for stability
this.world.step(1/60, deltaTime, 3);
this.syncVisuals();
}
}
Object Interaction System
class InteractionSystem {
// Gravity gun / pickup mechanics
holdObject(body) {
// Create constraint between player and object
this.constraint = new CANNON.PointToPointConstraint(
body,
localPivot,
playerBody,
playerPivot
);
this.world.addConstraint(this.constraint);
}
// Physics-based doors, breakable objects
createBreakableObject(position) {
// Compound body that fractures on impact
return new BreakableBody({
fractureThreshold: 50, // Newtons
shardCount: 8,
shardMass: 0.5
});
}
}
4.2 Vehicle System
Architecture
┌────────────────────────────────────────────────────┐
│ VEHICLE SYSTEM │
├────────────────────────────────────────────────────┤
│ VehicleController │
│ ├── State: ENTERING, DRIVING, EXITING, PARKED │
│ ├── Input: W/A/S/D + Mouse (camera) │
│ └── Physics: RaycastVehicle (Cannon-es) │
├────────────────────────────────────────────────────┤
│ RaycastVehicle Setup │
│ ├── Chassis: Box shape, ~1000kg │
│ ├── Wheels: 4 raycast sensors │
│ │ └── Suspension: Spring-damper model │
│ └── Engine: Torque curve, gears, max speed │
├────────────────────────────────────────────────────┤
│ Camera System │
│ ├── Interior: First-person cockpit view │
│ └── Exterior: Chase cam with collision avoidance │
└────────────────────────────────────────────────────┘
class VehicleController {
createVehicle(position) {
// Chassis
const chassisShape = new CANNON.Box(new CANNON.Vec3(1, 0.5, 2.5));
const chassisBody = new CANNON.Body({ mass: 1000 });
chassisBody.addShape(chassisShape);
chassisBody.position.copy(position);
// Vehicle
this.vehicle = new CANNON.RaycastVehicle({
chassisBody: chassisBody,
indexRightAxis: 0,
indexUpAxis: 1,
indexForwardAxis: 2
});
// Wheels
const wheelOptions = {
radius: 0.5,
directionLocal: new CANNON.Vec3(0, -1, 0),
suspensionStiffness: 30,
suspensionRestLength: 0.3,
frictionSlip: 1.4,
dampingRelaxation: 2.3,
dampingCompression: 4.4,
maxSuspensionForce: 100000,
rollInfluence: 0.01,
axleLocal: new CANNON.Vec3(-1, 0, 0),
chassisConnectionPointLocal: new CANNON.Vec3(1, 1, 0),
maxSuspensionTravel: 0.3,
customSlidingRotationalSpeed: -30,
useCustomSlidingRotationalSpeed: true
};
// Add 4 wheels
this.vehicle.addWheel({
...wheelOptions,
chassisConnectionPointLocal: new CANNON.Vec3(-1, 0, 1.5)
});
// ... repeat for all wheels
this.vehicle.addToWorld(this.physicsWorld);
// Visual mesh synchronization
this.syncVehicleMesh();
}
update(input) {
if (this.state !== 'DRIVING') return;
const maxSteerVal = 0.5;
const maxForce = 1000;
const brakeForce = 100;
this.vehicle.setSteeringValue(input.mouseX * maxSteerVal, 0);
this.vehicle.setSteeringValue(input.mouseX * maxSteerVal, 1);
if (input.forward) {
this.vehicle.applyEngineForce(-maxForce, 2);
this.vehicle.applyEngineForce(-maxForce, 3);
} else if (input.backward) {
this.vehicle.applyEngineForce(maxForce, 2);
this.vehicle.applyEngineForce(maxForce, 3);
}
// Brake
if (input.brake) {
this.vehicle.setBrake(brakeForce, 0);
this.vehicle.setBrake(brakeForce, 1);
this.vehicle.setBrake(brakeForce, 2);
this.vehicle.setBrake(brakeForce, 3);
}
}
enter(player) {
// Attach player to vehicle
// Switch camera to vehicle cam
// Disable player physics body
this.state = 'DRIVING';
}
exit() {
// Position player next to vehicle
// Re-enable player physics
// Switch to player camera
this.state = 'PARKED';
}
}
5. Performance & Optimization Strategy
Rendering Pipeline
class OptimizedRenderer {
constructor() {
this.renderer = new THREE.WebGLRenderer({
antialias: false, // Use FXAA/TAA instead
powerPreference: 'high-performance'
});
// WebGL2 features
this.renderer.capabilities.maxSamples = 4;
// Draw call batching
this.setupInstancing();
// GPU culling
this.setupHiZOcclusionCulling();
}
setupInstancing() {
// Group similar meshes for instanced rendering
this.instanceManagers = {
vegetation: new InstancedMeshManager(maxVegetationCount),
rocks: new InstancedMeshManager(maxRockCount),
debris: new InstancedMeshManager(maxDebrisCount)
};
}
render(scene, camera) {
// 1. Frustum culling (Three.js built-in)
// 2. Occlusion culling (custom Hi-Z)
// 3. LOD selection
// 4. Opaque pass
// 5. Decals / overlays
// 6. Transparent pass (clouds, water)
// 7. Post-processing
}
}
Memory Management
| Resource | Budget | Strategy |
|---|
| Textures | 512MB | Texture streaming, DXT compression |
| Geometry | 256MB | LOD, mesh streaming, instancing |
| Physics | 64MB | Body pooling, sleep states |
| Audio | 64MB | Streaming, 3D audio culling |
| GPU Buffers | 128MB | Dynamic updates, ring buffers |
6. Development Roadmap
Phase 1: Foundation (Weeks 1-3)
Phase 2: World Generation (Weeks 4-6)
Phase 3: Visual Systems (Weeks 7-9)
Phase 4: Gameplay (Weeks 10-12)
Phase 5: Polish (Weeks 13-14)
7. Risk Assessment & Mitigation
| Risk | Likelihood | Impact | Mitigation |
|---|
| GPU compute not supported | Low | High | Fallback to CPU generation with worker threads |
| Physics stability issues | Medium | High | Use fixed timestep, sub-stepping, conservative collision shapes |
| Memory overflow on large terrain | Medium | High | Aggressive LOD, texture streaming, chunk unloading |
| Shader complexity crashes mobile | High | Medium | Desktop-first, shader permutation system for scalability |
| Development scope creep | High | High | Strict milestone deadlines, vertical slice priority |
8. Technical Milestones
| Milestone | Success Criteria | Exit Quality |
|---|
| Terrain Streaming | 9 chunks loaded, 60fps | No pop-in, smooth LOD transitions |
| Cloud System | 50 cloud volumes, 60fps | Volumetric appearance, proper lighting |
| Vehicle Physics | Drivable jeep on terrain | Suspension feels good, no jitter |
| Combat Loop | Shoot, reload, AI dies | Satisfying feedback, stable physics |
Summary
This architecture prioritizes GPU-driven procedural generation for scalability, Cannon-es physics for reliability, and aggressive LOD systems for performance. The modular design allows each system to be developed and tested independently.
Key Technical Decisions:
- GPU compute for terrain → Enables large, detailed worlds
- Shell texturing for clouds → Best quality/performance ratio
- Cannon-es for physics → Proven stability, vehicle support
- Instancing + LOD for rendering → Handles dense environments
The result should demonstrate that Three.js can deliver a compelling FPS experience comparable to mid-2000s AAA titles when architected with performance as a primary constraint.