stream-core.js  ·  chunk-core.js  ·  ray-core.js  ·  stream-viewer.html  ·  interactive companion

The Renderer

You fly through a world 65,536 voxels on a side, with 3.45 trillion of them solid, and a frame takes a few milliseconds. The GPU never sees that world. It sees a few hundred 64³ pieces of it, and the rest of the code chooses those pieces, builds them away from the main thread, and never leaves a gap while they arrive. This page shows how the parts fit together first, then takes each part in turn, with the real code running.

65,536³
world side, D = 16
3.45 T
solid voxels
64³
the unit of everything
4 + 4 B
a cube: record, colour
0.3–15 M
cubes a view
18
indices a cube: three faces
which chunks? selectChunks the cut: a partition of the world, finer near the eye when the eye moves what's ready? coverOf the cover: the finest complete tiling of what's resident and when a chunk lands which path? chooseKinds raster or ray, per chunk, from its density (opt-in) and when a chunk lands which pixels? renderView raster (three faces a cube), stencil, ray, blit every frame

This page matches the viewer at commit 3d7894a (2026-11-26). Its cores are imported, so they're always today's, and §12's line numbers are looked up as the page loads. Its drawing lab is a shortened copy of renderView, and its prose describes the viewer as it was at that commit. The page is refreshed when the renderer changes a lot, not kept in step line by line. The first version was 2026-11-06. This refresh adds the faster job (§4), three faces a cube (§5), the shadow rule and the locked lod (§3, §4), the viewer's defaults in every demo, and universes (§11).

01

The whole thing on one page

This is the page's most important section, so start with the viewer's own frame function. Here it is with its details removed:

function frame(){ if (W.endless) endlessTick(); // §11 the endless lattice: re-centre the window, take the worlds that landed if (eye moved) streamer.update(eye); // §3 §9 re-cut the world, re-cover it, choose paths, order the job queue pool.dispatch(); // §4 hand jobs to idle workers, and don't wait for them streamer.service(); // §7 admit finished jobs, under a time and a byte budget editFlipped(); // §7 if an edit's results all landed this frame, the page follows the new root draw(); // §10 renderView: draw whatever is resident, right now; then the passes after it }

The middle four lines are the whole renderer. The first and the fifth do nothing unless you're in an endless lattice or editing, and draw() is renderView followed by passes that never touch the frame it made: SSAO, the wireframe, and edit mode's preview and outline (§10).

Five facts explain almost everything else in the code:

  1. The GPU never sees the DAG. The DAG lives on the main thread, with a copy in each worker. The GPU gets only finished pieces: records or ray pages.
  2. The chunk is the only unit. A chunk is one DAG node holding a 64³ grid of cells. Near the eye a cell is a voxel, and farther away it stands for 2, 4, 8… voxels on a side. Every chunk, near or far, costs about the same to store and draw. That is why a view's cost doesn't grow with the world.
  3. Deciding and doing are separate. Every decision is a pure function in stream-core.js, tested in Node on a virtual clock. The page and stream-pool.js only move messages and buffers. When you read the viewer, you are mostly reading the doing.
  4. Nothing waits. A frame draws what is resident, coarser than wanted if it has to. No frame ever blocks on a job, so flying too fast costs detail. It doesn't cost frame rate, and it doesn't leave holes.
  5. Cubes are the default, and a cube is three faces. The raster pass costs per cube, not per pixel, so the viewer draws of each axis's two faces only the one on the eye's side, which halved the pass (§5). A second path, rays, costs per pixel instead. It is built and tested, and joined to the raster by one depth buffer, but the viewer has drawn raster only since 2026-11-09 (it felt snappier), so the ray path is opt-in (?ray=density, §8, §9).

What the eye costs, right now, in the world chosen at the top right

Each row is measured live on this page's own streamer, from the eye the other sections share. The drop that matters is from voxels to cubes, by a factor of a thousand or more: that's what chunks and lods buy. The bars use a log scale, or you couldn't see the small ones at all.

The demos below all share one world, one eye and one streamer, with real workers, so what you do in one section shows up in the others. They start at the viewer's defaults: the shadow rule, detail 4, raster only. The drawing lab in §7, §9 and §10 is not the viewer. It is a smaller copy of its passes, built on the same GLSL_DECODE and GLSL_RAY and the same cores. §12 lists what it leaves out.

02

Five sizes, one address

Most of the difficulty in reading the code is keeping these words apart. Level counts up from the voxel: a level-k node is 2k voxels on a side. Lod says how much of that a single cell stands for. Everything else follows from those two, and from always splitting a chunk into the same 64³ cells:

wordwhat it isDAG levelside, cellsside, voxelsdecided in
Click any pane to move the pick. Slices are horizontal, at the pick's height.

The walk from the root, real node ids

The cell's 18-bit address inside its chunk

Two details matter later. The address is Morton (octant-major), because the DAG's octant order is Morton, so a depth-first walk emits a chunk's cells already sorted by index. And index >> 9 is the brick, the 8³ block a ray page stores as 512 bits (§8). A brick at lod l is also a real DAG node, at level l + 3, which is what lets two chunks share one.

03

The cut: which chunks the eye wants

The first question has a one-line answer. Start from the top chunk, the whole world at its coarsest. Split any chunk that is closer to the eye than detail of its own sides. Skip the empty children, which the DAG names for free. What's left when nothing more wants to split is the cut: leaves that partition the world, with the split chunks above them. The rule compares distance with size, so a leaf always spans about the same angle on screen, whatever its lod. That is ifsandwhats.md's clipmap, as a cut through an octree.

// selectChunks, without the heap and the cap. splitsAt is the rule, exported so a universe's cut (§11) asks the same one.
const splitsAt = (c, { detail, minLod, lock }) => lock == null ? c.lod > minLod && c.dist < detail * c.size : c.lod > lock;
if (splitsAt(c, cfg)) c.kids = childrenOf(world, c);   // split
else leaves.push(c);                                 // a leaf of the cut

The viewer's detail is 4 (the core's default is 2): a chunk is split until it is four of its own sides away, so a cell spans about half as many pixels as at 2. The locked lod (2026-11-20, lod-locked.md) is the other branch of splitsAt: every chunk is split down to one lod wherever it is, and no further, which is for looking at one lod at a time. The viewer's lod rule menu calls it locked, its cells drawn by the shadow rule (§4), and a slider moves it with no reload.

