Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

feat(kiln/imposter): lat-lon imposter atlas baker

Matt Kissingeree1c40027124
diff --git a/imposter/__tests__/bake.test.ts b/imposter/__tests__/bake.test.ts
new file mode 100644
index 00000000..79638c0d
--- /dev/null
+++ b/imposter/__tests__/bake.test.ts
@@ -0,0 +1,82 @@
+/**
+ * Live bake test — gated on KILN_IMPOSTER_LIVE=1.
+ *
+ * Real Chromium launch + GLB load + tile render. Slow (~15-30s). Skipped by
+ * default so the core test suite stays fast. Exercises the full pipeline
+ * against a known-good vegetation GLB from the Poly Pizza tier-A set.
+ *
+ * To run:
+ * KILN_IMPOSTER_LIVE=1 cd packages/core && bun test imposter/bake.test.ts
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { existsSync, readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { bakeImposter } from '../bake';
+import { ImposterMetaSchema } from '../schema';
+
+const LIVE = process.env.KILN_IMPOSTER_LIVE === '1';
+
+// Vegetation-research fixture. Pick any bamboo variant; they're all small.
+const here = resolve(fileURLToPath(import.meta.url), '..');
+const FIXTURE_CANDIDATES = [
+ // Primary: vegetation-research mount on the dev workstation.
+ 'C:/Users/Mattm/X/vegetation-research/assets/tier-a-psx/polypizza/bamboo-google-1/model.glb',
+ // Fallback: any tiny GLB bundled in war-assets/ for CI.
+ join(here, '../../../../../../war-assets/validation/gear.glb'),
+];
+
+function findFixture(): string | null {
+ for (const p of FIXTURE_CANDIDATES) {
+ if (existsSync(p)) return p;
+ }
+ return null;
+}
+
+describe.if(LIVE)('bakeImposter (live)', () => {
+ test('bakes a 16-angle hemi atlas with non-zero content', async () => {
+ const fixture = findFixture();
+ if (!fixture) {
+ throw new Error(
+ `no imposter fixture found. Tried:\n ${FIXTURE_CANDIDATES.join('\n ')}`,
+ );
+ }
+ const glb = readFileSync(fixture);
+
+ const result = await bakeImposter(glb, {
+ angles: 16,
+ axis: 'hemi-y',
+ tileSize: 256,
+ auxLayers: ['depth'],
+ bgColor: 'transparent',
+ sourcePath: fixture,
+ });
+
+ // Meta shape is valid.
+ const meta = ImposterMetaSchema.parse(result.meta);
+ expect(meta.angles).toBe(16);
+ expect(meta.tilesX).toBe(4);
+ expect(meta.tilesY).toBe(4);
+ expect(meta.atlasWidth).toBe(1024);
+ expect(meta.atlasHeight).toBe(1024);
+ expect(meta.source.tris).toBeGreaterThan(0);
+ expect(meta.worldSize).toBeGreaterThan(0);
+
+ // Albedo atlas is a valid PNG buffer.
+ expect(result.atlas.byteLength).toBeGreaterThan(1000);
+ expect(result.atlas.subarray(0, 4).toString('hex')).toBe('89504e47'); // PNG magic
+
+ // Aux depth atlas present.
+ expect(result.aux.depth).toBeTruthy();
+ expect(result.aux.depth!.byteLength).toBeGreaterThan(1000);
+ }, 60_000);
+});
+
+// When LIVE is off, still run at least one placeholder so bun reports the file.
+describe.if(!LIVE)('bakeImposter (skipped)', () => {
+ test('set KILN_IMPOSTER_LIVE=1 to run', () => {
+ expect(LIVE).toBe(false);
+ });
+});
diff --git a/imposter/__tests__/projection.test.ts b/imposter/__tests__/projection.test.ts
new file mode 100644
index 00000000..5315aa75
--- /dev/null
+++ b/imposter/__tests__/projection.test.ts
@@ -0,0 +1,116 @@
+/**
+ * Projection math tests — pure, no WebGL, no Chromium.
+ */
+
+import { describe, expect, test } from 'bun:test';
+
+import {
+ dirFromAzEl,
+ enumerateTiles,
+ resolveLayout,
+} from '../projection';
+
+function unit(v: [number, number, number]): boolean {
+ const len = Math.hypot(v[0], v[1], v[2]);
+ return Math.abs(len - 1) < 1e-6;
+}
+
+describe('resolveLayout', () => {
+ test('8 / hemi-y -> 4×2 with 4 azimuths and 2 elevations', () => {
+ const layout = resolveLayout(8, 'hemi-y');
+ expect(layout.tilesX).toBe(4);
+ expect(layout.tilesY).toBe(2);
+ expect(layout.azimuths).toHaveLength(4);
+ expect(layout.elevations).toHaveLength(2);
+ // Top row is HIGHER elevation than bottom row.
+ expect(layout.elevations[0]!).toBeGreaterThan(layout.elevations[1]!);
+ });
+
+ test('16 / y -> 8×2 full sphere (one above, one below horizon)', () => {
+ const layout = resolveLayout(16, 'y');
+ expect(layout.tilesX).toBe(8);
+ expect(layout.tilesY).toBe(2);
+ expect(layout.elevations[0]!).toBeGreaterThan(0);
+ expect(layout.elevations[1]!).toBeLessThan(0);
+ });
+
+ test('16 / hemi-y -> 4×4 hemi', () => {
+ const layout = resolveLayout(16, 'hemi-y');
+ expect(layout.tilesX).toBe(4);
+ expect(layout.tilesY).toBe(4);
+ // All elevations strictly above the horizon.
+ for (const e of layout.elevations) expect(e).toBeGreaterThan(0);
+ });
+
+ test('32 / hemi-y -> 8×4', () => {
+ const layout = resolveLayout(32, 'hemi-y');
+ expect(layout.tilesX).toBe(8);
+ expect(layout.tilesY).toBe(4);
+ });
+
+ test('rejects 8 / y', () => {
+ expect(() => resolveLayout(8, 'y')).toThrow(/hemi-y/);
+ });
+
+ test('rejects 32 / y', () => {
+ expect(() => resolveLayout(32, 'y')).toThrow(/hemi-y/);
+ });
+});
+
+describe('dirFromAzEl', () => {
+ test('azimuth 0, elevation 0 = +X (asset forward)', () => {
+ const d = dirFromAzEl(0, 0);
+ expect(d[0]).toBeCloseTo(1, 6);
+ expect(d[1]).toBeCloseTo(0, 6);
+ expect(d[2]).toBeCloseTo(0, 6);
+ });
+
+ test('azimuth pi/2, elevation 0 = +Z (asset right)', () => {
+ const d = dirFromAzEl(Math.PI / 2, 0);
+ expect(d[0]).toBeCloseTo(0, 6);
+ expect(d[1]).toBeCloseTo(0, 6);
+ expect(d[2]).toBeCloseTo(1, 6);
+ });
+
+ test('elevation pi/2 = +Y (zenith)', () => {
+ const d = dirFromAzEl(0, Math.PI / 2);
+ expect(d[1]).toBeCloseTo(1, 6);
+ });
+
+ test('arbitrary (az, el) returns a unit vector', () => {
+ for (const az of [0.3, 1.2, 2.5, -1.7]) {
+ for (const el of [0.1, 0.7, -0.4]) {
+ expect(unit(dirFromAzEl(az, el))).toBe(true);
+ }
+ }
+ });
+});
+
+describe('enumerateTiles', () => {
+ test('16 / hemi-y yields exactly 16 unique unit directions', () => {
+ const layout = resolveLayout(16, 'hemi-y');
+ const tiles = enumerateTiles(layout);
+ expect(tiles).toHaveLength(16);
+ for (const t of tiles) expect(unit(t.dir)).toBe(true);
+
+ // Each tile's (i,j) is unique.
+ const keys = new Set(tiles.map((t) => `${t.i},${t.j}`));
+ expect(keys.size).toBe(16);
+ });
+
+ test('row-major order: first tile is (0,0) — top-left, highest elevation', () => {
+ const layout = resolveLayout(16, 'hemi-y');
+ const tiles = enumerateTiles(layout);
+ expect(tiles[0]!.i).toBe(0);
+ expect(tiles[0]!.j).toBe(0);
+ // Top row == highest elevation.
+ expect(tiles[0]!.el).toBe(Math.max(...layout.elevations));
+ });
+
+ test('tile count matches angle count for every supported combo', () => {
+ expect(enumerateTiles(resolveLayout(8, 'hemi-y'))).toHaveLength(8);
+ expect(enumerateTiles(resolveLayout(16, 'y'))).toHaveLength(16);
+ expect(enumerateTiles(resolveLayout(16, 'hemi-y'))).toHaveLength(16);
+ expect(enumerateTiles(resolveLayout(32, 'hemi-y'))).toHaveLength(32);
+ });
+});
diff --git a/imposter/__tests__/schema.test.ts b/imposter/__tests__/schema.test.ts
new file mode 100644
index 00000000..28bc3d2d
--- /dev/null
+++ b/imposter/__tests__/schema.test.ts
@@ -0,0 +1,61 @@
+/**
+ * ImposterMeta zod schema round-trip tests.
+ */
+
+import { describe, expect, test } from 'bun:test';
+
+import { IMPOSTER_SCHEMA_VERSION, ImposterMetaSchema, type ImposterMeta } from '../schema';
+
+const VALID: ImposterMeta = {
+ version: IMPOSTER_SCHEMA_VERSION,
+ angles: 16,
+ tilesX: 4,
+ tilesY: 4,
+ tileSize: 512,
+ atlasWidth: 2048,
+ atlasHeight: 2048,
+ worldSize: 6.25,
+ yOffset: 3.1,
+ projection: 'orthographic',
+ axis: 'hemi-y',
+ hemi: true,
+ layout: 'latlon',
+ azimuths: [0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2],
+ elevations: [1.3, 0.87, 0.44, 0.087],
+ bbox: { min: [-0.5, 0, -0.5], max: [0.5, 6.2, 0.5] },
+ source: { path: 'foo.glb', bytes: 12345, tris: 987 },
+ auxLayers: ['albedo', 'depth'],
+ bgColor: 'transparent',
+};
+
+describe('ImposterMetaSchema', () => {
+ test('accepts a valid payload', () => {
+ expect(() => ImposterMetaSchema.parse(VALID)).not.toThrow();
+ });
+
+ test('round-trips via JSON', () => {
+ const json = JSON.stringify(VALID);
+ const decoded = ImposterMetaSchema.parse(JSON.parse(json));
+ expect(decoded).toEqual(VALID);
+ });
+
+ test('rejects unsupported angles', () => {
+ const bad = { ...VALID, angles: 24 as unknown as 16 };
+ expect(() => ImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('rejects non-orthographic projection', () => {
+ const bad = { ...VALID, projection: 'perspective' as unknown as 'orthographic' };
+ expect(() => ImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('rejects mismatched version', () => {
+ const bad = { ...VALID, version: 99 as unknown as typeof IMPOSTER_SCHEMA_VERSION };
+ expect(() => ImposterMetaSchema.parse(bad)).toThrow();
+ });
+
+ test('source.path is optional', () => {
+ const noPath = { ...VALID, source: { bytes: 0, tris: 0 } };
+ expect(() => ImposterMetaSchema.parse(noPath)).not.toThrow();
+ });
+});
diff --git a/imposter/bake.ts b/imposter/bake.ts
new file mode 100644
index 00000000..4723fe92
--- /dev/null
+++ b/imposter/bake.ts
@@ -0,0 +1,358 @@
+/**
+ * Imposter baker — renders a GLB from N camera angles into a packed atlas.
+ *
+ * Backend: Playwright + Chromium (same pattern as scripts/visual-audit.ts).
+ * Reason: the kiln render substrate (render.ts) is pure scene-graph math with
+ * no WebGL, so actual pixel output requires a real GPU context. Playwright is
+ * already a repo dep and works on Windows, which headless-gl does not.
+ *
+ * Strategy:
+ * 1. Launch one Chromium page per session (ImposterSession).
+ * 2. Inject a tiny three.js 0.184 harness that loads GLBs from data URLs.
+ * 3. For each tile, set an orthographic camera to (az, el), render, capture
+ * PNG tile via canvas.toDataURL.
+ * 4. Composite tiles into a single atlas via sharp.
+ * 5. Optionally bake auxiliary layers (depth, normal) with shared geometry
+ * and a swapped material — each emits its own atlas PNG.
+ *
+ * The session is reusable — one Chromium launch can bake dozens of GLBs.
+ */
+
+import { Buffer } from 'node:buffer';
+import { readFileSync } from 'node:fs';
+import sharp from 'sharp';
+import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
+
+import type {
+ ImposterAngleCount,
+ ImposterAuxLayer,
+ ImposterAxis,
+ ImposterBgColor,
+ ImposterMeta,
+} from './schema';
+import { IMPOSTER_SCHEMA_VERSION } from './schema';
+import { enumerateTiles, resolveLayout } from './projection';
+
+export interface BakeImposterOptions {
+ angles: ImposterAngleCount;
+ axis?: ImposterAxis;
+ /** Pixel size of a single tile (square). Atlas size = tileSize * tilesX × tilesY. */
+ tileSize?: 128 | 256 | 512 | 1024;
+ /** Which layers to produce. 'albedo' is always included. */
+ auxLayers?: ImposterAuxLayer[];
+ /** Background color for the albedo bake. 'transparent' uses RGBA alpha. */
+ bgColor?: ImposterBgColor;
+ /** Included in meta.source.path for provenance. */
+ sourcePath?: string;
+}
+
+export interface BakeImposterResult {
+ /** Packed albedo atlas (PNG). */
+ atlas: Buffer;
+ /** Auxiliary atlases keyed by layer name. */
+ aux: Partial<Record<ImposterAuxLayer, Buffer>>;
+ /** Sidecar metadata — write alongside the atlas. */
+ meta: ImposterMeta;
+}
+
+export interface ImposterSession {
+ bake(glb: Buffer | string, opts: BakeImposterOptions): Promise<BakeImposterResult>;
+ close(): Promise<void>;
+}
+
+/** Spin up a reusable Playwright session. Call close() when you're done batching. */
+export async function openImposterSession(): Promise<ImposterSession> {
+ const browser = await chromium.launch();
+ const ctx = await browser.newContext({ viewport: { width: 1024, height: 1024 }, deviceScaleFactor: 1 });
+ const page = await ctx.newPage();
+ await page.setContent(buildHarnessHtml());
+ await page.waitForFunction(
+ () => (globalThis as unknown as { __imposterReady?: boolean }).__imposterReady === true,
+ { timeout: 30_000 },
+ );
+
+ return {
+ bake: (glb, opts) => bakeOnPage(page, glb, opts),
+ close: async () => {
+ await ctx.close();
+ await browser.close();
+ },
+ };
+}
+
+/** Convenience: one-shot bake. Internally opens + closes a session. */
+export async function bakeImposter(
+ glb: Buffer | string,
+ opts: BakeImposterOptions,
+): Promise<BakeImposterResult> {
+ const session = await openImposterSession();
+ try {
+ return await session.bake(glb, opts);
+ } finally {
+ await session.close();
+ }
+}
+
+// ============================================================================
+// Internals
+// ============================================================================
+
+async function bakeOnPage(
+ page: Page,
+ glb: Buffer | string,
+ opts: BakeImposterOptions,
+): Promise<BakeImposterResult> {
+ const angles = opts.angles;
+ const axis: ImposterAxis = opts.axis ?? (angles === 16 ? 'y' : 'hemi-y');
+ const tileSize = opts.tileSize ?? 512;
+ const auxLayers = opts.auxLayers ?? [];
+ const bgColor: ImposterBgColor = opts.bgColor ?? 'transparent';
+
+ const buf = typeof glb === 'string' ? readFileSync(glb) : glb;
+ const sourcePath = opts.sourcePath ?? (typeof glb === 'string' ? glb : undefined);
+
+ const layout = resolveLayout(angles, axis);
+ const tiles = enumerateTiles(layout);
+
+ // Load the GLB into the harness and pull back bbox + tri count.
+ const loadInfo = (await page.evaluate(
+ async ([dataUrl, tileSz]) => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const w = globalThis as any;
+ return w.__imposterLoadGlb(dataUrl, tileSz);
+ },
+ [`data:model/gltf-binary;base64,${buf.toString('base64')}`, tileSize] as const,
+ )) as { bbox: { min: [number, number, number]; max: [number, number, number] }; tris: number };
+
+ // Render each layer.
+ const layers: ImposterAuxLayer[] = ['albedo', ...auxLayers];
+ const atlases: Partial<Record<ImposterAuxLayer, Buffer>> = {};
+ for (const layer of layers) {
+ const tilePngs: Buffer[] = [];
+ for (const tile of tiles) {
+ const dataUrl = (await page.evaluate(
+ (args) => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const w = globalThis as any;
+ return w.__imposterRenderTile(args);
+ },
+ {
+ dir: tile.dir,
+ layer,
+ bgColor,
+ tileSize,
+ },
+ )) as string;
+ const png = Buffer.from(dataUrl.split(',')[1]!, 'base64');
+ tilePngs.push(png);
+ }
+ atlases[layer] = await composeAtlas(tilePngs, tileSize, layout.tilesX, layout.tilesY, bgColor);
+ }
+
+ const albedo = atlases.albedo!;
+ // Separate aux from albedo in the result surface.
+ const aux: Partial<Record<ImposterAuxLayer, Buffer>> = {};
+ for (const layer of auxLayers) {
+ if (atlases[layer]) aux[layer] = atlases[layer];
+ }
+
+ // Build the ImposterMeta sidecar.
+ const min = loadInfo.bbox.min;
+ const max = loadInfo.bbox.max;
+ const sizeX = max[0] - min[0];
+ const sizeY = max[1] - min[1];
+ const sizeZ = max[2] - min[2];
+ const worldSize = Math.max(sizeX, sizeY, sizeZ);
+ const yOffset = (min[1] + max[1]) * 0.5;
+
+ const meta: ImposterMeta = {
+ version: IMPOSTER_SCHEMA_VERSION,
+ angles,
+ tilesX: layout.tilesX,
+ tilesY: layout.tilesY,
+ tileSize,
+ atlasWidth: layout.tilesX * tileSize,
+ atlasHeight: layout.tilesY * tileSize,
+ worldSize,
+ yOffset,
+ projection: 'orthographic',
+ axis,
+ hemi: axis === 'hemi-y',
+ layout: 'latlon',
+ azimuths: layout.azimuths,
+ elevations: layout.elevations,
+ bbox: { min, max },
+ source: {
+ ...(sourcePath ? { path: sourcePath } : {}),
+ bytes: buf.byteLength,
+ tris: loadInfo.tris,
+ },
+ auxLayers: layers,
+ bgColor,
+ };
+
+ return { atlas: albedo, aux, meta };
+}
+
+async function composeAtlas(
+ tilePngs: Buffer[],
+ tileSize: number,
+ tilesX: number,
+ tilesY: number,
+ bgColor: ImposterBgColor,
+): Promise<Buffer> {
+ const width = tilesX * tileSize;
+ const height = tilesY * tileSize;
+ const bg =
+ bgColor === 'transparent'
+ ? { r: 0, g: 0, b: 0, alpha: 0 }
+ : { r: 255, g: 0, b: 255, alpha: 1 };
+
+ const composites: sharp.OverlayOptions[] = [];
+ for (let idx = 0; idx < tilePngs.length; idx++) {
+ const i = idx % tilesX;
+ const j = Math.floor(idx / tilesX);
+ composites.push({ input: tilePngs[idx]!, left: i * tileSize, top: j * tileSize });
+ }
+
+ return sharp({
+ create: { width, height, channels: 4, background: bg },
+ })
+ .composite(composites)
+ .png()
+ .toBuffer();
+}
+
+// ============================================================================
+// In-browser harness — three.js 0.184 from CDN, with loader + render helpers.
+// ============================================================================
+
+function buildHarnessHtml(): string {
+ return `<!DOCTYPE html>
+<html><head>
+<meta charset="utf-8">
+<style>html,body{margin:0;padding:0;background:#ff00ff}#app{width:1024px;height:1024px}</style>
+<script type="importmap">
+{
+ "imports": {
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
+ }
+}
+</script>
+</head>
+<body>
+<div id="app"></div>
+<script type="module">
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+
+const W = () => renderer.domElement.width;
+const app = document.getElementById('app');
+const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
+renderer.setPixelRatio(1);
+renderer.setSize(1024, 1024);
+renderer.outputColorSpace = THREE.SRGBColorSpace;
+app.appendChild(renderer.domElement);
+
+const scene = new THREE.Scene();
+const ambient = new THREE.AmbientLight(0xffffff, 0.45);
+scene.add(ambient);
+const key = new THREE.DirectionalLight(0xffffff, 1.0);
+key.position.set(1.5, 2, 1);
+scene.add(key);
+const fill = new THREE.DirectionalLight(0xffffff, 0.35);
+fill.position.set(-1, 0.5, -1);
+scene.add(fill);
+
+let root = null;
+let boundsRadius = 1;
+let boundsCenter = new THREE.Vector3();
+let originalMaterials = new Map();
+
+window.__imposterLoadGlb = async (dataUrl, tileSize) => {
+ if (root) scene.remove(root);
+ originalMaterials.clear();
+ if (renderer.domElement.width !== tileSize) {
+ renderer.setSize(tileSize, tileSize);
+ }
+ const loader = new GLTFLoader();
+ return new Promise((resolve, reject) => {
+ loader.load(dataUrl, (gltf) => {
+ root = gltf.scene;
+ scene.add(root);
+ const box = new THREE.Box3().setFromObject(root);
+ boundsCenter = box.getCenter(new THREE.Vector3());
+ const size = box.getSize(new THREE.Vector3());
+ const diag = Math.sqrt(size.x * size.x + size.y * size.y + size.z * size.z);
+ boundsRadius = diag * 0.5 || 1;
+ let tris = 0;
+ root.traverse((obj) => {
+ if (obj.isMesh && obj.material) {
+ originalMaterials.set(obj, obj.material);
+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
+ for (const m of mats) {
+ m.side = THREE.FrontSide;
+ m.needsUpdate = true;
+ }
+ if (obj.geometry && obj.geometry.index) tris += obj.geometry.index.count / 3;
+ else if (obj.geometry && obj.geometry.attributes.position) tris += obj.geometry.attributes.position.count / 3;
+ }
+ });
+ resolve({
+ bbox: { min: [box.min.x, box.min.y, box.min.z], max: [box.max.x, box.max.y, box.max.z] },
+ tris: Math.round(tris),
+ });
+ }, undefined, (err) => reject(err));
+ });
+};
+
+window.__imposterRenderTile = ({ dir, layer, bgColor, tileSize }) => {
+ if (!root) throw new Error('no GLB loaded');
+ if (renderer.domElement.width !== tileSize) renderer.setSize(tileSize, tileSize);
+
+ // Swap materials for the active layer.
+ if (layer === 'normal') {
+ const normMat = new THREE.MeshNormalMaterial({ side: THREE.FrontSide });
+ root.traverse((o) => { if (o.isMesh) o.material = normMat; });
+ } else if (layer === 'depth') {
+ const depthMat = new THREE.MeshDepthMaterial({
+ side: THREE.FrontSide,
+ depthPacking: THREE.RGBADepthPacking,
+ });
+ root.traverse((o) => { if (o.isMesh) o.material = depthMat; });
+ } else {
+ // albedo — restore originals
+ root.traverse((o) => {
+ if (o.isMesh && originalMaterials.has(o)) o.material = originalMaterials.get(o);
+ });
+ }
+
+ // Orthographic camera sized to the bounding sphere.
+ const half = boundsRadius * 1.02;
+ const camera = new THREE.OrthographicCamera(-half, half, half, -half, 0.01, 200);
+ const d = new THREE.Vector3(dir[0], dir[1], dir[2]).normalize();
+ camera.position.copy(boundsCenter).addScaledVector(d, boundsRadius * 4);
+ camera.up.set(0, 1, 0);
+ camera.lookAt(boundsCenter);
+
+ // Background.
+ if (layer === 'albedo' && bgColor === 'transparent') {
+ scene.background = null;
+ renderer.setClearColor(0x000000, 0);
+ } else if (layer === 'albedo' && bgColor === 'magenta') {
+ scene.background = new THREE.Color(0xff00ff);
+ renderer.setClearColor(0xff00ff, 1);
+ } else {
+ scene.background = null;
+ renderer.setClearColor(0x000000, 0);
+ }
+
+ renderer.render(scene, camera);
+ return renderer.domElement.toDataURL('image/png');
+};
+
+window.__imposterReady = true;
+</script>
+</body></html>`;
+}
diff --git a/imposter/index.ts b/imposter/index.ts
new file mode 100644
index 00000000..0ab94768
--- /dev/null
+++ b/imposter/index.ts
@@ -0,0 +1,29 @@
+/**
+ * kiln/imposter — octahedral / lat-lon imposter atlas baker.
+ *
+ * Public surface consumed via the `kiln` namespace:
+ *
+ * import { kiln } from '@pixel-forge/core';
+ * const { atlas, aux, meta } = await kiln.bakeImposter(glbBuffer, {
+ * angles: 16, axis: 'hemi-y', tileSize: 512, auxLayers: ['depth'],
+ * });
+ */
+
+export { bakeImposter, openImposterSession } from './bake';
+export type { BakeImposterOptions, BakeImposterResult, ImposterSession } from './bake';
+
+export {
+ IMPOSTER_SCHEMA_VERSION,
+ ImposterMetaSchema,
+} from './schema';
+export type {
+ ImposterMeta,
+ ImposterAngleCount,
+ ImposterAxis,
+ ImposterLayout,
+ ImposterAuxLayer,
+ ImposterBgColor,
+} from './schema';
+
+export { resolveLayout, enumerateTiles, dirFromAzEl } from './projection';
+export type { TileCamera, TileLayout } from './projection';
diff --git a/imposter/projection.ts b/imposter/projection.ts
new file mode 100644
index 00000000..c56e061c
--- /dev/null
+++ b/imposter/projection.ts
@@ -0,0 +1,131 @@
+/**
+ * Imposter camera-direction math.
+ *
+ * Lat/lon layout (azimuth × elevation). For the angle counts supported:
+ *
+ * angles=8 hemi-y 4 az × 2 el → 4×2 tile grid
+ * angles=16 y 8 az × 2 el → 8×2 tile grid (full sphere: 2 elevations = +45° and -45°)
+ * angles=16 hemi-y 4 az × 4 el → 4×4 tile grid
+ * angles=32 hemi-y 8 az × 4 el → 8×4 tile grid
+ *
+ * Tiles are stored row-major, left-to-right / top-to-bottom. The TOP row is the
+ * HIGHEST elevation; this is the convention baked into the atlas and recorded
+ * in meta.elevations (top to bottom = high to low). Both arrays go in the
+ * order the shader expects when indexing by (tileX, tileY).
+ *
+ * Kiln world frame: +X forward (asset nose / canopy front), +Y up, +Z right.
+ * Azimuth 0 looks at the asset from +X. Azimuth increases toward +Z (right-side
+ * profile at azimuth π/2). All camera up-vectors stay (0,1,0).
+ */
+
+export type ImposterAngleCount = 8 | 16 | 32;
+export type ImposterAxis = 'y' | 'hemi-y';
+
+export interface TileCamera {
+ /** Tile column (0 = leftmost). */
+ i: number;
+ /** Tile row (0 = topmost = highest elevation). */
+ j: number;
+ /** Azimuth in radians. */
+ az: number;
+ /** Elevation in radians. 0 = horizon, positive = above. */
+ el: number;
+ /** Unit direction FROM target center TOWARD camera. */
+ dir: [number, number, number];
+}
+
+export interface TileLayout {
+ tilesX: number;
+ tilesY: number;
+ azimuths: number[]; // length === tilesX
+ elevations: number[]; // length === tilesY (top row first)
+ axis: ImposterAxis;
+}
+
+/**
+ * Resolve grid dimensions + angle sequences for a given (angles, axis) combo.
+ * Throws on unsupported combinations.
+ */
+export function resolveLayout(angles: ImposterAngleCount, axis: ImposterAxis): TileLayout {
+ if (angles === 8) {
+ if (axis !== 'hemi-y') {
+ throw new Error(`8-angle imposter requires axis='hemi-y' (got '${axis}')`);
+ }
+ return {
+ tilesX: 4,
+ tilesY: 2,
+ axis,
+ azimuths: evenAzimuths(4),
+ // Two elevations above the horizon: steep + shallow. Top row = high.
+ elevations: [degToRad(55), degToRad(15)],
+ };
+ }
+
+ if (angles === 16) {
+ if (axis === 'y') {
+ return {
+ tilesX: 8,
+ tilesY: 2,
+ axis,
+ azimuths: evenAzimuths(8),
+ // One above horizon, one below — full-sphere with minimal rows.
+ elevations: [degToRad(30), degToRad(-30)],
+ };
+ }
+ // hemi-y: 4 × 4
+ return {
+ tilesX: 4,
+ tilesY: 4,
+ axis,
+ azimuths: evenAzimuths(4),
+ elevations: [degToRad(75), degToRad(50), degToRad(25), degToRad(5)],
+ };
+ }
+
+ if (angles === 32) {
+ if (axis !== 'hemi-y') {
+ throw new Error(`32-angle imposter requires axis='hemi-y' (got '${axis}')`);
+ }
+ return {
+ tilesX: 8,
+ tilesY: 4,
+ axis,
+ azimuths: evenAzimuths(8),
+ elevations: [degToRad(75), degToRad(50), degToRad(25), degToRad(5)],
+ };
+ }
+
+ throw new Error(`Unsupported angle count: ${angles}`);
+}
+
+/** Enumerate every tile for a layout, left-to-right top-to-bottom. */
+export function enumerateTiles(layout: TileLayout): TileCamera[] {
+ const out: TileCamera[] = [];
+ for (let j = 0; j < layout.tilesY; j++) {
+ for (let i = 0; i < layout.tilesX; i++) {
+ const az = layout.azimuths[i]!;
+ const el = layout.elevations[j]!;
+ out.push({ i, j, az, el, dir: dirFromAzEl(az, el) });
+ }
+ }
+ return out;
+}
+
+/** Unit direction FROM target TOWARD camera, from (azimuth, elevation). */
+export function dirFromAzEl(az: number, el: number): [number, number, number] {
+ const ce = Math.cos(el);
+ const x = Math.cos(az) * ce;
+ const z = Math.sin(az) * ce;
+ const y = Math.sin(el);
+ return [x, y, z];
+}
+
+function evenAzimuths(count: number): number[] {
+ const out: number[] = [];
+ for (let i = 0; i < count; i++) out.push((i / count) * Math.PI * 2);
+ return out;
+}
+
+function degToRad(deg: number): number {
+ return (deg / 180) * Math.PI;
+}
diff --git a/imposter/schema.ts b/imposter/schema.ts
new file mode 100644
index 00000000..d423d161
--- /dev/null
+++ b/imposter/schema.ts
@@ -0,0 +1,84 @@
+/**
+ * ImposterMeta schema — sidecar written next to every baked imposter atlas.
+ *
+ * A consumer shader (TIJ's billboard system, or any three.js plane material)
+ * uses this to:
+ * - size the billboard quad to match the source bbox (worldSize, yOffset)
+ * - map a view-direction to a tile via layout + azimuths + elevations
+ * - sample auxiliary atlases (depth for parallax popping, normal for light)
+ *
+ * The pipeline pins `version: 1`. Any breaking change to tile layout or aux
+ * conventions increments the version and keeps prior readers working.
+ */
+
+import { z } from 'zod';
+
+export const IMPOSTER_SCHEMA_VERSION = 1 as const;
+
+export type ImposterAngleCount = 8 | 16 | 32;
+export type ImposterAxis = 'y' | 'hemi-y';
+export type ImposterLayout = 'latlon' | 'octahedral';
+export type ImposterAuxLayer = 'albedo' | 'normal' | 'depth';
+export type ImposterBgColor = 'magenta' | 'transparent';
+
+export const ImposterMetaSchema = z.object({
+ version: z.literal(IMPOSTER_SCHEMA_VERSION),
+
+ /** Total viewpoints baked into the atlas. */
+ angles: z.union([z.literal(8), z.literal(16), z.literal(32)]),
+ /** Atlas grid dimensions — tiles across / down. */
+ tilesX: z.number().int().positive(),
+ tilesY: z.number().int().positive(),
+ /** Pixel size of a single tile (square). */
+ tileSize: z.number().int().positive(),
+ /** Total atlas width/height in pixels (tilesX*tileSize, tilesY*tileSize). */
+ atlasWidth: z.number().int().positive(),
+ atlasHeight: z.number().int().positive(),
+
+ /** Bounding-sphere diameter of the source mesh, world units. Scale the billboard quad to this. */
+ worldSize: z.number().positive(),
+ /** Offset from the GLB origin to the bbox center along Y, world units. */
+ yOffset: z.number(),
+
+ /** Orthographic — imposters need constant silhouette. */
+ projection: z.literal('orthographic'),
+
+ /** Axis convention. 'y' = full sphere. 'hemi-y' = upper hemisphere only. */
+ axis: z.enum(['y', 'hemi-y']),
+ /** Redundant helper for shaders — true if axis === 'hemi-y'. */
+ hemi: z.boolean(),
+
+ /** Tile layout strategy. */
+ layout: z.enum(['latlon', 'octahedral']),
+ /**
+ * For layout='latlon': azimuth angles (radians) per column. Length === tilesX.
+ * Azimuth 0 = +X (the asset's forward). Increases toward +Z (right).
+ */
+ azimuths: z.array(z.number()),
+ /**
+ * For layout='latlon': elevation angles (radians) per row. Length === tilesY.
+ * 0 = horizon. +π/2 = zenith. Rows go top-to-bottom = high-to-low elevation.
+ */
+ elevations: z.array(z.number()),
+
+ /** Axis-aligned bbox of the source mesh, world units. */
+ bbox: z.object({
+ min: z.tuple([z.number(), z.number(), z.number()]),
+ max: z.tuple([z.number(), z.number(), z.number()]),
+ }),
+
+ /** Source mesh stats for provenance. */
+ source: z.object({
+ path: z.string().optional(),
+ bytes: z.number().int().nonnegative(),
+ tris: z.number().int().nonnegative(),
+ }),
+
+ /** Auxiliary layers packed alongside albedo (as separate PNGs). */
+ auxLayers: z.array(z.enum(['albedo', 'normal', 'depth'])),
+
+ /** Background color used for the bake. 'transparent' uses RGBA alpha. */
+ bgColor: z.enum(['magenta', 'transparent']),
+});
+
+export type ImposterMeta = z.infer<typeof ImposterMetaSchema>;
diff --git a/index.ts b/index.ts
index 58483b79..07c2e39e 100644
--- a/index.ts
+++ b/index.ts
@@ -122,6 +122,23 @@ export type { GearOptions, BladeOptions } from './gears';
export { loadTexture, pbrMaterial } from './textures';
export type { PbrMaterialOptions, TextureSource, EncodedTextureData } from './textures';
+// -----------------------------------------------------------------------------
+// Imposter baker (kiln/imposter)
+// -----------------------------------------------------------------------------
+export { bakeImposter, openImposterSession } from './imposter';
+export type {
+ BakeImposterOptions,
+ BakeImposterResult,
+ ImposterSession,
+ ImposterMeta,
+ ImposterAngleCount,
+ ImposterAxis,
+ ImposterLayout,
+ ImposterAuxLayer,
+ ImposterBgColor,
+} from './imposter';
+export { ImposterMetaSchema, IMPOSTER_SCHEMA_VERSION } from './imposter';
+
// =============================================================================
// Top-level `generate()` - the full pipeline: prompt -> code -> GLB
// =============================================================================