Repository navigation
Rendering
The 3D view is plain Three.js driven from React hooks. hooks/use-three-scene.ts owns the renderer, camera, controls, animation loop, resize handling and drag lifecycle; hooks/use-scene-effects.ts holds the effects that rebuild parts of the scene when state changes. Builders in three/ know nothing about React.
These are the rules that keep it fast and leak-free. Most bugs in this area come from breaking one of them.
The animation loop only draws a frame when something asks for one: OrbitControls reporting movement, or a call to the invalidate() function that useThreeScene returns. An idle editor draws nothing.
- Anything that changes the scene outside React state (an animation, a loader callback, a texture arriving late) must call
invalidate(), or the change won't appear until the next orbit. - The walkthrough asks for frames only while the walker moves or looks round; standing still draws nothing.
- The decorative loops (rain and snow, the walkers, the CCTV cone sweep) don't run their own
requestAnimationFrame. They register a step with the editor's frame budget (three/frame-budget.ts), which the render loop ticks once per animation frame: at most 30 steps a second while nothing else draws, every frame during an orbit or a drag, and none while the page is hidden. A window that's on screen but unfocused keeps animating. A step asks for a frame only when it reports a change, and a long gap is cut to 0.1 s so nothing jumps when you come back to the tab. Since 2.1.0 walkers cast no shadow at all (see Contact shadows and materials), so their steps never redraw the shadow map, and the rain and snow fall in the vertex shader, so no particle is re-uploaded per frame. - While the 2D plan is up the 3D canvas is hidden and the loop draws nothing, whatever changes in the house.
- During the walkthrough the loop skips
OrbitControls.update(), which would otherwise fight the pointer-lock camera. - PNG capture renders a fresh frame synchronously before reading the canvas, so
preserveDrawingBufferstays off. -
The first frame waits for its shaders. The first scene's shaders compile in parallel with
compileAsync;lib/shader-warmup.tsholds the first frame until that settles, fails or 4 s pass, and "Loading the lot…" stays up meanwhile. Without it the first visit froze for about two seconds on the first draw.
You can watch this with the ?debug overlay (add ?debug to the URL): the frame counter stands still when nothing moves. It also shows draw calls, triangles, and live geometries, textures and programs, which is the quickest way to spot a leak.
While an item is dragged, its meshes are moved directly and nothing is dispatched; one state update happens on release, so each drag is one undo entry. Collision feedback stays live through a tint on the dragged group. Don't add per-mousemove dispatches or scene rebuilds. If the furniture changes under a drag (another tab's save, the people model loading), the drag aborts without committing.
-
Narrow effect keys. Key rebuild effects on the fields they actually read, not on whole objects.
layout.floors,layout.roofandlayout.terrainget a new identity on unrelated edits, so an effect keyed on them rebuilds meshes and the shadow map for nothing. The furniture effect's keys come fromlib/furniture-scene.ts; labels and the Wi-Fi/vision overlays key onlib/overlay-keys.ts. - Per-item furniture diff. The furniture effect keeps one group per item and storey and compares each item's build key (everything its builder reads, plus tint and ghosting). A move, turn, mirror or lock re-places the existing group; only items whose build key changed are disposed and rebuilt.
- Show or hide before you rebuild. The roof is built while visible and kept, hidden, when you go below the top storey, so a floor switch flips visibility instead of rebuilding every dormer.
Every path that removes something from the scene must free its GPU resources through the helpers in three/builder-utils.ts: disposeObject and removeAndDispose (geometries, materials, textures, shadow maps), and disposeScene when the editor unmounts. Skipping them leaks GPU memory on every rebuild.
- Procedural textures (wall and floor patterns and their relief maps) are cached in an LRU (
three/texture-lru.ts) that disposes what it evicts. - Textures shared by every item or the whole lot (ground tiles, furniture detail textures, the lit-window texture) are marked shared, survive rebuilds, and are freed when the editor unmounts.
- Placed and walking people share the cached
people.glbgeometry. It's marked withmarkSharedGeometry(a WeakSet thatdisposeObjectskips) and released when the editor unmounts. Outfits don't copy it: at load its triangles are sorted into body regions, and each person draws a view of the same index and attributes with one material per run of same-coloured regions (at most five draws per mesh). Hair is built once and hung on each clone's head bone. Don't mutate a person's geometry. - Clone rigged people with
SkeletonUtils.clone, never plain.clone(): a plain clone shares the live skeleton and breaks anything that serialises the graph, such as the GLB export.
lib/render-quality.ts picks the renderer's settings from the device class and the View options Quality choice (saved in localStorage under render-quality, per device):
| Tier | Pixel ratio cap | Sun shadow map | Shadow radius | Ground tile | Anisotropy | Rich scenery | Settled frame |
|---|---|---|---|---|---|---|---|
| Low | 1.5 | 1024² | 2 | 256 px | 4 | no | no |
| Medium | 2 | 2048² | 3 | 512 px | 8 | yes | no |
| High | 2 | 4096² | 4 | 512 px | 16 | yes | yes |
Auto takes the device's tier (phones low, other coarse-pointer devices medium, mouse devices high) for the pixel ratio, ground tiles and scenery, but keeps the 2048² map at radius 3, the GPU's full anisotropy and no settled frame, as every device had before the tiers, so the default picture didn't change. "Rich scenery" is the clouds and full sky dome, the ground and road fading past the lot, the kerb and the grass's second (macro) lookup; on a phone they cost about a millisecond a frame and ten shader programs. A change applies live: three/texture-settings.ts re-uploads every texture that asked for the maximum anisotropy, and setSkyDetail rebuilds the sky.
Separately from the tier, a phone (coarse pointer, short side up to 500 CSS px: isPhone) gets smaller textures in three/texture-settings.ts: 256 px pattern and detail tiles instead of 512, no relief maps, a half-density contact map, and no reveals (revealsEnabled). These are read once per page, so phones draw no slower than before 1.29.0 whatever the choice.
Since 2.1.0 an explicit High quality adds soft ambient occlusion once the scene rests (three/settled-frame.ts): corners darken and furniture sits on the floor. Ambient occlusion costs tens of milliseconds a frame, far too slow for an orbit, but an editor rests most of the time and render-on-demand draws nothing then, so one such frame is affordable.
-
When: a pure schedule (
createSettleSchedule) waits 150 ms after the last frame (SETTLE_QUIET_MS), and an orbit's damping tail still counts as motion. The occlusion then fades in over six frames (one under reduced motion), and the editor is idle again. A scene that redraws on its own a little slower than the quiet time (an auto-cycling sun, a walker that pauses) would pay for a settled frame each time it stops, so each settle broken within a second doubles the wait, up to 4 s, and the next press, wheel or key brings it back to 150 ms. The loop owns no timer or rAF for it: it asks the schedule on frames it would otherwise skip. -
How: the frame is the normal frame, drawn exactly as the loop draws it, with three's
GTAOPassocclusion multiplied over it. No composer, no offscreen colour target and no second tone-mapping path, so with the occlusion at zero the settled frame is the normal frame byte for byte: nothing shifts as it settles, and MSAA stays the canvas's own. The pass and its addon code load lazily (loadSettledFrame), so only a device that rests on High pays for them. -
What it leaves alone: outlines, the placement ghost, camera cones, labels and glass are tagged in
three/occlusion-overlays.ts(a WeakSet, neveruserData) and never darkened. -
Stills: PNG capture and photo mode render through
renderStill, which draws the settled frame when this renderer has the pipeline, so photos and PNGs taken on High have the occlusion too.
- Three.js r187 since 2.1.0. Its PMREM (cube render targets) spreads the studio light a little differently: faces turned up gain about 1.5 % luminance and walls lose about as much. No single scale fixes both, so the light levels keep their r186 values and reflections look slightly different. r187 fixes the PCF shadow path's bias sign, but not its far-plane test, and on Metal the depth buffer is 24-bit fixed point, where reversed Z adds no precision, so the reversed depth buffer stays off and coplanar meshes keep their gaps.
-
Pipeline: ACES tone mapping, sRGB output, pixel ratio capped at 2 (1.5 on phones), PCF shadows softened by the sun's
shadow.radius, and image-based lighting from a PMREM-filteredRoomEnvironment. The time of day drives the sun, sky, hemisphere, ambient and environment intensities, fading through dusk so nights are dark. -
Shadows: one sun shadow map, 2048² unless the quality tier says otherwise. Its camera is fitted to a box around every shadow caster (house, roof, trees, street) in
lib/sun-shadow.ts.shadowMap.autoUpdateis off: the map is refreshed only when a caster moves. Weather particles never cast shadows, and window and shower glass don't either. -
Lamps share a fixed pool of eight point lights (
planLampPoolinlib/night-lights.ts, applied inuse-scene-effects.ts). They're given to the lamps nearest the viewer (the orbit target, or the walker) on the storeys being drawn. The pool is only in the scene while a lamp is lit, and its shaders compile in the hours before dusk. Each slot also carries a soft additive halo sprite at its bulb. Never add a light per item: every point light costs every lit fragment even at intensity 0, and changing the number of lights recompiles every shader. -
Indoor lamps stay indoors (
three/outdoor-lamps.ts): outdoor materials (the lot, the neighbours, the roof, and the outside face of shell walls and dormers, marked by a per-vertex attribute) scale each pool light by a shared per-slot uniform, 1 for a lamp outdoors and 0 for one behind the walls. A lamp assignment writes the array and recompiles nothing; by day, with the pool out of the scene, the patch compiles to the same program as an indoor material. -
Night glow (
three/night-glow.ts, planned bynightGlowPlaninlib/night-lights.ts) only writes material values: lit window glass (one shared room-light texture), lamp shades and bulbs, the neighbours' lit panes. Nothing recompiles and nothing runs per frame. Since 2.1.0 a walker inside at night sees the dark outside through a pane: the pane's tint, lit by the room, laid a pale dusk-like film over the dark garden, so for a walker indoors the tint fades with the sky's darkness (outsideDark, the sky's twilight to the fourth power), and dusk keeps its glow. The orbit view and the day keep the builder's pane. A walker indoors at night gets a warm fill when a lamp on its storey reaches it with no partition between; that's checked every 400 ms, not per frame. -
The sky (
three/sky.ts) is a world-space dome with clouds and a sun disc, kept centred on the camera inonBeforeRender, so a camera move needs no rebuild. Only colours change per hour step. The lot's grass, paving and asphalt share generated tiles (three/ground-surfaces.ts) laid by world position. -
TV screens switched on in EXPLORE (
three/tv-screens.ts, since 1.38.0) glow through their material's emissive colour only: no light, no texture, so nothing recompiles. Screens are known by their material in a WeakSet, neveruserData, which the GLB would carry. -
Walkers' thought bubbles (
three/need-bubbles.ts, since 1.38.0) are one canvas atlas with a cell per need, drawn once per walker set, and one sprite per walker whose map swaps between the atlas's views; showing or hiding one is avisibleflip, never a rebuild. The atlas textures are marked shared, sodisposeObjecton a walker leaves them. - The WebGL context is restored automatically if the GPU drops it, and the image-based light is baked again, so the scene keeps its lighting.
-
Contact shadows (
lib/contact-shadow.tsplans,three/contact-shadow.tspaints): one baked canvas per storey on one quad,CONTACT_PLANE_GAP(18 mm) over the floor so it clears rugs and zone patches. Items, stairs and walls each leave a soft patch; doors and stairwell holes wipe it. A drag repaints the map once as it starts and once on the drop, never per move. Since 2.1.0 placed people and pets leave a small soft pool with a darker core at their feet, since only the feet touch the floor. -
Walkers' ground patches (since 2.1.0): walkers cast no shadow, because their steps would recompute the static shadow map, and the baked storey map can't follow them. Instead each one carries a small soft disc under its feet,
FIGURE_CONTACT_GAP(22 mm) over the floor, above the baked map and the rugs, and in the sun a soft streak laid away from it (figureSun: as long as a 1.75 m figure's shadow at the sun's elevation, at most 3.2 m, fainter with a lower or weaker sun). The streak is only drawn where the sun can reach, not indoors or upstairs, and both patches shrink on a slope such as a porch step's edge (figureSlopeScale). One disc and one streak (geometry, texture and material) are shared by every walker; an hour or weather change re-aims them all. -
Furniture surfaces (
three/furniture-materials.ts): material classes (fabric, leather, oiled and lacquered wood, ceramic, painted, brushed metal, plastic), non-metals at metalness 0 and metals at 1. Wood, fabric and leather share one grey detail texture per kind (lib/detail-patterns.ts), drawn on first use.softBoxinthree/builder-utils.tsreplaces a box with chamfered edges and UVs in metres, so a detail texture keeps its scale on every part;mergePartsjoins an item's static parts that share a material into one geometry, so a kitchen unit's doors draw with its carcass in one call. -
Pattern relief (
three/surface-maps.ts): each floor and wall pattern paints a greyscale height tile on the same layout as its colour tile, turned once per pattern and size into a normal map and a roughness map. Not on phones. -
Reveals (
three/reveals.ts): openings in the outer walls get a lining, and the door or window is set back inside its group, never in its saved position, so the plan, collisions and the walker's door gaps don't move. -
The GLB (
three/building-export.ts) drops the relief and detail maps (stripRelief,stripDetailMaps) and the outside-face attribute: they're view effects, and would be extra images in the file.
The walkthrough is its own wall-display mode: every wall and the roof are up, lower storeys get a ceiling and stairwells are lined. Effects read the derived wallDisplay and ghostOtherFloors (via sceneWallDisplay in lib/walkthrough-view.ts), never view.wallDisplay directly.
A mesh that sits against a wall, the ground or the plinth needs a small gap, or it z-fights. Use the existing constants: BASEBOARD_WALL_GAP (three/baseboard.ts), EARTH_WALL_GAP (three/terrain.ts), PARTY_WALL_GAP (lib/street-row.ts), REVEAL_WALL_GAP (three/reveals.ts), FLOOR_SLAB_WALL_GAP (three/room-builder.ts) and CONTACT_PLANE_GAP and FIGURE_CONTACT_GAP (three/contact-shadow.ts).
Garden surfaces (three/ground-patches.ts, since 1.38.0) are one mesh of low slabs per kind, every patch of that kind merged into it, their tops just under the ground line at heights that keep the kinds and the grass apart; the GLB gets them in plain colours, since the view's tiles follow world position. The lot's grass tufts, shrubs, flowers, road dashes and stepping stones are InstancedMeshes, static meshes bake their matrices once, and the perimeter trees are merged into one mesh per kind and part. Keep high-count decoration instanced or merged.
Unit tests can't see any of this. Run the app, look at it in 3D and 2D, check the ?debug counters before and after (geometries and textures should return to the same numbers after a rebuild), and confirm undo still works. See Development and testing.
Open the app · Source on GitHub · Report an issue · MIT licence
Using the app
- Getting started
- Architect career
- Building the house
- Rooms and zones
- Roof and dormers
- Site and neighbours
- Tracing a floor plan
- Furnishing
- Catalogue
- Budget
- Templates, themes and sets
- Floors and stairs
- Lighting, weather and time of day
- Wi-Fi and security planning
- Views and tools
- The 2D plan
- Walkthrough
- Phones and tablets
- Achievements and statistics
- Saving, sharing and history
- Export and print
- Accessibility
- Keyboard shortcuts
- FAQ and troubleshooting
Contributing
Links