Drag the white eye marker. Hover over a chunk to see why it stopped splitting, and click one to carry it into §4. Blank areas are empty space, which the cut never visits. Looking from the side shows a terrain best: the cut follows the surface because everything else is empty or buried, and it costs only a few more chunks at each lod.

Deeper worlds, same relative view (real kits, built on this page, cut from the same fraction of the world)

worldsidevoxelsnodesleavessplitlodscut ms
…

Each row's world has 64× the volume of the row above, and the cut grows by a fixed ring of chunks per added lod. That is ifsandwhats.md §5.7's "bounded by screen resolution, not world size", and stream-findings.md §1 measures the same thing in bytes: a smooth view costs 4–6 MB from 2,048³ to 4,096³.

The one-lod rule. Face neighbours in the cut differ by at most one lod when K ≥ 1 and the cap doesn't bind. Say a leaf of side S had a neighbour two lods finer. That neighbour's parent, of side S/2, was split, so it is under K·S/2 from the eye. It lies within S/2 of the leaf, so the leaf is under K·S/2 + S/2 away. But as a leaf it is at least K·S away, which needs K < 1. The seam tail (§6) relies on this, and it's why the K slider stops at 1. maxChunks refuses splits in order of dist / size, so a cap costs detail where it shows least, but past the cap the one-lod promise no longer holds. A lock keeps the promise trivially (every leaf at one lod) until the cap refuses the far chunks, which a lock fine enough always makes it do: try lod 0 on a kit.

04

A job: from one DAG node to bytes

