// 24-hour day/night cycle: sun and moon paths and the one directional light
// that follows them, all driven by one slider value.
//
// Neither the sunset nor the sky is made here. The light is authored as it is
// above the air, one colour and one intensity all day; the renderer takes it
// through the scene's atmosphere on its way to a surface, so it dims and
// reddens toward the horizon and goes dark below it by its direction alone,
// and the same atmosphere draws the sky from it. What is left to author is
// the handover from sun to moon, as meep `AnimationCurve`s keyed on the sun's
// elevation in degrees rather than on clock time, so dusk and dawn share them
// whatever the time warp does to the sun's pace.
import { Color } from "@woosh/meep-engine/src/core/color/Color.js";
import Vector3 from "@woosh/meep-engine/src/core/geom/Vector3.js";
import { kelvin_to_rgb } from "@woosh/meep-engine/src/core/color/kelvin/kelvin_to_rgb.js";
import { smoothStep } from "@woosh/meep-engine/src/core/math/smoothStep.js";
import { AnimationCurve } from "@woosh/meep-engine/src/engine/animation/curve/AnimationCurve.js";
import { Keyframe } from "@woosh/meep-engine/src/engine/animation/curve/Keyframe.js";
export const DEFAULT_TIME_OF_DAY = 9.5;
// ─── Sun and moon paths ──────────────────────────────────────────────────────
const DEG = Math.PI / 180;
/** Observer latitude: sets the noon sun at 90° − 35° = 55° elevation. */
export const LATITUDE_DEG = 35;
/** Compass direction of the noon sun, in the azimuth convention of {@link directionFromAngles}. */
export const NOON_AZIMUTH_DEG = -30;
/** The moon runs nearly opposite the sun, on a slightly lower path. */
const MOON_DECLINATION_DEG = -8;
const MOON_HOUR_OFFSET = 12.4;
/**
* How strongly the clock is slowed around 06:00 and 18:00. At 0.6 the sun moves
* at 0.4× its normal pace across the horizon and 1.6× through noon and
* midnight, so sunrise and sunset take up about two and a half times their
* real share of the slider.
*/
export const TWILIGHT_STRETCH = 0.6;
/**
* Map slider hours to solar hours. Fixed points are 0, 6, 12, 18 and 24, and
* the mapping is monotonic and wraps cleanly at midnight.
*
* @param {number} hours 0..24
* @returns {number} 0..24
*/
export function solarHours(hours) {
return hours - (6 * TWILIGHT_STRETCH / Math.PI) * Math.sin(Math.PI * (hours - 6) / 6);
}
/**
* Unit vector toward an elevation/azimuth pair. Azimuth is measured from +Z
* toward +X.
*
* @param {number} elevationDeg
* @param {number} azimuthDeg
* @returns {number[]}
*/
export function directionFromAngles(elevationDeg, azimuthDeg) {
const el = elevationDeg * DEG;
const az = azimuthDeg * DEG;
const c = Math.cos(el);
return [c * Math.sin(az), Math.sin(el), c * Math.cos(az)];
}
const SOUTH = directionFromAngles(0, NOON_AZIMUTH_DEG);
const EAST = directionFromAngles(0, NOON_AZIMUTH_DEG - 90);
const WEST = [-EAST[0], -EAST[1], -EAST[2]];
const NORTH = [-SOUTH[0], -SOUTH[1], -SOUTH[2]];
/**
* Direction toward a body on the celestial sphere: hour angle 0 is the meridian
* (solar noon for the sun), positive hour angles are west.
*
* @param {number} hourAngleHours
* @param {number} declinationDeg
* @returns {number[]}
*/
export function celestialDirection(hourAngleHours, declinationDeg) {
const phi = LATITUDE_DEG * DEG;
const h = hourAngleHours * 15 * DEG;
const d = declinationDeg * DEG;
const cd = Math.cos(d);
const sd = Math.sin(d);
// Equator crosses the meridian at elevation 90° − latitude, due south;
// the celestial pole sits at elevation = latitude, due north.
const m = [
SOUTH[0] * Math.sin(phi),
Math.cos(phi),
SOUTH[2] * Math.sin(phi),
];
const p = [
NORTH[0] * Math.cos(phi),
Math.sin(phi),
NORTH[2] * Math.cos(phi),
];
const a = cd * Math.cos(h);
const b = cd * Math.sin(h);
return [
a * m[0] + b * WEST[0] + sd * p[0],
a * m[1] + b * WEST[1] + sd * p[1],
a * m[2] + b * WEST[2] + sd * p[2],
];
}
// ─── Animation curves, keyed on sun elevation (degrees) ─────────────────────
/**
* Build an `AnimationCurve` through `[time, value]` points with smooth,
* non-overshooting tangents: the Catmull-Rom slope, flattened at local extrema
* so colours never ring below zero.
*
* @param {number[][]} points
* @returns {AnimationCurve}
*/
export function smoothCurve(points) {
const curve = AnimationCurve.from(points.map(([t, v]) => Keyframe.from(t, v)));
const keys = curve.keys;
for (let i = 0; i < keys.length; i++) {
let slope = 0;
if (i > 0 && i < keys.length - 1) {
const prev = keys[i - 1];
const next = keys[i + 1];
const s0 = (keys[i].value - prev.value) / (keys[i].time - prev.time);
const s1 = (next.value - keys[i].value) / (next.time - keys[i].time);
if (s0 * s1 > 0) {
slope = (next.value - prev.value) / (next.time - prev.time);
// keep the Hermite segment monotone
const limit = 3 * Math.min(Math.abs(s0), Math.abs(s1));
slope = Math.sign(slope) * Math.min(Math.abs(slope), limit);
}
}
keys[i].inTangent = slope;
keys[i].outTangent = slope;
}
return curve;
}
/**
* The sun above the air, in kelvin: about 5500 K once the noon atmosphere has taken its blue.
*/
export const SUN_TEMPERATURE = 7100;
/** The sun's colour above the air, the same all day. */
export const SUN_COLOR = [0, 0, 0];
kelvin_to_rgb(SUN_COLOR, 0, SUN_TEMPERATURE);
/** The sun's intensity above the air, the same all day. */
export const SUN_INTENSITY = 3.6;
/**
* How much of the sun is left as it sinks below the horizon. The ground is already dark there and
* what this fades is the twilight sky, out by the time the light is handed to the moon.
*/
export const SUN_TWILIGHT = smoothCurve([
[-5, 0],
[-2.5, 1],
]);
/** Moonlight fades in only once the sky has gone properly dark. */
export const MOON_INTENSITY = smoothCurve([
[-18, 0.45],
[-10, 0.18],
[-6, 0],
]);
/** The light swaps from moon to sun here, where both are at zero. */
const LIGHT_SWAP_ELEVATION = -5;
/** Cold, slightly desaturated blue: night must read as night at a glance. */
export const MOON_COLOR = [0.5, 0.68, 1.0];
/** Angular radius of the moon's disc, drawn as emissive geometry in main.js. */
export const MOON_ANGULAR_RADIUS_DEG = 1.2;
/** Linear emissive radiance of the moon's disc at full visibility. */
export const MOON_DISC_RADIANCE = [0.9, 1.02, 1.2];
/** How much daylight is in the sky: the moon's disc shows as it goes. */
const DAY_SKY_WEIGHT = smoothCurve([
[-5, 0],
[4, 1],
]);
// ─── Time-of-day evaluation ─────────────────────────────────────────────────
/**
* Everything the scene needs for one slider position.
*
* @param {number} hours 0..24
*/
export function evaluateTimeOfDay(hours) {
const solar = solarHours(hours);
const toSun = celestialDirection(solar - 12, 0);
const toMoon = celestialDirection(solar - 12 - MOON_HOUR_OFFSET, MOON_DECLINATION_DEG);
const sunElevationDeg = Math.asin(toSun[1]) / DEG;
const moonElevationDeg = Math.asin(toMoon[1]) / DEG;
// the moon shows once the daylight has gone, and sinks below the horizon
const moonVisibility = (1 - DAY_SKY_WEIGHT.evaluate(sunElevationDeg))
* smoothStep(-2, 4, moonElevationDeg);
const isMoon = sunElevationDeg < LIGHT_SWAP_ELEVATION;
const lightTo = isMoon ? toMoon : toSun;
const rgb = isMoon ? MOON_COLOR : SUN_COLOR;
const intensity = isMoon
? MOON_INTENSITY.evaluate(sunElevationDeg) * smoothStep(0, 10, moonElevationDeg)
: SUN_INTENSITY * SUN_TWILIGHT.evaluate(sunElevationDeg);
return {
hours,
solarHours: solar,
toSun,
toMoon,
sunElevationDeg,
moonElevationDeg,
/** 0..1: how strongly the moon's disc shows. */
moonVisibility,
isMoon,
/** Direction the light travels (away from the sun or moon). */
lightDirection: new Vector3(-lightTo[0], -lightTo[1], -lightTo[2]).normalize(),
color: new Color(rgb[0], rgb[1], rgb[2]),
/** The light above the air; the renderer dims it through the atmosphere. */
intensity,
};
}
/**
* Format numeric hours (e.g. `9.5`) as a 24-hour `HH:MM` label (`"09:30"`).
*
* @param {number} hours
* @returns {string}
*/
export function formatTimeOfDay(hours) {
const totalMinutes = Math.round(hours * 60) % (24 * 60);
const hh = Math.floor(totalMinutes / 60);
const mm = totalMinutes % 60;
return `${String(hh).padStart(2, "0")}:${String(mm).padStart(2, "0")}`;
}
// Probe Clipmap Global Illumination — a Meep example.
//
// Demonstrates `ShadeIndirectLightingMode.ProbeClipmap` on "Flying world -
// Battle of the Trash god" by burunduk (CC-BY-4.0): a multi-tiered floating
// island with deep overhangs, archways, caverns, a giant skull, and 38 local
// torches, lanterns, and a staff jewel.
//
// How ProbeClipmap works:
//
// 1. Geometry SDF & Surface Caches (`GPUGeometrySDFManager`, `GPUMeshSurfaceCaches`):
// Every mesh with `ShadedGeometryFlags.SDFWorld` (and a non-transparent
// material) has an object-space signed distance field baked into 7³-voxel
// sparse bricks, plus a Model Surface Cache per (geometry, material) pair
// holding block-coded albedo, metalness/roughness and emissive wherever the
// material makes them vary.
//
// 2. World-Space Brick Clipmap (`GPUBrickClipmap`, `GPUBrickMaterial`):
// Each frame, object-space mesh SDFs are composited into a 6-cascade
// camera-centered 32³ world-space SDF brick clipmap (voxel size 0.125 m at
// cascade 0, doubling per cascade), and each built brick gathers its surface
// material from the surface caches. Direct sunlight, CSM/SDF
// shadows, and up to 64 local point/spot lights (`shader_probe_clipmap_light`)
// plus multi-bounce irradiance from the previous frame's probes are shaded
// along probe ray hits.
//
// 3. Octahedral Probe Clipmap (`GPUProbeClipmapGI`):
// A 5-cascade 32×32×32 grid of probes (1.0 m spacing at cascade 0, doubling
// per cascade) relocates probes out of solid geometry using the SDF gradient,
// traces 256 sphere-marched rays per probe update through the brick clipmap,
// blends hit radiance or the sky (the scene's atmosphere) temporally
// into a 16×16 octahedral radiance + 8×8 Chebyshev depth-moment atlas, and
// optionally re-samples its neighbours' histories.
//
// Nothing is converted or baked while the page loads. The scene arrives in meep's binary scene
// format (meshlets and their BVHs, materials, lights) and the mesh SDFs and surface caches of step 1
// arrive as a `ModelCacheBundle`; `tools/bake_scene.mjs` writes both from the glTF.
import Vector3 from "@woosh/meep-engine/src/core/geom/Vector3.js";
import { BinaryBuffer } from "@woosh/meep-engine/src/core/binary/BinaryBuffer.js";
import Entity from "@woosh/meep-engine/src/engine/ecs/Entity.js";
import { EntityComponentDataset } from "@woosh/meep-engine/src/engine/ecs/EntityComponentDataset.js";
import { Transform64 } from "@woosh/meep-engine/src/engine/ecs/transform/Transform64.js";
import { t64_announce_change } from "@woosh/meep-engine/src/engine/ecs/transform/t64_announce_change.js";
import { t64_look_rotation } from "@woosh/meep-engine/src/engine/ecs/transform/t64_look_rotation.js";
import { EngineHarness } from "@woosh/meep-engine/src/engine/EngineHarness.js";
import TopDownCameraController from "@woosh/meep-engine/src/engine/graphics/ecs/camera/topdown/TopDownCameraController.js";
import { Light } from "@woosh/meep-engine/src/engine/graphics/ecs/light/Light.js";
import { LightType } from "@woosh/meep-engine/src/engine/graphics/ecs/light/LightType.js";
import { ShadedGeometry } from "@woosh/meep-engine/src/engine/graphics/ecs/mesh-v2/ShadedGeometry.js";
import { ShadedGeometryFlags } from "@woosh/meep-engine/src/engine/graphics/ecs/mesh-v2/ShadedGeometryFlags.js";
import { meshlet_geometry_build_from_geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/meshlet_geometry_build_from_geometry.js";
import { make_octahedron_geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/primitives/make_octahedron_geometry.js";
import { StandardShadeMaterial } from "@woosh/meep-engine/src/shade/renderer/material/StandardShadeMaterial.js";
import { TransparencyMode } from "@woosh/meep-engine/src/shade/renderer/material/TransparencyMode.js";
import { Scene } from "@woosh/meep-engine/src/shade/renderer/scene/Scene.js";
import { deserialize_scene } from "@woosh/meep-engine/src/shade/renderer/scene/serialization/deserialize_scene.js";
import { ShadeIndirectLightingMode } from "@woosh/meep-engine/src/shade/renderer/ShadeIndirectLightingMode.js";
import { CAMERA_PRESETS } from "./probeClipmapSetup.js";
import {
DEFAULT_TIME_OF_DAY,
evaluateTimeOfDay,
formatTimeOfDay,
MOON_ANGULAR_RADIUS_DEG,
MOON_DISC_RADIANCE,
} from "./dayCycle.js";
import { uploadModelCaches } from "./modelCaches.js";
import { fetchGzip, MODEL_CACHE_URL, SCENE_URL } from "./sceneFiles.js";
import {
bootEngine,
buildView,
CAMERA_FAR,
configureProbeClipmap,
enterSDFWorld,
placeScene,
} from "./sceneSetup.js";
const CAMERA_ZOOM_MAX = 95;
/** How much harder the light lights the atmosphere than the ground (`sun_irradiance_scale`). */
const SKY_GAIN = 3;
/** The moon is real geometry this far from the camera; the projection is infinite. */
const MOON_DISTANCE = 10_000;
const loadingEl = document.getElementById("loading");
const loadingStatusEl = document.getElementById("loading-status");
const loadingProgressEl = document.getElementById("loading-progress");
const loadingProgressFillEl = document.getElementById("loading-progress-fill");
function setLoadingProgress(fraction, statusText) {
const pct = Math.max(0, Math.min(100, Math.round(fraction * 100)));
if (loadingProgressFillEl) {
loadingProgressFillEl.style.width = `${pct}%`;
}
if (loadingProgressEl) {
loadingProgressEl.setAttribute("aria-valuenow", String(pct));
}
if (statusText && loadingStatusEl) {
loadingStatusEl.textContent = statusText;
}
}
// ─── §1 Engine bootstrap ───────────────────────────────────────────────────
// Both files start downloading before the engine does anything, so the download overlaps WebGPU
// start-up and shader compilation.
const downloads = [0, 0];
const totals = [0, 0];
function download(slot, url) {
return fetchGzip(url, (loaded, total) => {
downloads[slot] = loaded;
totals[slot] = total;
const all = totals[0] + totals[1];
if (all > 0) {
setLoadingProgress(0.04 + 0.76 * (downloads[0] + downloads[1]) / all);
}
});
}
const sceneFile = download(0, SCENE_URL);
// Without the model caches the page still works: it bakes them, as it would for any scene.
const modelCacheFile = download(1, MODEL_CACHE_URL).catch((error) => {
console.warn("No baked model caches, baking them instead:", error);
return null;
});
setLoadingProgress(0.04, "Loading Flying World…");
const engine = await bootEngine();
const initialSun = evaluateTimeOfDay(DEFAULT_TIME_OF_DAY);
await buildView(engine);
const ecd = engine.entityManager.dataset;
const cameraController = ecd.getAnyComponent(TopDownCameraController).component;
cameraController.distanceMin = 1.5;
cameraController.distanceMax = CAMERA_ZOOM_MAX;
await EngineHarness.buildLights({
engine,
castShadow: true,
sunShadowDistance: 160,
sun: initialSun.color,
sunIntensity: initialSun.intensity,
sunDirection: initialSun.lightDirection,
});
// Find the directional light created by `buildLights`. The Time of Day slider
// steers it along the sun's arc by day and the moon's by night, with colour
// and intensity from the curves in dayCycle.js.
let sunLight = null;
let sunTransform = null;
let sunEntity = -1;
ecd.traverseEntities([Light, Transform64], (light, transform, entity) => {
if (light.type.getValue() === LightType.DIRECTION) {
sunLight = light;
sunTransform = transform;
sunEntity = entity;
}
});
// No environment map is set: the scene's atmosphere draws the sky from this
// one light, by day and by night, and the same sky is the image-based lighting
// and what a probe ray that misses reads. It follows the light as the slider
// moves it, with nothing to rebuild here. The renderer takes the same light
// through that atmosphere on its way to the ground, which is the whole of the
// sunset: dayCycle.js only turns the light. The one thing set here is how hard
// the light lights the air next to how hard it lights the ground, a constant:
// at this fixed exposure it is what fills the shadows.
const atmosphere = EngineHarness.shadeScene(engine).atmosphere;
atmosphere.enabled = true;
atmosphere.sun_irradiance_scale = SKY_GAIN;
// The moon's disc is an emissive sphere rather than texels of the sky map, so
// it stays round and crisp at any zoom. It rides along with the camera, so it
// stays where the moonlight comes from.
//
// The material is Transparent because the moon sits right on the moonlight's
// axis: shadow maps only draw opaque and alpha-tested casters, so an opaque
// moon would shadow the whole island. Being transparent also keeps it out of
// the SDF world, so GI rays neither hit it nor gather light off it, and lets it
// fade into the dawn sky through its opacity.
const moonMaterial = new StandardShadeMaterial();
moonMaterial.diffuse_color.setRGB(0, 0, 0);
moonMaterial.transparency_mode = TransparencyMode.Transparent;
const moonGeometry = ShadedGeometry.from(
meshlet_geometry_build_from_geometry(
make_octahedron_geometry(MOON_DISTANCE * Math.tan(MOON_ANGULAR_RADIUS_DEG * Math.PI / 180), 12),
),
moonMaterial,
);
moonGeometry.clearFlag(ShadedGeometryFlags.SDFWorld);
const moonTransform = new Transform64();
const moonEntity = new Entity().add(moonTransform).build(ecd);
const moonDirection = new Vector3();
let moonShown = false;
let moonVisibility = -1;
function setMoon(state) {
moonDirection.set(state.toMoon[0], state.toMoon[1], state.toMoon[2]);
const v = state.moonVisibility;
// by 0.1 the disc has already faded into the dawn sky
const show = v > 0.1;
if (show && v !== moonVisibility) {
moonVisibility = v;
// fade both: opacity lets the sky through, and the emissive goes to zero
moonMaterial.diffuse_color.a = v;
moonMaterial.emissive_factor.setRGB(
MOON_DISC_RADIANCE[0] * v,
MOON_DISC_RADIANCE[1] * v,
MOON_DISC_RADIANCE[2] * v,
);
moonMaterial.needsUpdate = true;
}
if (show !== moonShown) {
moonShown = show;
if (show) {
ecd.addComponentToEntity(moonEntity, moonGeometry);
} else {
ecd.removeComponentFromEntity(moonEntity, ShadedGeometry);
}
}
}
setMoon(initialSun);
engine.graphics.on.preRender.add(() => {
if (!moonShown) return;
const eye = engine.graphics.camera.camera.transform;
moonTransform.setTranslation(
eye.translation_x + moonDirection.x * MOON_DISTANCE,
eye.translation_y + moonDirection.y * MOON_DISTANCE,
eye.translation_z + moonDirection.z * MOON_DISTANCE,
);
moonTransform.updateMatrix();
t64_announce_change(ecd, moonEntity);
});
// ─── §2 Configure ShadeIndirectLightingMode.ProbeClipmap ───────────────────
const renderer = engine.graphics.renderer;
configureProbeClipmap(renderer);
// ─── §3 Load Flying World ──────────────────────────────────────────────────
//
// `deserialize_scene` hands back the meshes as a bundle to place, and puts the file's lights into
// the scene it is given. That scene is a stand-in here: the lights are read out of it and spawned
// as entities below, so the engine's own light system owns them.
const fileScene = new Scene();
fileScene.dataset = new EntityComponentDataset();
const bundle = await deserialize_scene(BinaryBuffer.fromArrayBuffer(await sceneFile), fileScene);
const placed = placeScene(ecd, bundle);
const { prefab, instance } = placed;
setLoadingProgress(0.85, "Preparing global illumination…");
// ─── §4 Spawn the scene's 38 point lights ──────────────────────────────────
//
// `shader_probe_clipmap_light` evaluates up to `MAX_LOCAL_LIGHTS = 64` local
// lights at every probe ray hit each frame, so torches, lanterns, and the
// glowing staff contribute warm multi-bounce indirect light into nearby
// probes as well as direct illumination.
const pointLightEntries = [];
for (const source of fileScene.lights.elements) {
if (source.isPointLight !== true) continue;
const light = new Light();
light.type.set(LightType.POINT);
light.color.copy(source.color);
light.intensity.set(source.intensity);
light.distance.set(source.distance);
light.radius.set(source.radius);
light.castShadow.set(false);
const transform = new Transform64();
transform.copy(source.transform);
const entity = new Entity().add(transform).add(light).build(ecd);
pointLightEntries.push({ entity, light, baseIntensity: source.intensity });
}
// ─── §5 Interactive UI controls ────────────────────────────────────────────
const giButtons = document.querySelectorAll("[data-gi-mode]");
function setGIMode(modeKey) {
const isProbeClipmap = modeKey === "probe-clipmap";
renderer.indirect_lighting_mode = isProbeClipmap
? ShadeIndirectLightingMode.ProbeClipmap
: ShadeIndirectLightingMode.IBL;
// GTAO is off in Image-based mode for a fairer comparison: it adds
// occlusion that IBL itself doesn't have, and its bent normals correct the
// environment sampling, which would skew the perception further.
renderer.feature_ssao_enabled = isProbeClipmap;
for (const btn of giButtons) {
btn.classList.toggle("active", btn.dataset.giMode === modeKey);
}
}
for (const btn of giButtons) {
btn.addEventListener("click", () => setGIMode(btn.dataset.giMode));
}
const localLightsEl = document.getElementById("local-lights");
localLightsEl?.addEventListener("change", () => {
const enabled = localLightsEl.checked;
for (const item of pointLightEntries) {
item.light.intensity.set(enabled ? item.baseIntensity : 0);
}
});
const timeOfDayEl = document.getElementById("time-of-day");
const timeOfDayValEl = document.getElementById("time-of-day-val");
function applyTimeOfDay(hours) {
const state = evaluateTimeOfDay(hours);
if (timeOfDayValEl) {
timeOfDayValEl.textContent = formatTimeOfDay(hours);
}
if (sunTransform !== null && sunEntity !== -1) {
t64_look_rotation(
sunTransform,
state.lightDirection.x,
state.lightDirection.y,
state.lightDirection.z,
Vector3.up.x,
Vector3.up.y,
Vector3.up.z,
);
sunTransform.updateMatrix();
t64_announce_change(ecd, sunEntity);
}
if (sunLight !== null) {
sunLight.color.copy(state.color);
sunLight.intensity.set(state.intensity);
}
setMoon(state);
}
timeOfDayEl?.addEventListener("input", () => {
applyTimeOfDay(Number(timeOfDayEl.value));
});
// Once the scene's rows have reached the GPU, hand the baked model caches to the SDF manager and
// only then let the meshes into the SDF world. The fields are resident two frames later, with
// nothing baked. Whatever the file did not cover is baked behind the progress bar instead.
const modelCaches = await modelCacheFile;
let sdfQueued = false;
let sdfReady = false;
engine.graphics.on.postRender.add(() => {
const context = engine.graphics.scene_context(EngineHarness.shadeScene(engine));
if (context === null) return;
if (!sdfQueued && context.rows.mesh_rows_version > 0) {
sdfQueued = true;
if (modelCaches !== null) {
const { taken, fields } = uploadModelCaches(context, prefab, modelCaches);
if (taken < fields) {
console.warn(`Baked model caches cover ${taken} of ${fields} mesh SDFs; baking the rest.`);
}
}
enterSDFWorld(ecd, placed);
return;
}
if (sdfQueued && !sdfReady) {
const sdf = context.geometries.sdf;
const resident = sdf.resident_count;
const pending = sdf.baking_count + sdf.queued_count;
const total = resident + pending;
if (total === 0) return;
if (pending === 0) {
sdfReady = true;
setLoadingProgress(1, "Ready");
loadingEl?.classList.add("hidden");
performance.mark("probe-clipmap-ready");
return;
}
setLoadingProgress(
0.85 + 0.15 * resident / total,
`Preparing global illumination (${Math.round(100 * resident / total)}%)…`,
);
}
});
window.__probeClipmap = {
engine,
ecd,
renderer,
instance,
pointLightEntries,
cameraController,
CAMERA_PRESETS,
setGIMode,
applyTimeOfDay,
moonEntity,
// what the SDF manager has, and how much of it this page had to bake itself
sdfStats() {
const sdf = engine.graphics.scene_context(EngineHarness.shadeScene(engine)).geometries.sdf;
return {
fields: sdf.resident_count,
fieldBricksBaked: sdf.bricks_evaluated,
surfaceCaches: sdf.surfaces.resident_count,
surfaceBricksBaked: sdf.surfaces.bricks_baked,
};
},
};
// Mesh SDFs and surface caches as a file: taken out of a scene that has baked them, and put into
// one that has not.
//
// The probe clipmap traces a world-space SDF that is composited each frame from one signed distance
// field per mesh, and shades its hits from one surface cache per (mesh, material) pair. Both are
// baked on the GPU from the mesh's triangles the first time a mesh joins the SDF world. A
// `ModelCacheBundle` holds the results of those bakes, so a page that uploads one skips them.
//
// What is not in the file, and cannot be: the world-space brick clipmap and the probes themselves.
// They follow the camera and the lighting, and are rebuilt continuously from these caches.
import { model_cache_bundle_read } from "@woosh/meep-engine/src/shade/renderer/geometry/sdf/bundle/model_cache_bundle_read.js";
import { model_cache_bundle_write } from "@woosh/meep-engine/src/shade/renderer/geometry/sdf/bundle/model_cache_bundle_write.js";
import { MeshSDFState } from "@woosh/meep-engine/src/shade/renderer/geometry/sdf/MESH_SDF.js";
import { MESH_SDF_MAX_BRICKS, MESH_SDF_VOXEL_SIZE_CM } from "./probeClipmapSetup.js";
import { packModelCaches, sdfTargets, unpackModelCaches } from "./sceneFiles.js";
/**
* Hand a baked model cache file to the scene's SDF manager, in place of baking.
*
* Call it once the scene's rows have reached the GPU (the geometries have records by then) and
* before any of them is flagged `SDFWorld`: a field is taken only by a geometry with no bake under
* way. A field or cache the manager does not take is simply baked as it would have been.
*
* @param {import("@woosh/meep-engine/src/shade/renderer/scene/GPUSceneContext.js").GPUSceneContext} context
* @param {import("@woosh/meep-engine/src/engine/graphics3/prefab/Prefab.js").Prefab} prefab
* @param {ArrayBuffer} file
* @returns {{taken: number, fields: number}} how many of the file's fields the manager took
*/
export function uploadModelCaches(context, prefab, file) {
const { fields, caches, bundle: bytes } = unpackModelCaches(file);
const bundle = model_cache_bundle_read(bytes);
const { geometries, materials } = sdfTargets(prefab);
const sdf = context.geometries.sdf;
// the bundle is only good at the voxel size and brick cap it was baked at
sdf.configure(MESH_SDF_VOXEL_SIZE_CM, MESH_SDF_MAX_BRICKS);
if (bundle.voxel_size !== Math.fround(sdf.voxel_size) || bundle.max_bricks !== sdf.max_bricks) {
return { taken: 0, fields: fields.length };
}
const records = Array.from(fields, (index) => {
const geometry = geometries[index];
return (geometry !== undefined && context.geometries.get_metadata(geometry)) || null;
});
const cacheMaterials = Array.from(caches, (index) => materials[index] ?? null);
// one scene's bundle, loaded alone: its bricks are already kept once each
const taken = sdf.upload_bundle(bundle, records, cacheMaterials, false);
return { taken, fields: fields.length };
}
/**
* The scene's resident mesh SDFs and surface caches as a model cache file. Call it when nothing is
* baking any more.
*
* @param {import("@woosh/meep-engine/src/shade/renderer/scene/GPUSceneContext.js").GPUSceneContext} context
* @param {import("@woosh/meep-engine/src/engine/graphics3/prefab/Prefab.js").Prefab} prefab
* @returns {Promise<{file: Uint8Array, fields: number, caches: number, bricks: number}>}
*/
export async function exportModelCaches(context, prefab) {
const { geometryIndex, materialIndex, included } = sdfTargets(prefab);
const sdf = context.geometries.sdf;
const surfaces = sdf.surfaces;
const records = [];
const fields = [];
const recordIds = new Set();
prefab.primitives.forEach((primitive, i) => {
if (!included[i]) return;
const record = context.geometries.get_metadata(primitive.geometry);
if (record === undefined || recordIds.has(record.index)) return;
if (sdf.state_of(record) !== MeshSDFState.Resident) return;
recordIds.add(record.index);
records.push(record);
fields.push(geometryIndex.get(primitive.geometry));
});
// cache ids are handed out from zero; nothing has been released, so they are dense
const cacheIds = [];
const caches = [];
for (let id = 0, seen = 0; seen < surfaces.count && id < 1 << 20; id++) {
const material = surfaces.material_of(id);
if (material === undefined) continue;
seen++;
if (!surfaces.is_resident(id) || !recordIds.has(surfaces.geometry_of(id))) continue;
const index = materialIndex.get(material);
if (index === undefined) continue;
cacheIds.push(id);
caches.push(index);
}
const bundle = await sdf.export_bundle(records, cacheIds);
return {
file: packModelCaches(fields, caches, model_cache_bundle_write(bundle)),
fields: fields.length,
caches: caches.length,
bricks: bundle.brick_count,
};
}
import { TransparencyMode } from "@woosh/meep-engine/src/shade/renderer/material/TransparencyMode.js";
// In `flying_world/scene.gltf`, `RootNode` carries a uniform 0.01 scale
// (centimetres → metres). `ProbeClipmapSettings.mesh_sdf_voxel_size` is
// expressed in local mesh units, whereas `brick_voxel_size` (0.125 m) is in
// world space. Setting `mesh_sdf_voxel_size = 25` (25 cm = 0.25 m in world
// space) and `mesh_sdf_max_bricks = 10` (up to 70³ voxels per mesh before
// automatic coarsening) keeps total SDF bricks across the ~570 structural
// geometries under ~40k. The baked model caches (`tools/bake_scene.mjs`) were made at
// these two values and are only taken at them; change either and rerun the bake.
export const MODEL_ROOT_SCALE = 0.01;
export const MESH_SDF_VOXEL_SIZE_CM = 25;
export const MESH_SDF_MAX_BRICKS = 10;
export const MESH_SDF_BAKE_BUDGET = 2048;
// Cascade 0 probes sit on a 1.0 m grid (brick voxel 0.125 m). Excluding small
// non-emissive clutter (< 2.5 m world bounding-box diagonal — pebbles, cups,
// candle sticks) from `ShadedGeometryFlags.SDFWorld` keeps the SDF brick pool
// and 6-card surface atlas focused on structural islands, cliffs, arches,
// bridges, roofs, trees, and emissive signs/lightning bolts.
export const MIN_SDF_WORLD_DIAGONAL_M = 2.5;
// Camera viewpoint presets across the floating island.
export const CAMERA_PRESETS = {
overview: {
target: [-52.34, 5.38, -11.71],
distance: 18,
pitch: 0.6867,
yaw: -2.5203,
},
courtyard: {
target: [-31.41, 4.81, -23.70],
distance: 14,
pitch: 0.3041,
yaw: 2.5224,
},
underbridge: {
target: [-50.63, 4.40, -15.48],
distance: 12,
pitch: 0.0085,
yaw: 2.5630,
},
skullArch: {
target: [-40.52, 3.01, -15.82],
distance: 15,
pitch: 0.3041,
yaw: -1.6683,
},
crystal: {
target: [-66.71, 11.19, 27.26],
distance: 14,
pitch: 0.4722,
yaw: -1.8654,
},
};
/**
* Compute world-space bounding-box diagonal (in metres) of a glTF primitive
* under the model's `0.01` root scale, whether it belongs in `SDFWorld`, and
* its largest-first sort score.
*/
export function primitiveSDFPriority(primitive) {
const bbox = primitive.geometry.bounding_box;
const dx = (bbox[3] - bbox[0]) * MODEL_ROOT_SCALE;
const dy = (bbox[4] - bbox[1]) * MODEL_ROOT_SCALE;
const dz = (bbox[5] - bbox[2]) * MODEL_ROOT_SCALE;
const diagM = Math.hypot(dx, dy, dz);
const mat = primitive.material;
const transparent = mat.transparency_mode === TransparencyMode.Transparent;
const em = mat.emissive_factor;
const emissive = !transparent && em !== undefined && (em.r + em.g + em.b) > 0;
const includeInSDF = !transparent && (emissive || diagM >= MIN_SDF_WORLD_DIAGONAL_M);
return {
diagM,
emissive,
includeInSDF,
sortScore: (includeInSDF ? 1e6 : 0) + (emissive ? 1e5 : 0) + diagM,
};
}
// The two baked files the page loads, and how the second one is tied to the first.
//
// scene.shade.gzip the scene in meep's binary scene format (`serialize_scene`): every mesh
// as meshlets with its ray-tracing BVH, the materials, and the point lights
// scene.modelcache.gzip the mesh SDFs and surface caches the probe clipmap reads, as a meep
// `ModelCacheBundle`, so the page uploads them instead of baking them
//
// `tools/bake_scene.mjs` writes both from the glTF in `source-assets/`.
//
// They are `.gzip` and not `.gz` on purpose. Vite's dev server sends a `.gz` file as gzip-encoded,
// so the browser inflates it before the page sees it and the page's own inflate then fails. The
// page inflates the files itself because the site's server does not compress binary files.
import { primitiveSDFPriority } from "./probeClipmapSetup.js";
export const SCENE_URL = "./models/flying_world/scene.shade.gzip";
export const MODEL_CACHE_URL = "./models/flying_world/scene.modelcache.gzip";
/**
* Fetch a gzipped file and inflate it.
*
* @param {string} url
* @param {(loaded: number, total: number) => void} [onProgress] compressed bytes so far, and in all
* (0 when the server does not say)
* @returns {Promise<ArrayBuffer>}
*/
export async function fetchGzip(url, onProgress) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
}
const total = Number(response.headers.get("content-length")) || 0;
let loaded = 0;
const counted = response.body.pipeThrough(new TransformStream({
transform(chunk, controller) {
loaded += chunk.byteLength;
onProgress?.(loaded, total);
controller.enqueue(chunk);
},
}));
return new Response(counted.pipeThrough(new DecompressionStream("gzip"))).arrayBuffer();
}
/**
* A prefab's geometries and materials, each once, in the order its primitives first use them, and
* the primitives that belong in the SDF world.
*
* A model cache bundle names no geometry or material: its fields and caches are matched to them by
* these positions, which are the same wherever the same scene file is loaded.
*
* @param {import("@woosh/meep-engine/src/engine/graphics3/prefab/Prefab.js").Prefab} prefab
*/
export function sdfTargets(prefab) {
const geometries = [];
const materials = [];
const geometryIndex = new Map();
const materialIndex = new Map();
const included = [];
for (const primitive of prefab.primitives) {
if (!geometryIndex.has(primitive.geometry)) {
geometryIndex.set(primitive.geometry, geometries.length);
geometries.push(primitive.geometry);
}
if (!materialIndex.has(primitive.material)) {
materialIndex.set(primitive.material, materials.length);
materials.push(primitive.material);
}
included.push(primitiveSDFPriority(primitive).includeInSDF);
}
return { geometries, materials, geometryIndex, materialIndex, included };
}
// The model cache file: a small table in front of the bundle's own bytes.
//
// u32 magic "FWMC", u32 fields, u32 caches
// u32 × fields the geometry of each of the bundle's fields, as a position in `sdfTargets`
// u32 × caches the material of each of the bundle's caches, likewise
// the bundle, as `model_cache_bundle_write` wrote it
const MAGIC = 0x434d5746;
/**
* @param {number[]} fields
* @param {number[]} caches
* @param {Uint8Array} bundle
* @returns {Uint8Array}
*/
export function packModelCaches(fields, caches, bundle) {
const head = new Uint32Array(3 + fields.length + caches.length);
head[0] = MAGIC;
head[1] = fields.length;
head[2] = caches.length;
head.set(fields, 3);
head.set(caches, 3 + fields.length);
const bytes = new Uint8Array(head.byteLength + bundle.byteLength);
bytes.set(new Uint8Array(head.buffer), 0);
bytes.set(bundle, head.byteLength);
return bytes;
}
/**
* @param {ArrayBuffer} buffer
* @returns {{fields: Uint32Array, caches: Uint32Array, bundle: Uint8Array}}
*/
export function unpackModelCaches(buffer) {
const counts = new Uint32Array(buffer, 0, 3);
if (counts[0] !== MAGIC) {
throw new Error("not a model cache file");
}
const fields = new Uint32Array(buffer, 12, counts[1]);
const caches = new Uint32Array(buffer, 12 + 4 * counts[1], counts[2]);
const bundle = new Uint8Array(buffer, 12 + 4 * (counts[1] + counts[2]));
return { fields, caches, bundle };
}
// The engine, the view and the scene as both the page (`main.js`) and the bake (`tools/bake.js`)
// stand them up. The bake has to configure the mesh SDFs exactly as the page does, or the page
// cannot take what it baked.
import Vector3 from "@woosh/meep-engine/src/core/geom/Vector3.js";
import Entity from "@woosh/meep-engine/src/engine/ecs/Entity.js";
import { ParentEntitySystem } from "@woosh/meep-engine/src/engine/ecs/parent/ParentEntitySystem.js";
import {
TransformAttachmentSystem,
} from "@woosh/meep-engine/src/engine/ecs/transform-attachment/TransformAttachmentSystem.js";
import { Transform64 } from "@woosh/meep-engine/src/engine/ecs/transform/Transform64.js";
import { EngineHarness } from "@woosh/meep-engine/src/engine/EngineHarness.js";
import {
SHADED_GEOMETRY_EVENT_CHANGE,
} from "@woosh/meep-engine/src/engine/graphics/ecs/mesh-v2/SHADED_GEOMETRY_EVENT_CHANGE.js";
import { ShadedGeometry } from "@woosh/meep-engine/src/engine/graphics/ecs/mesh-v2/ShadedGeometry.js";
import { ShadedGeometryFlags } from "@woosh/meep-engine/src/engine/graphics/ecs/mesh-v2/ShadedGeometryFlags.js";
import { prefab_compile } from "@woosh/meep-engine/src/engine/graphics3/prefab/prefab_compile.js";
import { prefab_instantiate } from "@woosh/meep-engine/src/engine/graphics3/prefab/prefab_instantiate.js";
import { ShadedGeometrySystem } from "@woosh/meep-engine/src/engine/graphics3/ShadedGeometrySystem.js";
import {
ProbeClipmapDebugView,
} from "@woosh/meep-engine/src/shade/renderer/global_illumination/probe_clipmap/debug/ProbeClipmapDebugView.js";
import { ShadeIndirectLightingMode } from "@woosh/meep-engine/src/shade/renderer/ShadeIndirectLightingMode.js";
import {
CAMERA_PRESETS,
MESH_SDF_BAKE_BUDGET,
MESH_SDF_MAX_BRICKS,
MESH_SDF_VOXEL_SIZE_CM,
} from "./probeClipmapSetup.js";
import { sdfTargets } from "./sceneFiles.js";
export const CAMERA_FAR = 180;
/**
* @param {(config: object, engine: object) => void} [configure] more loaders or systems
*/
export async function bootEngine(configure) {
return EngineHarness.bootstrap({
configuration: (config, engine) => {
const scene = EngineHarness.shadeScene(engine);
config.addSystem(new ShadedGeometrySystem(engine.graphics, scene));
config.addSystem(new ParentEntitySystem());
config.addSystem(new TransformAttachmentSystem());
configure?.(config, engine);
},
});
}
export async function buildView(engine) {
const preset = CAMERA_PRESETS.overview;
await EngineHarness.buildBasics({
engine,
enableTerrain: false,
enableWater: false,
enableLights: false,
focus: new Vector3(...preset.target),
distance: preset.distance,
pitch: preset.pitch,
yaw: preset.yaw,
cameraFarDistance: CAMERA_FAR,
cameraController: true,
showFps: false,
});
}
/**
* Turn on `ShadeIndirectLightingMode.ProbeClipmap`, tuned for this scene.
*
* The model's root carries a 0.01 scale, so the local mesh SDF voxel size is in centimetres; the
* per-mesh brick grid is capped at 10 bricks an axis; and the per-frame bake budget is raised so
* that anything the baked model caches do not cover still bakes in a second or two.
*/
export function configureProbeClipmap(renderer) {
renderer.feature_automatic_exposure_enabled = false;
renderer.exposure_compensation = 0.25;
renderer.probe_clipmap.mesh_sdf_voxel_size = MESH_SDF_VOXEL_SIZE_CM;
renderer.probe_clipmap.mesh_sdf_max_bricks = MESH_SDF_MAX_BRICKS;
renderer.probe_clipmap.mesh_sdf_bake_budget = MESH_SDF_BAKE_BUDGET;
renderer.probe_clipmap.history_resampling = true;
renderer.probe_clipmap.debug_view = ProbeClipmapDebugView.None;
renderer.indirect_lighting_mode = ShadeIndirectLightingMode.ProbeClipmap;
}
/**
* Put a scene bundle into the dataset, with every mesh out of the SDF world for now.
*
* A mesh joins the SDF world, and has its SDF baked, the moment its row carrying `SDFWorld` reaches
* the GPU. Holding all of them back until `enterSDFWorld` leaves a frame in which the geometries
* have their GPU records and none is baking: the frame baked model caches can be uploaded in.
*
* @param {import("@woosh/meep-engine/src/engine/ecs/EntityComponentDataset.js").EntityComponentDataset} ecd
* @param {import("@woosh/meep-engine/src/shade/renderer/loader/SceneBundle.js").SceneBundle} bundle
*/
export function placeScene(ecd, bundle) {
const prefab = prefab_compile(bundle);
const root = new Entity().add(new Transform64()).build(ecd);
const instance = prefab_instantiate(prefab, ecd, root);
const { included } = sdfTargets(prefab);
setSDFWorld(ecd, instance, () => false);
return { prefab, instance, included };
}
/**
* Flag the structural and emissive meshes `SDFWorld`; small clutter and transparent meshes stay out
* (`primitiveSDFPriority`).
*/
export function enterSDFWorld(ecd, { instance, included }) {
setSDFWorld(ecd, instance, (i) => included[i]);
}
function setSDFWorld(ecd, instance, wanted) {
const entities = instance.mesh_entities;
for (let i = 0; i < entities.length; i++) {
const geometry = ecd.getComponent(entities[i], ShadedGeometry);
if (geometry === undefined) continue;
const on = wanted(i);
if (geometry.getFlag(ShadedGeometryFlags.SDFWorld) === on) continue;
geometry.writeFlag(ShadedGeometryFlags.SDFWorld, on);
ecd.sendEvent(entities[i], SHADED_GEOMETRY_EVENT_CHANGE, geometry);
}
}
// Bake the Flying World glTF into the two files the page loads, so the page converts and bakes
// nothing.
//
// node tools/bake_scene.mjs [--headful]
//
// Run from this example's folder after `npm ci`. It needs Chrome 149 or newer (set CHROME=<path>
// if it is not in the usual place). The outputs are committed and nothing runs this at build time.
//
// public/models/flying_world/scene.shade.gzip the scene in meep's binary scene format
// public/models/flying_world/scene.modelcache.gzip its mesh SDFs and surface caches
//
// Rerun it after an engine update, and after changing the glTF in `source-assets/`, the lights in
// `tools/sceneLights.js`, or anything in `src/probeClipmapSetup.js`: the model caches are only
// good for the voxel size, brick cap and set of meshes they were baked with. A page given stale
// caches does not break, it bakes what it could not take.
//
// The work happens in a browser (`bake.html`, `bake.js`), because the SDFs are baked on the GPU.
// This script serves that page with Vite, opens it in headless Chrome, and writes down what it
// posts back.
import { spawn } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { gzipSync } from "node:zlib";
import { createServer } from "vite";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const out = join(root, "public/models/flying_world");
const headful = process.argv.includes("--headful");
const CHROME = [
process.env.CHROME,
"C:/Program Files/Google/Chrome/Application/chrome.exe",
"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
"/usr/bin/google-chrome",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
].filter(Boolean).find((candidate) => existsSync(candidate));
if (CHROME === undefined) {
console.error("No Chrome found. Set CHROME=<path to chrome>; it must be 149 or newer.");
process.exit(2);
}
mkdirSync(out, { recursive: true });
let finish;
const finished = new Promise((resolve, reject) => {
finish = { resolve, reject };
});
const server = await createServer({
root,
configFile: join(root, "vite.config.js"),
// no file watching: nothing is edited while this runs, and the files it writes land in public/
server: { port: 5199, strictPort: false, open: false, watch: null },
logLevel: "warn",
plugins: [{
name: "bake-receiver",
configureServer(vite) {
vite.middlewares.use("/__bake", (request, response) => {
const name = request.url.slice(1);
const chunks = [];
request.on("data", (chunk) => chunks.push(chunk));
request.on("end", () => {
const body = Buffer.concat(chunks);
if (name === "log") {
console.log(body.toString());
} else if (name === "done") {
finish.resolve();
} else if (name === "failed") {
finish.reject(new Error(body.toString()));
} else {
// level 9, and no timestamp in the header: an unchanged bake writes the same file
const packed = gzipSync(body, { level: 9 });
writeFileSync(join(out, `${name}.gzip`), packed);
console.log(`${name}.gzip: ${body.length} bytes, ${packed.length} gzipped`);
}
response.statusCode = 204;
response.end();
});
});
},
}],
});
await server.listen();
const url = `${server.resolvedUrls.local[0]}tools/bake.html`;
const profile = mkdtempSync(join(tmpdir(), "meep-bake-"));
const chrome = spawn(CHROME, [
...(headful ? [] : ["--headless=new"]),
`--user-data-dir=${profile}`,
"--remote-debugging-port=0",
"--no-first-run",
"--no-default-browser-check",
"--disable-extensions",
"--enable-unsafe-webgpu",
"--enable-features=Vulkan",
"--window-size=1280,720",
// the page is never looked at, and must keep rendering frames all the same
"--disable-background-timer-throttling",
"--disable-renderer-backgrounding",
"--disable-backgrounding-occluded-windows",
url,
], { stdio: "ignore" });
const timeout = setTimeout(() => finish.reject(new Error("the bake did not finish in 10 minutes")), 600_000);
let code = 0;
try {
await finished;
} catch (error) {
console.error(`Bake failed: ${error.message}`);
code = 1;
}
clearTimeout(timeout);
chrome.kill();
await server.close();
setTimeout(() => {
try {
rmSync(profile, { recursive: true, force: true });
} catch {}
process.exit(code);
}, 500);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Flying World bake</title>
<style>
html, body { margin: 0; height: 100%; background: #0d0c0a; color: #ede9e0; font: 13px ui-monospace, monospace; }
#viewport { position: fixed; inset: 0; }
#status { position: fixed; z-index: 10; top: 12px; left: 12px; white-space: pre; }
</style>
</head>
<body>
<!-- Opened by tools/bake_scene.mjs, which also takes what this page posts. -->
<div id="viewport"></div>
<div id="status">starting…</div>
<script type="module" src="./bake.js"></script>
</body>
</html>
// The browser half of the bake (`bake_scene.mjs` is the other half, and says how to run it).
//
// It needs a browser because the mesh SDFs and surface caches are baked on the GPU. The page:
//
// 1. loads the glTF, and writes it out again in meep's binary scene format, with the 38 point
// lights of `sceneLights.js`;
// 2. loads that file back the way `src/main.js` does, and lets the renderer bake every mesh SDF
// and surface cache;
// 3. reads them back from the GPU as a `ModelCacheBundle`.
//
// Step 2 loads the written file rather than reusing the glTF's objects so that the bundle is tied
// to exactly what the page will have in hand: the same geometries and materials, in the same order.
import { BinaryBuffer } from "@woosh/meep-engine/src/core/binary/BinaryBuffer.js";
import { GameAssetType } from "@woosh/meep-engine/src/engine/asset/GameAssetType.js";
import { load_model_scene_bundle } from "@woosh/meep-engine/src/engine/asset/load_model_scene_bundle.js";
import { ArrayBufferLoader } from "@woosh/meep-engine/src/engine/asset/loaders/ArrayBufferLoader.js";
import {
GLTFSceneBundleAssetLoader,
} from "@woosh/meep-engine/src/engine/asset/loaders/GLTFSceneBundleAssetLoader.js";
import { EntityComponentDataset } from "@woosh/meep-engine/src/engine/ecs/EntityComponentDataset.js";
import { EngineHarness } from "@woosh/meep-engine/src/engine/EngineHarness.js";
import { PointLight } from "@woosh/meep-engine/src/shade/renderer/light/model/PointLight.js";
import { place_light } from "@woosh/meep-engine/src/shade/renderer/light/place_light.js";
import { Scene } from "@woosh/meep-engine/src/shade/renderer/scene/Scene.js";
import { scene_optimize } from "@woosh/meep-engine/src/shade/renderer/scene/optimization/scene_optimize.js";
import { deserialize_scene } from "@woosh/meep-engine/src/shade/renderer/scene/serialization/deserialize_scene.js";
import { serialize_scene } from "@woosh/meep-engine/src/shade/renderer/scene/serialization/serialize_scene.js";
import { exportModelCaches } from "../src/modelCaches.js";
import { bootEngine, buildView, configureProbeClipmap, enterSDFWorld, placeScene } from "../src/sceneSetup.js";
import { SCENE_POINT_LIGHTS } from "./sceneLights.js";
const GLTF_URL = "/source-assets/flying_world/scene.gltf";
const statusEl = document.getElementById("status");
function say(text) {
statusEl.textContent = text;
// the script that opened this page prints it
fetch("/__bake/log", { method: "POST", body: text }).catch(() => {});
}
async function post(name, bytes) {
const response = await fetch(`/__bake/${name}`, { method: "POST", body: bytes });
if (!response.ok) {
throw new Error(`could not hand over ${name}: ${response.status}`);
}
}
function emptyScene() {
const scene = new Scene();
// lights stand at entities, so the scene names a dataset for them
scene.dataset = new EntityComponentDataset();
return scene;
}
/** Resolves once `done()` has held for `frames` rendered frames in a row. */
function settled(engine, done, frames = 20) {
return new Promise((resolve) => {
let held = 0;
const tick = () => {
held = done() ? held + 1 : 0;
if (held >= frames) {
engine.graphics.on.postRender.remove(tick);
resolve();
}
};
engine.graphics.on.postRender.add(tick);
});
}
async function bake() {
say("starting the engine…");
const engine = await bootEngine((config) => {
const gltfLoader = new GLTFSceneBundleAssetLoader();
config.addLoader(GameAssetType.ModelGLTF, gltfLoader);
config.addLoader(GameAssetType.ModelGLTF_JSON, gltfLoader);
config.addLoader(GameAssetType.ArrayBuffer, new ArrayBufferLoader());
});
await buildView(engine);
// as on the page: a sun, whose light system is also what points the renderer at the harness's scene
await EngineHarness.buildLights({ engine, castShadow: false });
configureProbeClipmap(engine.graphics.renderer);
const ecd = engine.entityManager.dataset;
// ── 1. glTF → meep's binary scene ──
say("loading the glTF…");
const source = await load_model_scene_bundle(engine.assetManager, GLTF_URL);
const meshes = source.nodes.filter((node) => node.geometry !== null).length;
// The scene repeats its props (candles, planks, lanterns) as separate meshes. `scene_optimize`
// stores each geometry once, and shares the equal pieces of different ones.
scene_optimize(source);
const drawn = source.nodes.filter((node) => node.geometry !== null);
const geometries = new Set(drawn.map((node) => node.geometry)).size;
const lights = emptyScene();
for (const spec of SCENE_POINT_LIGHTS) {
const light = new PointLight();
light.name = spec.name;
light.color.setRGB(spec.color[0], spec.color[1], spec.color[2]);
light.intensity = spec.intensity;
light.distance = spec.distance;
light.radius = spec.radius;
light.casts_shadow = false;
light.transform.setTranslation(spec.position[0], spec.position[1], spec.position[2]);
light.transform.updateMatrix();
place_light(lights, light);
}
const written = await serialize_scene({ bundle: source, scene: lights });
written.trim();
const sceneBytes = new Uint8Array(written.data);
await post("scene.shade", sceneBytes);
say(`scene: ${meshes} meshes (${drawn.length} after sharing pieces), ${geometries} geometries, ${SCENE_POINT_LIGHTS.length} lights, ${sceneBytes.length} bytes`);
// ── 2. load it back as the page does, and let the renderer bake ──
const bundle = await deserialize_scene(BinaryBuffer.fromArrayBuffer(sceneBytes.buffer.slice(0)), emptyScene());
const placed = placeScene(ecd, bundle);
const context = () => engine.graphics.scene_context(EngineHarness.shadeScene(engine));
await settled(engine, () => context() !== null && context().rows.mesh_rows_version > 0, 1);
enterSDFWorld(ecd, placed);
const sdf = context().geometries.sdf;
const progress = setInterval(() => {
say(`baking: ${sdf.resident_count} mesh SDFs resident, ${sdf.baking_count + sdf.queued_count} to go; `
+ `${sdf.surfaces.resident_count} of ${sdf.surfaces.count} surface caches`);
}, 500);
await settled(engine, () =>
sdf.resident_count > 0
&& sdf.baking_count + sdf.queued_count === 0
&& sdf.surfaces.resident_count === sdf.surfaces.count
&& !sdf.surfaces.has_pending_bake);
clearInterval(progress);
// ── 3. read the caches back ──
const caches = await exportModelCaches(context(), placed.prefab);
await post("scene.modelcache", caches.file);
say(`model caches: ${caches.fields} mesh SDFs (${sdf.coarsened_count} coarsened), ${caches.caches} surface caches, `
+ `${caches.bricks} bricks, ${caches.file.length} bytes`);
await post("done", new Uint8Array(0));
}
bake().catch(async (error) => {
console.error(error);
say(`failed: ${error.stack ?? error}`);
await fetch("/__bake/failed", { method: "POST", body: String(error.stack ?? error) }).catch(() => {});
});
// Authored KHR_lights_punctual point lights extracted from flying_world/scene.gltf
// (Staff Jewel, 15 Point Torch Yellow, and 22 Point Lantern White = 38 lights,
// fitting within ProbeClipmap's MAX_LOCAL_LIGHTS = 64 per-hit evaluation budget).
export const SCENE_POINT_LIGHTS = [
{
"name": "Staff",
"kind": "Staff Jewel",
"position": [
-52.922,
17.179,
15.804
],
"color": [
0.0342,
0.6204,
1
],
"intensity": 10.87,
"distance": 7,
"radius": 0.13
},
{
"name": "Torch",
"kind": "Point Torch Yellow",
"position": [
-81.096,
19.716,
-20.787
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.001",
"kind": "Point Torch Yellow",
"position": [
-54.868,
4.371,
-3.532
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.002",
"kind": "Point Torch Yellow",
"position": [
-62.577,
6.678,
-11.013
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.003",
"kind": "Point Torch Yellow",
"position": [
-46.954,
5.949,
-14.748
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.004",
"kind": "Point Torch Yellow",
"position": [
-51.714,
0.282,
-23.195
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.005",
"kind": "Point Torch Yellow",
"position": [
-43.249,
-0.01,
-24.076
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.006",
"kind": "Point Torch Yellow",
"position": [
-58.065,
2.326,
-24.841
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.007",
"kind": "Point Torch Yellow",
"position": [
-62.364,
2.731,
-25.651
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.008",
"kind": "Point Torch Yellow",
"position": [
-34.971,
6.811,
-18.439
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.009",
"kind": "Point Torch Yellow",
"position": [
-34.941,
6.92,
-15.267
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.010",
"kind": "Point Torch Yellow",
"position": [
-42.997,
0.418,
24.875
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.011",
"kind": "Point Torch Yellow",
"position": [
-41.996,
-0.227,
31.66
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.012",
"kind": "Point Torch Yellow",
"position": [
-45.791,
0.258,
27.72
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.013",
"kind": "Point Torch Yellow",
"position": [
-51.449,
0.68,
20.578
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Torch.014",
"kind": "Point Torch Yellow",
"position": [
-31.39,
9.033,
22.638
],
"color": [
1,
0.7382,
0.0927
],
"intensity": 6.522,
"distance": 4,
"radius": 0.16
},
{
"name": "Point",
"kind": "Point Lantern White",
"position": [
-79.225,
15.85,
-21.45
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.001",
"kind": "Point Lantern White",
"position": [
-79.99,
6.598,
-22.97
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.002",
"kind": "Point Lantern White",
"position": [
-79.945,
1.984,
-23.054
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.003",
"kind": "Point Lantern White",
"position": [
-78.271,
1.241,
-19.722
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.004",
"kind": "Point Lantern White",
"position": [
-62.342,
26.488,
-30.446
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.005",
"kind": "Point Lantern White",
"position": [
-61.15,
22.927,
-25.008
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.006",
"kind": "Point Lantern White",
"position": [
-61.15,
19.449,
-25.008
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.007",
"kind": "Point Lantern White",
"position": [
-59.871,
24.037,
-20.402
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.008",
"kind": "Point Lantern White",
"position": [
-60.807,
19.199,
-20.402
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.009",
"kind": "Point Lantern White",
"position": [
-60.154,
15.459,
-20.402
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.010",
"kind": "Point Lantern White",
"position": [
-59.205,
11.056,
-20.464
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.011",
"kind": "Point Lantern White",
"position": [
-60.796,
6.758,
-20.464
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.012",
"kind": "Point Lantern White",
"position": [
-60.524,
8.542,
-15.142
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.013",
"kind": "Point Lantern White",
"position": [
-57.845,
6.84,
-9.515
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.014",
"kind": "Point Lantern White",
"position": [
-39.962,
7.927,
-21.157
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.015",
"kind": "Point Lantern White",
"position": [
-68.405,
1.02,
17.6
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.016",
"kind": "Point Lantern White",
"position": [
-59.072,
4.665,
18.984
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.017",
"kind": "Point Lantern White",
"position": [
-55.193,
1.568,
15.343
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.018",
"kind": "Point Lantern White",
"position": [
-47.144,
0.887,
16.343
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.019",
"kind": "Point Lantern White",
"position": [
-40.163,
0.533,
18.461
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.020",
"kind": "Point Lantern White",
"position": [
-47.115,
9.573,
24.861
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
},
{
"name": "Point.021",
"kind": "Point Lantern White",
"position": [
-35.763,
10.227,
23.581
],
"color": [
1,
1,
1
],
"intensity": 5.435,
"distance": 3,
"radius": 0.2
}
];
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Real-time Global Illumination · Meep</title>
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #0d0c0a;
color: #ede9e0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 13px;
user-select: none;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
}
.panel, .legend {
position: fixed;
z-index: 10;
background: rgba(20, 18, 15, 0.84);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid rgba(255, 248, 230, 0.12);
border-radius: 10px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45);
}
.panel {
top: 14px;
left: 16px;
width: 280px;
padding: 11px 14px;
max-height: calc(100vh - 60px);
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: rgba(255, 248, 230, 0.2) transparent;
}
.section-title {
margin: 7px 0 4px;
padding-top: 6px;
border-top: 1px solid rgba(255, 248, 230, 0.08);
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
color: #f5b942;
}
.section-title:first-of-type {
margin-top: 0;
padding-top: 0;
border-top: none;
}
.btn-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 5px;
margin-bottom: 4px;
}
.mode-btn {
padding: 6px 8px;
border-radius: 6px;
border: 1px solid rgba(255, 248, 230, 0.14);
background: rgba(255, 248, 230, 0.05);
color: #d8d1c2;
font: inherit;
font-size: 11.5px;
font-weight: 500;
cursor: pointer;
transition: background 0.12s, border-color 0.12s, color 0.12s;
text-align: center;
}
.mode-btn:hover {
background: rgba(255, 248, 230, 0.11);
color: #fff;
}
.mode-btn.active {
background: rgba(245, 185, 66, 0.2);
border-color: rgba(245, 185, 66, 0.65);
color: #ffd57e;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 5px 0;
}
.row label {
color: #d8d1c2;
font-size: 11.5px;
flex: 1;
white-space: nowrap;
}
.row .val {
font-variant-numeric: tabular-nums;
color: #a89f8e;
font-size: 11.5px;
min-width: 38px;
text-align: right;
}
.row input[type="range"] {
width: 112px;
accent-color: #f5b942;
cursor: pointer;
}
.row input[type="checkbox"] {
width: 15px;
height: 15px;
accent-color: #f5b942;
cursor: pointer;
margin: 0;
}
.legend {
bottom: 16px;
left: 16px;
padding: 8px 12px;
font-size: 11.5px;
color: #b9b09f;
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
}
.legend kbd {
display: inline-block;
padding: 1px 5px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10.5px;
color: #efe9dc;
background: rgba(255, 248, 230, 0.1);
border: 1px solid rgba(255, 248, 230, 0.2);
border-radius: 4px;
margin-right: 3px;
}
.legend .credit {
color: #8f8676;
font-size: 10.5px;
border-left: 1px solid rgba(255, 248, 230, 0.12);
padding-left: 10px;
}
.loading {
position: fixed;
inset: 0;
z-index: 20;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
background: radial-gradient(circle at 50% 45%, #1c1915, #0b0a08 75%);
color: #d8d1c2;
font-size: 13px;
letter-spacing: 0.04em;
transition: opacity 0.35s ease;
}
.loading .sub-status {
font-size: 11.5px;
color: #9b9282;
}
.progress-track {
width: 240px;
height: 6px;
border-radius: 999px;
background: rgba(255, 248, 230, 0.1);
border: 1px solid rgba(255, 248, 230, 0.14);
overflow: hidden;
margin-top: 2px;
}
.progress-fill {
width: 0%;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #e09b2d, #ffd57e);
transition: width 0.12s ease-out;
}
.loading.hidden {
opacity: 0;
pointer-events: none;
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="loading" class="loading">
<div>Initialising WebGPU & loading Flying World…</div>
<div id="loading-status" class="sub-status">Preparing global illumination…</div>
<div id="loading-progress" class="progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div id="loading-progress-fill" class="progress-fill"></div>
</div>
</div>
<aside class="panel">
<div class="section-title">Indirect Lighting Mode</div>
<div class="btn-grid">
<button type="button" class="mode-btn active" data-gi-mode="probe-clipmap">Global Illumination</button>
<button type="button" class="mode-btn" data-gi-mode="ibl">Image-based</button>
</div>
<div class="section-title">Lighting</div>
<div class="row">
<label for="local-lights">Scene Point Lights (38)</label>
<input id="local-lights" type="checkbox" checked />
</div>
<div class="row">
<label for="time-of-day">Time of Day</label>
<input id="time-of-day" type="range" min="0" max="24" step="0.05" value="9.5" />
<span class="val" id="time-of-day-val">09:30</span>
</div>
</aside>
<div class="legend">
<span><kbd>Left-drag</kbd> Orbit</span>
<span><kbd>Right-drag</kbd> Pan</span>
<span><kbd>Scroll</kbd> Zoom</span>
<span><kbd>WASD</kbd> Fly</span>
<span class="credit">Scene: “Flying world - Battle of the Trash god” by burunduk (CC-BY-4.0)</span>
</div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
{
"name": "@meep-examples/probe-clipmap",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --open /demo.html",
"build": "vite build",
"bake": "node tools/bake_scene.mjs"
},
"dependencies": {
"@woosh/meep-engine": "3.71.0"
},
"devDependencies": {
"@rollup/plugin-strip": "^3.0.4",
"vite": "^8.0.13"
}
}
# Real-time Global Illumination
A multi-tiered floating island — overhangs, archways, caverns, a giant skull, and 38 torches, lanterns, and a staff jewel — rendered with Shade's real-time `ShadeIndirectLightingMode.ProbeClipmap` global illumination pipeline.
**Left-drag** to orbit, **right-drag** to pan, **scroll** to zoom, **WASD** to fly, and use the panel on the left to switch between **Global Illumination** and **Image-based**, toggle the scene point lights, or sweep the **Time of Day** slider through a full 24 hours.
## What `ProbeClipmap` is doing
Enabling probe clipmap global illumination is a single mode switch on the renderer:
```js
import { ShadeIndirectLightingMode } from "@woosh/meep-engine/src/shade/renderer/ShadeIndirectLightingMode.js";
engine.graphics.renderer.indirect_lighting_mode = ShadeIndirectLightingMode.ProbeClipmap;
```
Under the hood, `ProbeClipmap` maintains three cooperating GPU structures:
1. **Per-Mesh SDFs & Surface Caches (`GPUGeometrySDFManager`, `GPUMeshSurfaceCaches`)** — Every mesh carrying `ShadedGeometryFlags.SDFWorld` (and a non-transparent material) has an object-space signed distance field baked on the GPU into sparse `7³`-voxel bricks (`8³` texels with 1-texel overlap; bricks with identical bytes share a slot), together with a Model Surface Cache per (geometry, material) pair that keeps block-coded diffuse albedo, metalness/roughness and emissive only where the material makes them vary.
2. **World-Space Brick Clipmap (`GPUBrickClipmap`, `GPUBrickMaterial`)** — Each frame, object-space mesh SDFs are composited into a 6-cascade camera-centered `32³` world-space SDF brick clipmap (`0.125 m` voxels at cascade 0, doubling per cascade), and each built brick gathers its surface material from the surface caches. Probe ray hits read that brick material and are shaded with direct sunlight, cascaded/SDF shadows, up to 64 local point/spot lights (`shader_probe_clipmap_light`), and multi-bounce irradiance sampled from the previous frame's probes.
3. **Octahedral Probe Clipmap (`GPUProbeClipmapGI`)** — A 5-cascade `32×32×32` probe volume (`1.0 m` probe spacing at cascade 0, doubling per cascade) relocates probes out of solid geometry along the SDF gradient, sphere-marches 256 rays per probe update (three quarters of the `131,072`-ray frame budget; the rest updates a denser world cache that probe-ray hits sample where these probes have none) through the world brick clipmap, evaluates the brick material's lighting on hits or the octahedral sky environment on misses, temporally blends into a `16×16` octahedral radiance + `8×8` Chebyshev depth-moment atlas, and optionally re-samples its neighbours' histories (`history_resampling`).
## Tuning for a centimetre-scaled glTF scene
The Flying World asset (`source-assets/flying_world/scene.gltf`) contains 5,202 primitives authored in centimetres under a `RootNode` with uniform scale `0.01`:
- **Matching local mesh SDF voxel size to world scale**: `ProbeClipmapSettings.mesh_sdf_voxel_size` is expressed in local mesh units, whereas `brick_voxel_size` (`0.125 m`) is in world space. Setting `renderer.probe_clipmap.mesh_sdf_voxel_size = 25` (`25 cm × 0.01 = 0.25 m`), `mesh_sdf_max_bricks = 10` (up to `70³` voxels per mesh before coarsening), scales every mesh SDF to centimetre coordinates, so the scene's structural meshes fit in about 37,600 SDF bricks.
- **Prioritizing structural & emissive geometry in `SDFWorld`**: Cascade 0 probes are spaced `1.0 m` apart. Transparent meshes (`alphaMode: "BLEND"`, such as the 1,186 candle-flame halo cards) are automatically excluded from `MESH_FLAG_SDF_WORLD` by `GPUSceneRows`, and small non-emissive clutter (`< 2.5 m` world bounding-box diagonal) has `ShadedGeometryFlags.SDFWorld` cleared so the SDF brick pool and surface caches focus on the structural island cliffs, buildings, bridges, arches, skull, trees, and emissive signs/lightning bolts.
## Loading without converting or baking
The page loads two files, and neither needs any work before it can be drawn or traced:
- **`scene.shade.gzip`** is the scene in meep's binary scene format (`serialize_scene` / `deserialize_scene`): every mesh as meshlets with its ray-tracing BVH, the 32 materials, and the 38 point lights. Loading it is a copy into GPU buffers; there is no glTF to parse and no meshlets or BVHs to build. `scene_optimize` runs first, so the 5,202 meshes share 1,158 geometries. It is 3.6 MB, against 27.7 MB of glTF.
- **`scene.modelcache.gzip`** is a `ModelCacheBundle`: the per-mesh SDFs and surface caches of step 1, read back from a GPU that has baked them (`GPUGeometrySDFManager.export_bundle`). The page hands it to `upload_bundle` before any mesh joins the SDF world, and all 650 fields are resident two frames later with nothing baked. It is 5.1 MB.
Both downloads start before the engine does, so they overlap WebGPU start-up.
The world-space brick clipmap and the probes of steps 2 and 3 are not in a file. They follow the camera and the lighting, and the renderer builds them from the model caches within the first few frames.
```js
// src/modelCaches.js
const bundle = model_cache_bundle_read(bytes);
sdf.upload_bundle(bundle, geometryRecords, cacheMaterials, false);
```
A bundle is only taken at the voxel size and brick cap it was baked at, and a field only by a geometry of the same layout. Anything that does not match is baked at load as usual, so a stale file costs time, not correctness.
### Rebaking
```sh
npm run bake
```
`tools/bake_scene.mjs` opens `tools/bake.html` in headless Chrome (the SDFs are baked on the GPU, so the bake needs one), which converts the glTF, loads the result back exactly as the page does, waits for every SDF and surface cache, and exports them. Rerun it after an engine update or after changing the glTF, `tools/sceneLights.js` or `src/probeClipmapSetup.js`.
## Day and night
The Time of Day slider runs from 00:00 to 24:00 and drives everything from `src/dayCycle.js`:
- **Sun and moon paths**: the sun follows its arc across the sky for a 35° latitude, peaking at 55° at noon; the moon runs nearly opposite. The clock is warped so the sun crosses the horizon at under half its noon pace, which stretches sunrise and sunset across a wider part of the slider.
- **One directional light**: it follows the sun by day and the moon by night, swapping between them in the dark minutes of twilight when both are at zero.
- **A sun authored above the air**: one colour (7100 K) and one intensity all day. The renderer takes a directional light through the scene's atmosphere on its way to a surface, so the sun goes gold, then deep orange-red and dim at the horizon, and dark below it, by its direction alone. Two meep `AnimationCurve`s keyed on the sun's elevation are all that is authored, so sunrise and sunset share them: the sun fading out once it is below the horizon, and the moonlight, a dim cold blue, fading in after it.
- **Sky**: the scene's atmosphere (`scene.atmosphere`), with no environment map. It draws the sky from the one directional light, wherever the slider puts it, and the same sky is the image-based lighting and what a probe ray that misses reads, so the whole scene goes cold and dark at night while torches and lanterns stand out. One constant, `sun_irradiance_scale`, lights the air three times as hard as the ground, which fills the shadows at the page's fixed exposure.
- **The moon**: an emissive sphere 10 km out that rides along with the camera, so its disc stays round and crisp at any zoom. Its material is transparent, which keeps it out of the shadow maps (it sits on the moonlight's own axis) and out of the SDF world, and lets it fade into the dawn sky.
## Credits & License
- Scene: **"Flying world - Battle of the Trash god"** by **burunduk** (<https://sketchfab.com/3d-models/flying-world-battle-of-the-trash-god-72228430438a4999935f2fd07dc6fa72>), licensed under [CC-BY-4.0](http://creativecommons.org/licenses/by/4.0/) (see `public/models/flying_world/license.txt`). The shipped files are baked from the glTF in `source-assets/flying_world/`.
import { defineConfig } from "vite";
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { resolve, dirname } from "node:path";
import strip from "@rollup/plugin-strip";
const __dirname = dirname(fileURLToPath(import.meta.url));
export default defineConfig({
// Vite's dependency pre-bundling rewrites the engine's own asset imports and
// loses their URLs, so a dev server ends up serving ".../deps/undefined" for
// the renderer's data files. The engine is source-only ESM and needs no
// pre-bundling - but its CommonJS dependencies do, or the import of them from inside
// the excluded engine finds no default export.
optimizeDeps: {
exclude: ["@woosh/meep-engine"],
include: ["dat.gui", "opentype.js"],
},
plugins: [
{
// Copy the committed source thumbnail into the generated gallery folder.
// public/examples/<id>/ is build output (gitignored); thumbnail.png is
// kept in source here and copied through on every build so the gallery
// (src/data/examples.ts) can resolve it.
name: "copy-thumbnail",
apply: "build",
closeBundle() {
const thumb = resolve(__dirname, "thumbnail.png");
const dst = resolve(__dirname, "../../public/examples/probe-clipmap");
if (existsSync(thumb)) {
mkdirSync(dst, { recursive: true });
copyFileSync(thumb, resolve(dst, "thumbnail.png"));
}
},
},
],
base: "./",
build: {
outDir: resolve(__dirname, "../../public/examples/probe-clipmap"),
emptyOutDir: false,
rollupOptions: {
input: resolve(__dirname, "demo.html"),
plugins: [
{
// this will remove all assert statements from the production build
...strip(),
apply: "build",
},
],
},
target: "es2022",
},
});
thumbnail.png · 337.3 KB
license.txt
Unsupported file type.
scene.modelcache.gzip
Binary file.
scene.shade.gzip
Binary file.