TExcelTAD
Home › 3D Web Games with Three.js › lil-gui, Spector.js & three-mesh-bvh

lil-gui, Spector.js & three-mesh-bvh

Every Three.js developer ends up with the same small toolbox: a tweak panel to tune values while the game runs, a frame-rate meter, a WebGL inspector for when the picture is wrong, and three-mesh-bvh for when raycasts get slow. This lesson sets them up, plus the built-in helpers and browser tools that cost nothing.

lil-gui: a tweak panel in five lines

lil-gui (npm install lil-gui; Three.js's own examples vendor a copy as three/addons/libs/lil-gui.module.min.js) builds a small panel of sliders, checkboxes, color pickers and dropdowns bound directly to object properties. It's how you find the right light intensity, jump height or fog distance in minutes instead of edit-reload cycles. Stats (three/addons/libs/stats.module.js, or the newer stats-gl package) adds the classic FPS / frame-time graph.

Both are in the addons folder, so they run here. Open the panel and tune the scene:

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
import Stats from 'three/addons/libs/stats.module.js';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.toneMapping = THREE.AgXToneMapping;
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#9cbfe0');
scene.fog = new THREE.Fog('#9cbfe0', 10, 40);
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);
camera.position.set(6, 4, 8);
camera.lookAt(0, 0.5, 0);
addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});
const hemi = new THREE.HemisphereLight('#dfeaff', '#4a3f33', 1.2);
const sun = new THREE.DirectionalLight('#fff2dd', 2.5);
sun.position.set(-4, 8, 3);
sun.castShadow = true;
scene.add(hemi, sun);
const floor = new THREE.Mesh(new THREE.PlaneGeometry(60, 60), new THREE.MeshStandardMaterial({ color: '#7a9a63' }));
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const mat = new THREE.MeshStandardMaterial({ color: '#e0763c', roughness: 0.4, metalness: 0 });
const knot = new THREE.Mesh(new THREE.TorusKnotGeometry(0.8, 0.28, 160, 20), mat);
knot.position.y = 1.4;
knot.castShadow = true;
scene.add(knot);

// The panel: each line binds a property of an object.
const params = { spin: 0.5, color: '#e0763c', toneMapping: 'AgX' };
const gui = new GUI({ title: 'Tweaks' });
gui.add(params, 'spin', 0, 3, 0.1);
const look = gui.addFolder('Look');
look.addColor(params, 'color').onChange((v) => mat.color.set(v));   // a hex string: see the note below
look.add(mat, 'roughness', 0, 1, 0.01);
look.add(mat, 'metalness', 0, 1, 0.01);
look.add(mat, 'wireframe');
const light = gui.addFolder('Light');
light.add(sun, 'intensity', 0, 8, 0.1).name('sun');
light.add(hemi, 'intensity', 0, 4, 0.1).name('hemisphere');
light.add(sun, 'castShadow').name('shadows');
const render = gui.addFolder('Rendering');
render.add(params, 'toneMapping', ['None', 'ACESFilmic', 'AgX', 'Neutral']).onChange((v) => {
  renderer.toneMapping = { None: THREE.NoToneMapping, ACESFilmic: THREE.ACESFilmicToneMapping, AgX: THREE.AgXToneMapping, Neutral: THREE.NeutralToneMapping }[v];
});
render.add(renderer, 'toneMappingExposure', 0.2, 2, 0.05).name('exposure');
render.add(scene.fog, 'far', 15, 100, 1).name('fog far');
gui.close();                                                   // start collapsed: click "Tweaks"

const stats = new Stats();                                     // FPS; click the graph for ms and MB
document.body.appendChild(stats.dom);
stats.dom.style.cssText = 'position:fixed;left:0;top:0';

const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
  timer.update(t);
  knot.rotation.y += params.spin * Math.min(Math.max(timer.getDelta(), 0), 0.1);
  renderer.render(scene, camera);
  stats.update();
});
</script>

Note: lil-gui can bind a THREE.Color directly (gui.addColor(material, 'color')), but it then shows and edits the color's linear components as if they were sRGB, so the swatch and hex value don't match what you typed in code. Bind a hex string and convert it in onChange, as above. See Color Spaces & Tone Mapping.

Habits that make tweak panels pay off:

  • Bind the panel to your real config objects (player.jumpHeight, camera.followSharpness), not copies, so changes apply immediately.
  • Add a "copy values" button (gui.add({ copy: () => navigator.clipboard.writeText(JSON.stringify(gui.save())) }, 'copy')) so tuned values make it back into the code. gui.save() / gui.load() serialize all controllers.
  • Hide the panel in production builds (if (import.meta.env.DEV) with Vite), or behind a key.

Built-in helpers

Helper Shows
AxesHelper, GridHelper, PolarGridHelper orientation and scale
BoxHelper(object), Box3Helper(box) bounding boxes (culling and collision bugs)
CameraHelper(light.shadow.camera) a shadow camera's frustum (Shadows)
DirectionalLightHelper, PointLightHelper, SpotLightHelper, HemisphereLightHelper where lights are and where they point
SkeletonHelper(model) the bones of a skinned mesh
ArrowHelper(dir, origin, length) any vector: velocities, normals, ray directions
VertexNormalsHelper (addons) the normals of a mesh (lighting bugs)