A worker receives { lod, cx, cy, cz, kind, lodRule, root } and returns buffers. What a records job makes is defined by one function, with seams: true, and computed by a faster twin, , which gives the same bytes (more below the demo). Below is a real expandChunk call on the chunk you picked in §3, in one horizontal layer of its 64 cell layers, with fastChunk run beside it and held to its bytes. Everything a job does comes down to answering three questions per cell: is it kept, can anything see it, and what does its record say?

…

This cell's record, 4 bytes

Hover over a cell.

What the job produced

The steps, as expandChunk takes them:

What the workers run: fastChunk (2026-11-07, job-speed-log.md). The same records, words, counts and tail as expandChunk, byte for byte, with three exact changes. A full node lists only its shell: its block of the grid is filled at once and its interior, which can't show a face, is added to occupied as a number. A per-brick rule's kept cells are a 512-bit mask made once per (rule, lod, node) and kept for the snapshot's life, so a repeated brick is walked by its mask with no sort. The seam test starts from the neighbouring chunk's node, 5 child reads instead of D − lod − 1, and each answer is cached for the job. Without colour that's 4–12× on every world benched (warm medians of 1.3–4.3 ms a job). With colour it's 1.4–3.7×, because colour is now most of a job: the kit's warm job is about 1.5 ms of walk and 12–13 ms of words. expandChunk stays the plain reference, and test/job-core.test.js holds the two equal on every chunk of a dozen worlds, with 18 mutants. The table's last rows are the two run here, on this thread: cold (a fresh mask cache) and warm (the same cache, again).

Why it's 3.5× to 150× smaller than block-showroom's record. A centre takes 12 bytes, and the shader can rebuild it from the cell index, the chunk's origin and the cell size, so the 14-byte record drops to 4. That's the 3.5×, and skipping buried voxels is the rest: 6.7 MB against 441 MB over the shapes corpus (expand-findings.md). The workers are the bottleneck in flight, not the bookkeeping, which takes 0.1–2.5 ms a frame (stream-findings.md). That was measured when a job took 2–19 ms. With fastChunk it's still true of coloured worlds, where a D = 13 city's view is 1,290 jobs and about 6 s on four workers (city-frame-cost.md §5).

The shortcut. A chunk that is completely full, with all six neighbours completely full too, expands to nothing, and createJobRunner says so without walking its 262,144 cells. That's most of a terrain's cut underground. It lives in the runner, and fastChunk's shells in job-core, not in expandChunk, so the dense oracles keep testing the plain code. And ask isFull, never a count: voxel counts are float64, so past level 17 a count can't feel one missing voxel.

05

A draw: one chunk, one instanced call

The chunk from §4, drawn the way the raster pass draws it. There is no vertex data per cube. A chunk is one buffer of records and one drawElementsInstanced of a shared cube index, 18 of its 36 indices, and the vertex shader builds the rest from the record, gl_VertexID and three uniforms. The decode is the real GLSL_DECODE from , and the face choice is 's:

// in rasterVS. aRec: this instance's record. A cube has 24 corners, four a face, and 12 of them are run.
vec3 c = recCentre(aRec);                      // uOrigin + (cell + 0.5) * uCellSize: the centre, eye-relative
uint v = uint(gl_VertexID), k = v / 4u;        // k: an axis, 0, 1 or 2
uint face = 2u * k + (c[k] < 0.0 ? 0u : 1u);   // of its two faces, the one on the eye's side
vec3 p = c + CORNER[4u * face + v % 4u] * uCellSize;
gl_Position = uViewProj * vec4(p, 1.0);
if (!faceShown(aRec, face)) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);   // a hidden face collapses outside clip space

Three faces a cube (2026-11-18, city-frame-cost.md). A cube has at most three faces toward the eye, one an axis, and which one is the sign of its centre from the eye: the +x face can face the eye only if the cube is at negative x from it. So of each axis's two faces the shader draws only that one, 12 vertices instead of 24. When the eye is inside a cube's slab on an axis, both of that axis's faces are back-facing, so either choice is culled, which is why the raster pass needs CULL_FACE on. The frame is the same byte for byte: facesSelftest() holds it to the six-face shader on four worlds, three eyes and six headings each. It halved the pass, because the pass is bound by geometry, not pixels: the same view at 1 and at 7.7 million pixels cost the same. In Chrome on the M2 Max, the D = 14 kit's opening view went from 5.8 to 3.9 ms, and a D = 13 city seen from 600 up from 26–31 ms to 15.

