
Building Interactive 3D Voxel Maps in the Browser with Three.js and WebGL
A developer just released an interactive 3D voxel map of Warsaw’s city center that’s caught the attention of the Hacker News community, and for good reason. This isn’t some heavy Unity export requiring gigabytes of downloads—it’s a browser-based experience built with web technologies that runs smoothly on desktop while remaining functional on mobile. Users can change the time of day, adjust weather conditions, and even click on pedestrians to take control of them, Dungeon Keeper style.
What makes this particularly interesting from an IT professional’s perspective isn’t just the visual appeal—it’s the technical execution. This project demonstrates how far browser-based 3D rendering has come and showcases practical techniques you can apply to data visualization, urban planning tools, architectural presentations, or any scenario where you need to represent spatial information interactively.
Let’s break down how you can build similar interactive 3D experiences using modern web technologies, starting with the fundamentals and moving into optimization strategies that make these projects actually usable in production.
Table of Contents
- Setting Up Three.js for Voxel Rendering
- Efficient Voxel Geometry and Instancing
- Adding Raycasting and User Interaction
- Performance Optimization for Large Scenes
- Dynamic Lighting and Atmospheric Effects
Setting Up Three.js for Voxel Rendering
Three.js is the de facto library for WebGL in the browser, abstracting away much of the low-level complexity while still giving you the control needed for performance-critical applications. Unlike game engines that require compilation steps, Three.js lets you iterate rapidly and deploy instantly—critical advantages for web-based projects.
Here’s a minimal scene setup that establishes the foundation for voxel rendering:
// Initialize scene, camera, and renderer for voxel environment
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 2000);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
// Position camera for city overview
camera.position.set(50, 80, 50);
camera.lookAt(0, 0, 0);
// Add ambient and directional lighting
const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
scene.add(ambientLight);
const sunLight = new THREE.DirectionalLight(0xffffff, 0.8);
sunLight.position.set(100, 200, 50);
sunLight.castShadow = true;
sunLight.shadow.camera.left = -100;
sunLight.shadow.camera.right = 100;
sunLight.shadow.camera.top = 100;
sunLight.shadow.camera.bottom = -100;
scene.add(sunLight);
This setup includes shadow mapping, which is essential for creating the depth and visual hierarchy that makes voxel scenes readable. The directional light represents the sun, and as you’ll see later, adjusting its position and color lets you simulate different times of day.
Efficient Voxel Geometry and Instancing
The naive approach to voxels—creating individual cube meshes for every block—will destroy your frame rate faster than you can say “memory leak.” A city center might contain tens of thousands of voxels, and each traditional mesh carries significant overhead.
The solution is geometry instancing, where you define a single cube geometry and material, then use InstancedMesh to render thousands of copies with different positions and colors. This dramatically reduces draw calls and memory usage.
Here’s how to implement efficient voxel rendering with instancing:
// Create instanced mesh for efficient rendering of thousands of voxels
const voxelGeometry = new THREE.BoxGeometry(1, 1, 1);
const voxelMaterial = new THREE.MeshLambertMaterial();
const maxVoxels = 50000;
const instancedMesh = new THREE.InstancedMesh(voxelGeometry, voxelMaterial, maxVoxels);
instancedMesh.castShadow = true;
instancedMesh.receiveShadow = true;
// Temporary objects for matrix transformations
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
// Function to add a voxel at specific coordinates
function addVoxel(x, y, z, colorHex, index) {
matrix.setPosition(x, y, z);
instancedMesh.setMatrixAt(index, matrix);
color.setHex(colorHex);
instancedMesh.setColorAt(index, color);
}
// Example: Create a simple building structure
let voxelIndex = 0;
for (let x = 0; x < 10; x++) {
for (let y = 0; y < 20; y++) {
for (let z = 0; z < 10; z++) {
if (x === 0 || x === 9 || z === 0 || z === 9) {
addVoxel(x, y, z, 0xcccccc, voxelIndex++);
}
}
}
}
instancedMesh.instanceMatrix.needsUpdate = true;
instancedMesh.instanceColor.needsUpdate = true;
scene.add(instancedMesh);
This approach lets you render a basic building structure with hundreds of voxels while maintaining smooth performance. The InstancedMesh API gives you per-instance colors and transforms without the overhead of separate mesh objects.
Adding Raycasting and User Interaction
The Warsaw voxel map's ability to click on pedestrians and control them demonstrates sophisticated interaction handling. In Three.js, this is accomplished through raycasting—casting a virtual ray from the camera through the mouse position to detect intersections with 3D objects.
For IT professionals building dashboards or visualization tools, this same technique enables clicking on data points in 3D space, selecting buildings in architectural models, or interacting with network topology visualizations. If you're looking to deepen your understanding of interactive web graphics and related front-end technologies, Coursera offers comprehensive courses on computer graphics and web development that cover these concepts in depth.
Implementing raycasting requires careful consideration of performance, especially with instanced meshes where you need to determine not just which mesh was clicked, but which specific instance within that mesh.
Handling Click Events in 3D Space
The raycaster needs to convert 2D mouse coordinates into 3D world coordinates, then check for intersections:
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Convert mouse coordinates and perform raycasting
renderer.domElement.addEventListener('click', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObject(instancedMesh);
if (intersects.length > 0) {
const instanceId = intersects[0].instanceId;
console.log(`Clicked on voxel instance: ${instanceId}`);
// Highlight or modify the clicked instance
const highlightColor = new THREE.Color(0xff0000);
instancedMesh.setColorAt(instanceId, highlightColor);
instancedMesh.instanceColor.needsUpdate = true;
}
});
This code captures click events, translates them into 3D space, and identifies which specific voxel instance was clicked. You can extend this to trigger animations, open information panels, or change the camera focus—exactly the kind of interaction patterns that make data visualization tools genuinely useful rather than just pretty.
Performance Optimization for Large Scenes
The Warsaw map works smoothly because it implements several critical optimization strategies. When you're rendering city-scale scenes with potentially hundreds of thousands of voxels, performance becomes non-negotiable.
Key optimization techniques include:
- Frustum culling: Three.js handles this automatically, but you can optimize further by organizing voxels into spatial hierarchies
- Texture atlasing: Combine multiple textures into a single atlas to reduce texture binding overhead
- Geometry merging: For static structures, merge adjacent voxels into single optimized meshes
- Web Workers: Offload voxel data processing and collision detection to separate threads
For professionals looking to master these performance optimization techniques alongside data processing workflows, DataCamp provides practical courses on working with large datasets and efficient algorithms that translate well to 3D rendering contexts.
Implementing Chunk-Based Rendering
Divide your voxel world into chunks (typically 16x16x16 or 32x32x32 blocks) and only render chunks within view distance:
class VoxelChunkManager {
constructor(chunkSize = 16, viewDistance = 5) {
this.chunkSize = chunkSize;
this.viewDistance = viewDistance;
this.chunks = new Map();
}
// Get chunk key from world coordinates
getChunkKey(x, y, z) {
const cx = Math.floor(x / this.chunkSize);
const cy = Math.floor(y / this.chunkSize);
const cz = Math.floor(z / this.chunkSize);
return `${cx},${cy},${cz}`;
}
// Update visible chunks based on camera position
updateVisibleChunks(cameraPosition) {
const visibleKeys = new Set();
const camChunkX = Math.floor(cameraPosition.x / this.chunkSize);
const camChunkZ = Math.floor(cameraPosition.z / this.chunkSize);
for (let x = -this.viewDistance; x <= this.viewDistance; x++) {
for (let z = -this.viewDistance; z <= this.viewDistance; z++) {
const key = `${camChunkX + x},0,${camChunkZ + z}`;
visibleKeys.add(key);
if (!this.chunks.has(key)) {
this.loadChunk(key);
}
}
}
// Unload distant chunks
for (const [key, chunk] of this.chunks) {
if (!visibleKeys.has(key)) {
this.unloadChunk(key);
}
}
}
loadChunk(key) {
// Create and add chunk mesh to scene
console.log(`Loading chunk: ${key}`);
}
unloadChunk(key) {
// Remove chunk mesh and free memory
console.log(`Unloading chunk: ${key}`);
this.chunks.delete(key);
}
}
This chunk management system ensures you're only rendering what's visible, dramatically reducing the computational load for large scenes. The Warsaw map likely implements something similar to maintain its smooth performance across different hardware capabilities.
Dynamic Lighting and Atmospheric Effects
One of the Warsaw map's most compelling features is the ability to change time of day and weather conditions. These aren't just cosmetic—they demonstrate how dynamic lighting transforms the perception of 3D space and can be applied to any scenario where environmental context matters.
Implementing time-of-day transitions involves smoothly interpolating light color, intensity, and position. The sun moves across the sky, its color shifts from warm orange at dawn to bright white at noon to deep red at sunset, and the ambient light adjusts accordingly.
Creating Dynamic Sky and Weather Systems
Here's a simplified approach to dynamic lighting that responds to a time parameter:
class TimeOfDayController {
constructor(scene, sunLight) {
this.scene = scene;
this.sunLight = sunLight;
this.time = 12; // Hour in 24-hour format
}
// Update lighting based on time of day
setTime(hour) {
this.time = hour;
// Calculate sun position (simplified solar path)
const angle = (hour - 6) * (Math.PI / 12);
this.sunLight.position.set(
Math.cos(angle) * 100,
Math.sin(angle) * 100,
50
);
// Adjust sun color temperature
if (hour < 6 || hour > 20) {
// Night: dim blue
this.sunLight.color.setHex(0x2244aa);
this.sunLight.intensity = 0.1;
this.scene.background = new THREE.Color(0x001133);
} else if (hour < 8 || hour > 18) {
// Dawn/dusk: warm orange
this.sunLight.color.setHex(0xff8844);
this.sunLight.intensity = 0.5;
this.scene.background = new THREE.Color(0xff6633);
} else {
// Day: bright white
this.sunLight.color.setHex(0xffffff);
this.sunLight.intensity = 0.9;
this.scene.background =