Add helpers behind a debug flag. Seeing a velocity vector or a collider's box solves bugs in seconds that print statements take an hour to find.

Spector.js: inspect a frame

When the picture is wrong (black objects, missing textures, mysterious draw-call counts), Spector.js shows what WebGL actually did. Install the browser extension (Chrome or Firefox), open your game, click the Spector icon and capture a frame. You get:

  • every WebGL command of that frame, in order, grouped by draw call;
  • for each draw call: the bound textures (with previews), uniforms, shader source, blending and depth state, and the render target contents after it;
  • totals: draw calls, textures, buffers, program switches.

You can also embed it in a page (npm install spectorjs; const spector = new SPECTOR.Spector(); spector.displayUI();) for devices where you can't install the extension. Captures are expensive; use them on a single frame, not while playing.

The browsers' own tools complete the set: the Performance panel (find long frames, see JS vs GPU time), the Memory panel (leaks of geometries and textures), and chrome://gpu (which GPU and which WebGL features this machine really has). Safari's Web Inspector has a similar graphics view.

three-mesh-bvh: fast raycasts against big meshes

Raycaster tests every triangle of every mesh it's given (after a bounding-sphere check). For a 200,000-triangle level mesh, that's 200,000 tests per ray: a few rays per frame for ground checks, bullets and camera collision will eat the frame budget. three-mesh-bvh (by gkjohnson, version 0.9 at the time of writing) builds a bounding volume hierarchy for a geometry: a tree of nested boxes, so a ray only visits the few branches it actually passes through.

js
import * as THREE from 'three';
import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';

THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;
THREE.Mesh.prototype.raycast = acceleratedRaycast;

levelMesh.geometry.computeBoundsTree();      // once, after loading (or in a worker for huge meshes)
raycaster.firstHitOnly = true;               // stop at the first hit: what most game queries want

It also offers shape casts, closest-point queries and capsule-vs-mesh collision (enough for a simple character controller against a level mesh without a physics engine), plus a MeshBVHHelper to visualize the tree. This model shows why a hierarchy wins, with boxes on a 2D grid standing in for triangles:

js · try it yourself
// Count box tests for a ray (a horizontal line y = rayY) with brute force vs a simple BVH.
const boxes = [];
for (let i = 0; i < 100; i++) for (let j = 0; j < 100; j++) boxes.push({ minX: i, maxX: i + 0.8, minY: j, maxY: j + 0.8 });

function build(items, depth = 0) {                   // median split, alternating axes
  const node = { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity };
  for (const b of items) {
    node.minX = Math.min(node.minX, b.minX); node.maxX = Math.max(node.maxX, b.maxX);
    node.minY = Math.min(node.minY, b.minY); node.maxY = Math.max(node.maxY, b.maxY);
  }
  if (items.length <= 8) { node.items = items; return node; }
  const axis = depth % 2 ? 'minY' : 'minX';
  const sorted = [...items].sort((a, b) => a[axis] - b[axis]);
  const mid = sorted.length >> 1;
  node.children = [build(sorted.slice(0, mid), depth + 1), build(sorted.slice(mid), depth + 1)];
  return node;
}
function query(node, y, stats) {
  stats.tests++;
  if (y < node.minY || y > node.maxY) return 0;
  if (node.items) return node.items.reduce((n, b) => (stats.tests++, n + (y >= b.minY && y <= b.maxY ? 1 : 0)), 0);
  return query(node.children[0], y, stats) + query(node.children[1], y, stats);
}

const root = build(boxes);
for (const y of [10.5, 50.2, 10.9, 120]) {
  const brute = boxes.filter((b) => y >= b.minY && y <= b.maxY).length;
  const stats = { tests: 0 };
  const hits = query(root, y, stats);
  console.log(`ray y=${y}: ${hits} hits (brute force ${brute}), tests: brute ${boxes.length}, BVH ${stats.tests}`);
}
ray y=10.5: 100 hits (brute force 100), tests: brute 10000, BVH 571
ray y=50.2: 100 hits (brute force 100), tests: brute 10000, BVH 555
ray y=10.9: 0 hits (brute force 0), tests: brute 10000, BVH 571
ray y=120: 0 hits (brute force 0), tests: brute 10000, BVH 1

A line crossing a whole row still needs about 560 tests (it really does pass through 100 boxes' row), a line in the thin gap between two rows costs about as much (the node boxes overlap the gap, so the tree can't tell until it reaches the leaves), and a ray that misses everything is rejected by the root box in one test. Brute force always pays 10,000. Real rays in a 3D level touch a tiny fraction of the triangles and stop at the first hit, so a BVH typically turns hundreds of thousands of tests into dozens. Physics engines use the same structures internally, which is why their ray casts are fast.

Test yourself

What is lil-gui mainly used for in game development?

  1. Shipping in-game menus
  2. Tuning values (speeds, light intensities, fog) live while the game runs
  3. Profiling the GPU
  4. Loading models

Objects render black and you suspect a missing texture binding. Which tool shows the textures and uniforms of each draw call?

  1. lil-gui
  2. Stats
  3. Spector.js frame capture
  4. three-mesh-bvh

What does raycaster.firstHitOnly = true do with three-mesh-bvh?

  1. Ignores invisible objects
  2. Stops each mesh's BVH query at the closest hit instead of collecting every intersection
  3. Raycasts only the first object in the list
  4. Disables the BVH