Things to notice:

06

Seams: why chunks carry a tail

The apron has a catch. A job hides a boundary face because the neighbour at the same lod has a cell there, but the neighbour may be drawn at another lod, where that cell may not be kept. Then nothing covers the hidden face, and you see sky through the world. Records can't fix that at build time, because a job can't know how its neighbours will be drawn (that changes with every step of the eye), and rebuilding a chunk each time would be far too slow. So the choice is made in the shader:

// GLSL_DECODE. uOpenSides: a bit per side, set when the same-lod neighbour across it isn't drawn.
uint recShown(uint r){ return recMask(r) | (boundaryBits(recCell(r)) & uOpenSides); }

A 2D teaching model: one profile, a side view, lod 0 beside lod 0 or lod 1. The bright lines are faces. A red slit is a face the apron hid and nothing replaced.

Showing boundary faces isn't quite enough, because a cell the apron alone buried has no record at all, and needs one. So each job appends those cells after its main records, as the seam tail, with mask 0, and borderStart says where the tail begins. A chunk with no open side draws [0, borderStart), and a chunk with any open side draws everything. The tail is the whole cost of seams on smooth content: 3.6–6.7% of records, or 43% on a dense porous row. In one terrain view, seams were 11K of 402K cubes (stream-findings.md §3).

Why the tail isn't huge. A buried boundary cell joins the tail only if the coarser cell across its boundary (the level-(lod + 1) node holding the neighbour) isn't completely full. A full cell is drawn by every rule at every lod, so no crack can open against it. Without that test, a solid chunk underground would carry its whole boundary shell, about 23K records. The one-lod rule from §3 is what lets the test look just one level up.

07

The streamer: drawing what's here while the rest arrives

The cut says what the eye wants, and the workers take time. The streamer sits between them, and this is the part that's hardest to see from the code, because it's never doing one thing. It holds a cache keyed by lod:x,y,z, and each frame it answers a new question: given what's resident, what should I draw so that every part of the world appears once, as fine as possible? Its rule is complete beats finer: a region is drawn from its children only if all of them are resident. Otherwise its parent stays up.

What's on screen, drag to look, click then WASD/QE to fly
the lab draws where you're looking

Coverage over the last few seconds (share of the cut's leaves)

The job queue, next first

Where the bytes are

The throttle exists only so you can watch. It caps how many jobs reach the workers a second, and the viewer has nothing like it. Press flush with the throttle at 20 a second to see a world load from the top chunk down.

Four rules to try against the demo

Where edits fit in. A click makes a new root in the same store. setRoot doesn't flush anything. It opens a transaction: a second cut of the new root, and jobs only for what that cut would draw wrongly, 2 to 14 chunks on the worlds measured. Their results are held until the last one lands, and then they all install in one frame, the flip, so every frame draws one root. What lets the cache keep everything else is the stamp: a chunk's job reads exactly seven nodes (its own and six neighbours), and equal ids mean equal voxels, so an entry built from the same seven ids is still right, whatever else changed. edit-stream-log.md has the rest. The "Follow a click" tour in §1 walks it through the map. Since then: one log carries both blocks and dropped worlds, in one order, and its delta is what a worker's tail carries (onelog-log.md). The flip installs what the new plan draws, not only what its cut wants: a chunk held as a leaf and merged away by a jump of the eye mid-edit is still drawn, as the fallback child of its absent parent, and the first flip missed it (onelog-log.md §5). And a world built in workers is made real at the first edit with setStore, a store holding the same ids, so nothing flushes (gizmo-log.md §14).

08

Rays: the other way to draw a chunk

Cubes cost per cube. A dense porous row is 15M cubes and 103 MB in a single view. But the same row is a DAG of under 250 nodes, so its content has very few distinct pieces. The ray path stores a chunk as a page and walks it per pixel. The cost moves from cubes to pixels, and the storage can share pieces between chunks. The viewer has drawn raster only by default since 2026-11-09, so this path is opt-in (?ray=density, or a fixed ?ray=<lod>); this section builds real pages whichever path is chosen above.

structurelayoutwherewhat it's for
page512 words: each brick's atlas slot, 0 if emptyR32UI, a row per pageone chunk, its 8³ grid of bricks
brick512 bits = 16 words, in Morton orderRGBA32UI atlas8³ cells. Shared: keyed by (node id, lod)
cover tree12 words a node: kind, lod, page, 8 childrenRGBA32UI, rebuilt on changefrom a voxel to the page under it
attribute heapper brick: 16-word shown mask, then a word per shown cellR32UI, 4,096 widecolour. A page's own, not the brick's

Below, every leaf of the cut crossing the eye's plane is built as a real page, on this thread, with the real pageJob, createBrickPool and buildCoverTree. The background is classifyPagesCPU at each pixel: bright is occupied, and each darker shade is the size of the empty block that classify reports. Every step of the march jumps out of one of these blocks. Move the mouse to aim, and click to hold the aim.

The march, step by step

A brick: 16 words, 32 cells a word

Hover over the slice.

Why Morton makes empty blocks free. Cells in a brick are numbered in Morton order, so an aligned 2³ block is one byte of a word, and an aligned 4³ block is two whole words. Asking "is this block empty?" is a mask, not a loop. So classify always returns the largest empty aligned block it can see: an empty octant of the tree, a raster chunk, an empty brick, a 4³, a 2³, or a single cell. That took the sparse far view from about 450 texture reads a ray to about 124 (ray-findings.md). The tracer also remembers its current page, skipping the walk from the root while it stays inside.

// the march, ray-glsl.js's traceRay and ray-core.js's traceCPU, line for line
while (inside the world && t < tEnd) {
  size = classify(cell);              // 0: occupied, a hit. Otherwise the side of an empty aligned block.
  if (size == 0) return hit(t, cell, axis);
  lo   = cell - cell % size;          // that block's corner
  t    = exit of the box [lo, lo + size];
  cell = the integer cell across that face;   // carried, never re-derived from the rounded point
}

Why the cell is carried. Re-deriving a cell from floor(o + t·d) looks equivalent, but after rounding the point can land back in the block it just left, and the ray stalls until its budget runs out. At radix 4 that would have truncated 34% of rays at L = 7 (tracer-cell-carry.md). Colour: a brick is shared, but a cell being shown depends on its neighbours, so a word can't live in the brick. A page has its own run per brick: the shown mask, then one word per shown cell. A hit finds its word by rank, a popcount of the mask below it, in SWAR because GLSL ES 3.00 has no bitCount.

09

The path: raster or ray, chunk by chunk

Opt-in since 2026-11-09. The viewer draws raster only unless the link says ?ray=density: by density measured at or near the best on the benches below, but raster only felt snappier, faster to follow the mouse (lodacne.md, the decisions). This section's demos start raster only too; pick "by density" to see the rule work. The cost model predates three faces a cube (§5): it was fitted to a raster pass that sent 36 indices a cube, which now costs about half as much, so the line below traces more than a refit would. Neither the benches nor the fit have been redone since (path-occupancy.md).

Neither path wins everywhere, so each chunk is priced. Raster costs cubes · c_cube. A ray costs footprint · c_px, the pixels its box covers on screen, and a ray stops sooner in a fuller chunk. Dividing gives one number and one line. A chunk is traced when its cubes per footprint pixel exceed a threshold that falls as the chunk fills, from 0.27 when empty to 0.025 when full, fitted to the real-GPU benches. Both inputs come from the job's own report: recordCount and occupied. That's why a chunk has to be built once before it can be priced. Until then it takes its parent's kind.

The same chunks on screen, warm: raster, cool: traced
the lab draws where you're looking
Table view: the chart's chunks
chunkcubesfootprint pxcubes / pxoccupancythresholdwantsis

The dashed lines are the hysteresis: a chunk resident as records turns into a page only above threshold × 1.5, and a page back into records only below threshold ÷ 1.5, because each flip is a job. As you move a threshold, watch the points change sides, and watch the view keep drawing. A chunk in the wrong kind is drawn until its replacement lands, and nothing flushes. The rule is computed for your whole window's size, as the viewer would, not for this small canvas.

What it does on a real GPU (Safari, Apple GPU, wall clock, ms a frame, from the repo's benches)

viewraster onlyby densityray onlytraced by densitysource
seed row, from inside1.351.3510.20 of 428ray-depth-findings.md
terrain, low (2560×1357)1.741.5316.7582, on 0% of pixelsstencil-pass.md §8
scatter, D = 122.982.8614.3767, on 1%stencil-pass.md §7
caves, D = 12, start chamber1.961.707.55queries take it to 1.44occlusion.md §7
graph row (dense, porous)3.551.21 †0.86428 of 532 †ray-depth-findings.md
kit D = 16, street12.7812.1311.43ray ≥ lod 3 is 11.26occlusion.md §8

† Benched under the first, constant rule (0.2). The occupancy rule traces all 532 chunks there, which is the ray-only row at most (path-occupancy.md). Bench canvases differ, so compare across a row, not down a column.

Read across the rows: ray only is 11× worse than the rule on a terrain and 4× better than raster on a graph row, and the rule lands at or near the best on each. One rayLod couldn't do that, since a seed row and a graph row both put every leaf at lod 3 or above. The first version of the rule was a constant, and it needed the occupancy term to separate a 97%-full chunk (0.11 ns per footprint pixel) from a 1.6% one (0.91 ns), which looked identical on screen as cubes per pixel (path-occupancy.md). And the rule is written three times, in stream-core.js, the test's expectedKinds and the page's invariants(), on purpose.

10

A frame, pass by pass

Everything above produces a draw list, and turns it into pixels. This lab really runs those passes, on the world chosen at the top, and each tab shows what's in the framebuffer after a stage. The rule that makes the two paths compose: the cover is a partition, so they never draw the same voxel, and the raster goes first so its depth can bound the rays.

the lab draws where you're looking
  1. Raster, into an offscreen target. Near chunks first, so the depth test rejects as much as it can. A frustum test drops whole chunks. Traced chunks are skipped here, and read as empty space to it. Three faces a cube (§5), 18 indices. Then, in the viewer, the occlusion queries, then actors (?actors=N, one draw a body), after the queries so a flier can't hide a chunk from them and before the ray pass so a ray stops at a flier as at any raster surface. With no actors it's the frame it always was, call for call. The near plane is half the clearance, or half the way to the nearest actor if that's nearer.
  2. Read the depth as a texture. The depth attachment is a texture, so the next stages can sample it. That's why the canvas has no MSAA: a blit can't write into a multisampled framebuffer, and a resolved depth would put a dark fringe around raster silhouettes.
  3. Mark the traced chunks in a stencil. Each traced chunk's box, grown by one cell, is drawn with no culling. Its fragment shader finds where the pixel's ray enters the box and discards if the raster's surface comes first.
  4. The ray pass, on marked pixels only. One full-screen triangle, stencil-tested. Each ray marches from the near plane to the raster's surface, so a hit is always nearer than the raster: a hit simply overwrites, with no depth test and no gl_FragDepth.
  5. Blit to the canvas. The colour renderbuffer holds both paths by now.

That is renderView, and every test that compares frames byte for byte compares what it made. The viewer's draw() then runs passes that read the frame but never change it, so they can't break a comparison: SSAO (Y, off by default: GTAO on the raster's depth, normals rebuilt from it; vdagssao.md), the wireframe (T: the same vertices as lines, 30 a cube, with a triangle count), and in edit mode the preview of a world being placed, solid in front of the raster's depth and faint behind, and the outline or the placement box's handles. None of them is in this lab.

T.fb: the raster pass draws here

COLOR0: a renderbuffer, shared DEPTH: a texture, DEPTH_COMPONENT24

T.rayFb: the marking and ray passes draw here

COLOR0: the same renderbuffer STENCIL: its own renderbuffer. No depth at all.

Why two framebuffers. WebGL2 wants depth and stencil in one image when both are attached, and that image would be the depth texture the ray pass samples. Sampling a texture attached to the framebuffer being drawn is a feedback loop, an INVALID_OPERATION whatever the depth mask says. So the ray framebuffer has no depth, and the hand-written depth test in the box shader takes its place (stencil-pass.md §1).

Three traps that cost real milliseconds

Occlusion: skipping what's behind a wall

After the raster pass, each raster chunk's box, grown by a cell, is drawn inside an occlusion query, depth-tested with every write off. If no sample passes, later frames skip its cubes and keep asking. It doesn't change a frame at rest: occlusion.test.js holds the frame to the one drawn without, byte for byte. A cube inside the grown box is at least a cell behind the box's front faces, so wherever the cube would win the depth test, the box would have passed first. The price is a late answer: a query can't return before the page goes back to the event loop, so a chunk revealed by a move can be missing for a frame or two. In the caves' start chamber it skips 93% of the cubes at D = 10, and takes the frame from 2.63 to 1.57 ms at D = 12. On an open view it's pure cost, so the caves, the kit, the dungeon (where it cut the frame to a quarter) and the city default to it, and nothing else. The decisions are in .

11

Many worlds: one cut over a forest

A universe (2026-11-19, universe-plan.md, universe-log.md) is worlds drawn as instances, never baked into one DAG. An instance is { world, at, turn, scale }: the world's cube corner in whole universe voxels, one of the 48 turns of the cube, and 2scale universe voxels a world voxel. Those three keep every box a box in both frames, so the cut, collision and occlusion stay exact, with nothing approximated. The viewer's universe:<seed> lays nine tiles on a plane, and endless:<seed> an endless lattice of 512-voxel cells, built as you go. Every section above still holds inside each world. What's new is the cut, the cache key and the draw.

// selectForest, without the bookkeeping: each instance's top chunk is a tree, and every tree's chunks go in ONE heap.
for (inst of universe.instances) push(topChunk(inst), dist from toLocal(inst.frame, eye));   // the eye, in that world's own voxels
while (heap.length){ c = pop();                                    // the smallest dist / size, whichever world it's in
  if (splitsAt(c, cfg) && count + kids <= maxChunks) push(...kids); else leaf(c); }

Nothing new is needed for the lods to be right, because dist / size is the same number in either frame: a scale multiplies both, and a turn moves neither. So a near chunk of a small world and a far chunk of a big one are compared as they look, worlds of different depths and scales each get the right lod, and one maxChunks is spent where it shows most across the whole universe. Each tree is exactly what selectChunks would cut for its instance alone, which test/stream-core.test.js holds key for key.

Built on this page with the real buildKit, createUniverse and selectForest: six instances of three kits. A D = 10 kit three times (as it is, turned a quarter about y, mirrored), once more at ×2, another D = 10 kit, and a D = 12 kit at ¼, so the same size on the plane. From above, at the eye's height: each instance's leaves that cross that plane, in the universe, by lod. Drag anywhere to move the eye. Hover a chunk to outline every copy of it.

The cache holds world chunks, not instance chunks. The streamer keys an entry world/lod:x,y,z (forestKey), so copies of a world that want the same chunk want it once, one job builds it, and coverForest lists it once an instance to draw, all from one entry. A world chunk two trees want takes the nearer one's distance, so it's built in its turn. The pool posts each world's snapshot to the workers once, under its key, and a job names its world (setUniverse).

// rasterVS(…, turned): a universe's raster program. The records stay in their world's frame.
uOrigin = chunk corner − toLocal(frame, eye);     // in the world's own voxels, so §5's face choice is made where it's right
vec3 q = uTurn * p;                                // turnMatrix: the turn, times 2^scale, eye-relative world to eye-relative universe
vNormal = uTurn * NORMAL[face] / uScale;
gl.frontFace(mirrored ? gl.CW : gl.CCW);          // a mirror reverses every face's winding, so CULL_FACE needs the other order

The draw is a turned twin of the raster program, set once an instance: placeChunk puts each drawn chunk's box in the universe for culling, sorting and occlusion (keyed instance and chunk), and instanceUniforms sets the turn, the scale, the mirror's winding, the world's gamut and a tint for the far view. A plain world keeps the plain program, so its frames don't change: universeSelftest() holds one identity instance through the turned program to the plain frame, byte for byte, and turned and mirrored instances to the same worlds baked into one DAG.

The endless lattice moves without a flush. setUniverse(u, { keep: true }) swaps one window of cells for the next: a world under the same key, store, root and depth keeps its entries, jobs and results, and any other world's are dropped at once. The coordinates roll with the eye (shiftOrigin, by whole voxels), so float32 stays fine however far you fly. A universe has no ray path, no edits and no export yet, and the viewer says why when you ask for one.

12

Reading order for the code

With the map in your head, read the code in this order. It skips a lot on purpose: stream-viewer.html is nearly 10,000 lines, and most of them are worlds, controls, tests and benches. Line numbers below are looked up from the files as this page loads, so they stay right. Click one to copy it, and paste it into your editor's quick-open.

#readwherefor
1the viewer's framethe loop at the top of this page, in the original, and draw() below it
2chunk addressesheader comment just above it: lod, level, chunk (§2)
3selectChunksthe cut and splitsAt; the proof of the one-lod rule is in the comment above it (§3)
4coverOfcomplete beats finer, and how open sides are found (§6, §7)
5chooseKindswith kindFor and the long comment above it (§9)
6recover, nextJob, servicejob order, admission, then installItem, in that order. Skip the edit branches at first (§7)
7StreamPool.dispatchhow little the threads do
8createJobRunnerwhat a worker runs: fastChunk, plus the buried shortcut (§4)
9expandChunkwalk, apron, masks, tail (§4): what a job makes, the plain way. Header comment first: the record
10fastChunkthe same bytes, faster; read job-core's header for the three changes (§4)
11GLSL_DECODEthe same record from the other side (§5)
12rasterVSthree faces a cube, and the comment above it (§5); turned is a universe's (§11)
13renderViewthe passes, in order (§10). Ignore occl, places and timed on a first read
14install / disposethe streamer's only two GL hooks
15ray-core's headerpage, brick, cover tree layouts (§8), then traceCPU, which is easier than the GLSL
16GLSL_RAYthe same march, line for line
17markTracedthe stencil (§10)
18selectForesta universe's cut, and coverForest below it (§11); universe-core's header for the frames
19frameCheckerevery promise the streamer makes, written as a check. It's the best summary of the rules

What's where, and which side of the line

fileruns onwhat it holds
dag-core.jsmainworkersthe world: store, counts, classes, storeView
stream-core.jsmainworkersevery streaming decision, pure. Its job runner is what the workers call
chunk-core.jsworkersexpandChunk: a node to records, the reference. The lod rules. Pure
job-core.jsworkersfastChunk: the same records, 4–12× faster without colour. Pure
universe-core.jsmaininstances, frames, the plane, the endless lattice's cells. Pure
ray-core.jsworkersmainpages in workers; brick pool, heap and cover tree on main; CPU twins for the tests
stream-pool.js + chunk-worker.jsmainworkersthreads and messages. No decisions
chunk-glsl.js, ray-glsl.jsGPUthe decode and the march, as strings every program prepends
occlusion-core.jsmainwhich chunks to skip and ask about. Pure. stream-core doesn't know about it
stream-viewer.htmlmainGPUthe shaders, the textures, the passes; then worlds, UI, tests and benches

What this page's lab leaves out

The docs for each part: stream-plan.md, stream-findings.md, ray-plan.md, ray-depth-findings.md, path-occupancy.md, stencil-pass.md, occlusion.md, edit-stream-log.md, job-speed-log.md, lodacne.md, city-frame-cost.md, lod-locked.md, universe-log.md. docs/README.md is the index.