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.

Ship static octahedral imposter CLI

Matt Kissingerdf3d1a7d50da
diff --git a/imposter/__tests__/projection.test.ts b/imposter/__tests__/projection.test.ts
index 5315aa75..9fbcf008 100644
--- a/imposter/__tests__/projection.test.ts
+++ b/imposter/__tests__/projection.test.ts
@@ -6,7 +6,10 @@ import { describe, expect, test } from 'bun:test';
import {
dirFromAzEl,
+ enumerateOctahedralTiles,
enumerateTiles,
+ octaDecode,
+ octaEncode,
resolveLayout,
} from '../projection';
@@ -114,3 +117,39 @@ describe('enumerateTiles', () => {
expect(enumerateTiles(resolveLayout(32, 'hemi-y'))).toHaveLength(32);
});
});
+
+describe('octahedral projection', () => {
+ test('enumerateOctahedralTiles returns row-major unit directions', () => {
+ const tiles = enumerateOctahedralTiles({ x: 4, y: 4 });
+ expect(tiles).toHaveLength(16);
+ expect(tiles.map((tile) => [tile.i, tile.j]).slice(0, 5)).toEqual([
+ [0, 0],
+ [1, 0],
+ [2, 0],
+ [3, 0],
+ [0, 1],
+ ]);
+ for (const tile of tiles) expect(unit(tile.dir)).toBe(true);
+ });
+
+ test('octaEncode and octaDecode round-trip canonical directions', () => {
+ for (const dir of [
+ [1, 0, 0],
+ [0, 1, 0],
+ [0, -1, 0],
+ [0, 0, 1],
+ [0, 0, -1],
+ ] as Array<[number, number, number]>) {
+ const encoded = octaEncode(dir);
+ const decoded = octaDecode(encoded[0], encoded[1]);
+ expect(decoded[0]).toBeCloseTo(dir[0], 6);
+ expect(decoded[1]).toBeCloseTo(dir[1], 6);
+ expect(decoded[2]).toBeCloseTo(dir[2], 6);
+ }
+ });
+
+ test('rejects invalid octahedral grid dimensions', () => {
+ expect(() => enumerateOctahedralTiles({ x: 0, y: 4 })).toThrow();
+ expect(() => enumerateOctahedralTiles({ x: 4.5, y: 4 })).toThrow();
+ });
+});
diff --git a/imposter/__tests__/schema.test.ts b/imposter/__tests__/schema.test.ts
index 69e2fcf1..7efd553b 100644
--- a/imposter/__tests__/schema.test.ts
+++ b/imposter/__tests__/schema.test.ts
@@ -4,10 +4,15 @@
import { describe, expect, test } from 'bun:test';
-import { IMPOSTER_SCHEMA_VERSION, ImposterMetaSchema, type ImposterMeta } from '../schema';
+import {
+ IMPOSTER_LEGACY_SCHEMA_VERSION,
+ IMPOSTER_SCHEMA_VERSION,
+ ImposterMetaSchema,
+ type ImposterMeta,
+} from '../schema';
const VALID: ImposterMeta = {
- version: IMPOSTER_SCHEMA_VERSION,
+ version: IMPOSTER_LEGACY_SCHEMA_VERSION,
angles: 16,
tilesX: 4,
tilesY: 4,
@@ -83,4 +88,60 @@ describe('ImposterMetaSchema', () => {
const ok = { ...bad, auxLayers: ['albedo', 'normal'] };
expect(() => ImposterMetaSchema.parse(ok)).not.toThrow();
});
+
+ test('accepts v2 latlon sidecars for forward-compatible static bakes', () => {
+ const decoded = ImposterMetaSchema.parse({ ...VALID, version: IMPOSTER_SCHEMA_VERSION });
+ expect(decoded.version).toBe(IMPOSTER_SCHEMA_VERSION);
+ expect(decoded.layout).toBe('latlon');
+ });
+
+ test('accepts a valid v2 octahedral sidecar', () => {
+ const octa = {
+ ...VALID,
+ version: IMPOSTER_SCHEMA_VERSION,
+ angles: 4,
+ tilesX: 2,
+ tilesY: 2,
+ atlasWidth: 1024,
+ atlasHeight: 1024,
+ axis: 'octahedral',
+ hemi: false,
+ layout: 'octahedral',
+ directionEncoding: 'octahedral',
+ directions: [
+ [1, 0, 0],
+ [0, 1, 0],
+ [0, 0, 1],
+ [-1, 0, 0],
+ ],
+ };
+ delete (octa as Record<string, unknown>).azimuths;
+ delete (octa as Record<string, unknown>).elevations;
+
+ const decoded = ImposterMetaSchema.parse(octa);
+ expect(decoded.version).toBe(2);
+ expect(decoded.layout).toBe('octahedral');
+ if (decoded.layout !== 'octahedral') throw new Error('expected octahedral payload');
+ expect(decoded.directions).toHaveLength(4);
+ });
+
+ test('rejects octahedral sidecars with non-unit directions', () => {
+ const bad = {
+ ...VALID,
+ version: IMPOSTER_SCHEMA_VERSION,
+ angles: 1,
+ tilesX: 1,
+ tilesY: 1,
+ atlasWidth: 512,
+ atlasHeight: 512,
+ axis: 'octahedral',
+ hemi: false,
+ layout: 'octahedral',
+ directionEncoding: 'octahedral',
+ directions: [[2, 0, 0]],
+ };
+ delete (bad as Record<string, unknown>).azimuths;
+ delete (bad as Record<string, unknown>).elevations;
+ expect(() => ImposterMetaSchema.parse(bad)).toThrow();
+ });
});
diff --git a/imposter/__tests__/validate.test.ts b/imposter/__tests__/validate.test.ts
new file mode 100644
index 00000000..b9523cb2
--- /dev/null
+++ b/imposter/__tests__/validate.test.ts
@@ -0,0 +1,128 @@
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { describe, expect, test } from 'bun:test';
+import sharp from 'sharp';
+
+import { validateImposterSidecar } from '../validate';
+
+const BASE_META = {
+ tileSize: 128,
+ worldSize: 1,
+ yOffset: 0.5,
+ projection: 'orthographic',
+ bbox: { min: [0, 0, 0], max: [1, 1, 0] },
+ source: { path: 'one-triangle.glb', bytes: 988, tris: 1 },
+ auxLayers: ['albedo', 'normal', 'depth'],
+ bgColor: 'transparent',
+ colorLayer: 'baseColor',
+ normalSpace: 'capture-view',
+ edgeBleedPx: 2,
+ textureColorSpace: 'srgb',
+} as const;
+
+function makeDir(): string {
+ return mkdtempSync(join(tmpdir(), 'pf-imposter-validate-'));
+}
+
+async function writePng(path: string, width: number, height: number): Promise<void> {
+ const png = await sharp({
+ create: {
+ width,
+ height,
+ channels: 4,
+ background: { r: 80, g: 120, b: 40, alpha: 1 },
+ },
+ }).png().toBuffer();
+ writeFileSync(path, png);
+}
+
+async function writeSidecarSet(dir: string, name: string, meta: unknown): Promise<string> {
+ const sidecar = join(dir, `${name}.json`);
+ writeFileSync(sidecar, JSON.stringify(meta, null, 2), 'utf-8');
+ const m = meta as { atlasWidth: number; atlasHeight: number };
+ await writePng(join(dir, `${name}.png`), m.atlasWidth, m.atlasHeight);
+ await writePng(join(dir, `${name}.normal.png`), m.atlasWidth, m.atlasHeight);
+ await writePng(join(dir, `${name}.depth.png`), m.atlasWidth, m.atlasHeight);
+ return sidecar;
+}
+
+describe('validateImposterSidecar', () => {
+ test('accepts a v1 latlon sidecar and sibling PNGs', async () => {
+ const dir = makeDir();
+ const meta = {
+ version: 1,
+ angles: 16,
+ tilesX: 4,
+ tilesY: 4,
+ atlasWidth: 512,
+ atlasHeight: 512,
+ axis: 'hemi-y',
+ hemi: true,
+ layout: 'latlon',
+ azimuths: [0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2],
+ elevations: [1.4, 1.0, 0.5, 0.1],
+ ...BASE_META,
+ };
+ const sidecar = await writeSidecarSet(dir, 'latlon', meta);
+
+ const result = await validateImposterSidecar(sidecar);
+ expect(result.ok).toBe(true);
+ expect(result.meta?.version).toBe(1);
+ expect(result.meta?.layout).toBe('latlon');
+ });
+
+ test('accepts a v2 octahedral sidecar with unit directions', async () => {
+ const dir = makeDir();
+ const meta = {
+ version: 2,
+ angles: 4,
+ tilesX: 2,
+ tilesY: 2,
+ atlasWidth: 256,
+ atlasHeight: 256,
+ axis: 'octahedral',
+ hemi: false,
+ layout: 'octahedral',
+ directionEncoding: 'octahedral',
+ directions: [
+ [1, 0, 0],
+ [0, 1, 0],
+ [0, 0, 1],
+ [-1, 0, 0],
+ ],
+ ...BASE_META,
+ };
+ const sidecar = await writeSidecarSet(dir, 'octa', meta);
+
+ const result = await validateImposterSidecar(sidecar);
+ expect(result.ok).toBe(true);
+ expect(result.meta?.version).toBe(2);
+ expect(result.meta?.layout).toBe('octahedral');
+ });
+
+ test('flags sibling PNG dimension mismatches', async () => {
+ const dir = makeDir();
+ const meta = {
+ version: 1,
+ angles: 8,
+ tilesX: 4,
+ tilesY: 2,
+ atlasWidth: 512,
+ atlasHeight: 256,
+ axis: 'hemi-y',
+ hemi: true,
+ layout: 'latlon',
+ azimuths: [0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2],
+ elevations: [1.0, 0.2],
+ ...BASE_META,
+ };
+ const sidecar = await writeSidecarSet(dir, 'bad-png', meta);
+ await writePng(join(dir, 'bad-png.normal.png'), 128, 128);
+
+ const result = await validateImposterSidecar(sidecar);
+ expect(result.ok).toBe(false);
+ expect(result.issues.some((issue) => issue.message.includes('PNG dimensions'))).toBe(true);
+ });
+});
diff --git a/imposter/animated-bake.ts b/imposter/animated-bake.ts
index 67b4cc84..bd07291c 100644
--- a/imposter/animated-bake.ts
+++ b/imposter/animated-bake.ts
@@ -26,6 +26,7 @@ import {
type AnimatedImposterPreBakeReport,
} from './animated-validate';
import type { ResolvedClip } from './clip-resolver';
+import { enumerateOctahedralTiles } from './projection';
export interface AnimatedTileCamera {
i: number;
@@ -98,18 +99,7 @@ interface BrowserAttachmentInput extends Omit<AnimatedImposterAttachment, 'glb'>
}
export function enumerateOctahedralGrid(x: number, y: number): AnimatedTileCamera[] {
- if (!Number.isInteger(x) || !Number.isInteger(y) || x <= 0 || y <= 0) {
- throw new Error('octahedral grid dimensions must be positive integers');
- }
- const out: AnimatedTileCamera[] = [];
- for (let j = 0; j < y; j++) {
- for (let i = 0; i < x; i++) {
- const u = ((i + 0.5) / x) * 2 - 1;
- const v = 1 - ((j + 0.5) / y) * 2;
- out.push({ i, j, u, v, dir: octaDecode(u, v) });
- }
- }
- return out;
+ return enumerateOctahedralTiles({ x, y });
}
export async function openAnimatedImposterSession(): Promise<AnimatedImposterSession> {
@@ -385,21 +375,6 @@ function chooseFrameGrid(layerCount: number): { framesX: number; framesY: number
return { framesX: best.framesX, framesY: best.framesY };
}
-function octaDecode(u: number, v: number): [number, number, number] {
- let x = u;
- const y = 1 - Math.abs(u) - Math.abs(v);
- let z = v;
-
- if (y < 0) {
- const oldX = x;
- x = (1 - Math.abs(z)) * Math.sign(oldX || 1);
- z = (1 - Math.abs(oldX)) * Math.sign(z || 1);
- }
-
- const len = Math.hypot(x, y, z) || 1;
- return [x / len, y / len, z / len];
-}
-
function buildAnimatedHarnessHtml(): string {
return `<!DOCTYPE html>
<html><head>
diff --git a/imposter/bake.ts b/imposter/bake.ts
index 1a0f74b8..e5b7259d 100644
--- a/imposter/bake.ts
+++ b/imposter/bake.ts
@@ -1,10 +1,11 @@
/**
* Imposter baker — renders a GLB from N camera angles into a packed atlas.
*
- * Backend: Playwright + Chromium (same pattern as scripts/visual-audit.ts).
+ * Backend: Playwright + Chromium.
* 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.
+ * no WebGL, so actual pixel output requires a real browser context. The public
+ * pixelforge CLI runs this path through Node, which is Playwright's supported
+ * JavaScript runtime across Windows, macOS, and Linux.
*
* Strategy:
* 1. Launch one Chromium page per session (ImposterSession).
@@ -19,24 +20,34 @@
*/
import { Buffer } from 'node:buffer';
-import { readFileSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { dirname, extname, resolve, sep } from 'node:path';
import sharp from 'sharp';
import { chromium, type Page } from 'playwright';
import type {
ImposterAngleCount,
ImposterAuxLayer,
- ImposterAxis,
ImposterBgColor,
ImposterColorLayer,
+ ImposterLayout,
ImposterMeta,
+ LatLonImposterAxis,
} from './schema';
-import { IMPOSTER_SCHEMA_VERSION } from './schema';
-import { enumerateTiles, resolveLayout } from './projection';
+import { IMPOSTER_LEGACY_SCHEMA_VERSION, IMPOSTER_SCHEMA_VERSION, ImposterMetaSchema } from './schema';
+import { enumerateOctahedralTiles, enumerateTiles, resolveLayout } from './projection';
+
+const HARNESS_ORIGIN = 'https://pixel-forge-kiln.local';
+const nodeRequire = createRequire(import.meta.url);
export interface BakeImposterOptions {
- angles: ImposterAngleCount;
- axis?: ImposterAxis;
+ angles?: ImposterAngleCount;
+ axis?: LatLonImposterAxis | 'octahedral';
+ /** Tile layout. Defaults to lat/lon unless axis is the octahedral compatibility alias. */
+ layout?: ImposterLayout;
+ /** Octahedral grid dimensions. Defaults to 8x8 when layout='octahedral'. */
+ grid?: { x: number; y: number };
/** 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. */
@@ -49,6 +60,8 @@ export interface BakeImposterOptions {
edgeBleedPx?: number;
/** Included in meta.source.path for provenance. */
sourcePath?: string;
+ /** Pin deterministic browser and PNG settings where Chromium permits it. */
+ deterministic?: boolean;
}
export interface BakeImposterResult {
@@ -65,12 +78,28 @@ export interface ImposterSession {
close(): Promise<void>;
}
+export interface OpenImposterSessionOptions {
+ deterministic?: boolean;
+}
+
/** Spin up a reusable Playwright session. Call close() when you're done batching. */
-export async function openImposterSession(): Promise<ImposterSession> {
- const browser = await chromium.launch();
+export async function openImposterSession(opts: OpenImposterSessionOptions = {}): Promise<ImposterSession> {
+ assertSupportedBrowserBakeRuntime();
+ const browser = await chromium.launch({
+ ...(opts.deterministic
+ ? {
+ args: [
+ '--disable-gpu',
+ '--use-angle=swiftshader-webgl',
+ '--use-gl=angle',
+ ],
+ }
+ : {}),
+ });
const ctx = await browser.newContext({ viewport: { width: 1024, height: 1024 }, deviceScaleFactor: 1 });
const page = await ctx.newPage();
- await page.setContent(buildHarnessHtml());
+ await installHarnessRoutes(page);
+ await page.setContent(buildHarnessHtml({ deterministic: Boolean(opts.deterministic) }));
await page.waitForFunction(
() => (globalThis as unknown as { __imposterReady?: boolean }).__imposterReady === true,
{ timeout: 30_000 },
@@ -85,12 +114,21 @@ export async function openImposterSession(): Promise<ImposterSession> {
};
}
+function assertSupportedBrowserBakeRuntime(): void {
+ const isBun = Boolean((globalThis as { Bun?: unknown }).Bun);
+ if (isBun && process.platform === 'win32') {
+ throw new Error(
+ 'Playwright-backed imposter baking is not supported through Bun on Windows. Build and run the public Node CLI instead: bun run --filter @pixel-forge/cli build && node packages/cli/dist/index.js kiln bake-imposter ...',
+ );
+ }
+}
+
/** Convenience: one-shot bake. Internally opens + closes a session. */
export async function bakeImposter(
glb: Buffer | string,
opts: BakeImposterOptions,
): Promise<BakeImposterResult> {
- const session = await openImposterSession();
+ const session = await openImposterSession({ deterministic: opts.deterministic });
try {
return await session.bake(glb, opts);
} finally {
@@ -107,8 +145,7 @@ async function bakeOnPage(
glb: Buffer | string,
opts: BakeImposterOptions,
): Promise<BakeImposterResult> {
- const angles = opts.angles;
- const axis: ImposterAxis = opts.axis ?? (angles === 16 ? 'y' : 'hemi-y');
+ const requestedLayout: ImposterLayout = opts.layout ?? (opts.axis === 'octahedral' ? 'octahedral' : 'latlon');
const tileSize = opts.tileSize ?? 512;
const auxLayers = uniqueAuxLayers(opts.auxLayers ?? []);
const bgColor: ImposterBgColor = opts.bgColor ?? 'transparent';
@@ -125,8 +162,10 @@ async function bakeOnPage(
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);
+ const resolved = resolveBakeLayout(opts, requestedLayout);
+ const tiles = resolved.layout === 'octahedral'
+ ? enumerateOctahedralTiles(resolved.grid)
+ : enumerateTiles(resolved.latLon);
// Load the GLB into the harness and pull back bbox + tri count.
const loadInfo = (await page.evaluate(
@@ -161,7 +200,7 @@ async function bakeOnPage(
const png = Buffer.from(dataUrl.split(',')[1]!, 'base64');
tilePngs.push(png);
}
- atlases[layer] = await composeAtlas(tilePngs, tileSize, layout.tilesX, layout.tilesY, bgColor, edgeBleedPx);
+ atlases[layer] = await composeAtlas(tilePngs, tileSize, resolved.tilesX, resolved.tilesY, bgColor, edgeBleedPx);
}
const albedo = atlases.albedo!;
@@ -180,22 +219,16 @@ async function bakeOnPage(
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,
+ const common = {
+ angles: resolved.angles,
+ tilesX: resolved.tilesX,
+ tilesY: resolved.tilesY,
tileSize,
- atlasWidth: layout.tilesX * tileSize,
- atlasHeight: layout.tilesY * tileSize,
+ atlasWidth: resolved.tilesX * tileSize,
+ atlasHeight: resolved.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 } : {}),
@@ -208,11 +241,82 @@ async function bakeOnPage(
normalSpace: 'capture-view',
edgeBleedPx,
textureColorSpace: 'srgb',
- };
+ } as const;
+
+ const metaPayload = resolved.layout === 'octahedral'
+ ? {
+ version: IMPOSTER_SCHEMA_VERSION,
+ ...common,
+ axis: 'octahedral',
+ hemi: false,
+ layout: 'octahedral',
+ directionEncoding: 'octahedral',
+ directions: tiles.map((tile) => tile.dir),
+ }
+ : {
+ version: IMPOSTER_LEGACY_SCHEMA_VERSION,
+ ...common,
+ axis: resolved.latLon.axis,
+ hemi: resolved.latLon.axis === 'hemi-y',
+ layout: 'latlon',
+ azimuths: resolved.latLon.azimuths,
+ elevations: resolved.latLon.elevations,
+ };
+ ImposterMetaSchema.parse(metaPayload);
+ const meta = metaPayload as ImposterMeta;
return { atlas: albedo, aux, meta };
}
+type ResolvedBakeLayout =
+ | {
+ layout: 'latlon';
+ angles: ImposterAngleCount;
+ tilesX: number;
+ tilesY: number;
+ latLon: ReturnType<typeof resolveLayout>;
+ }
+ | {
+ layout: 'octahedral';
+ angles: number;
+ tilesX: number;
+ tilesY: number;
+ grid: { x: number; y: number };
+ };
+
+function resolveBakeLayout(
+ opts: BakeImposterOptions,
+ layout: ImposterLayout,
+): ResolvedBakeLayout {
+ if (layout === 'octahedral') {
+ const grid = opts.grid ?? { x: 8, y: 8 };
+ if (!Number.isInteger(grid.x) || !Number.isInteger(grid.y) || grid.x <= 0 || grid.y <= 0) {
+ throw new Error(`octahedral grid must be positive integers (got ${grid.x}x${grid.y})`);
+ }
+ return {
+ layout,
+ angles: grid.x * grid.y,
+ tilesX: grid.x,
+ tilesY: grid.y,
+ grid,
+ };
+ }
+
+ if (opts.axis === 'octahedral') {
+ throw new Error("axis='octahedral' requires layout='octahedral'");
+ }
+ const angles = opts.angles ?? 16;
+ const axis: LatLonImposterAxis = opts.axis ?? (angles === 16 ? 'y' : 'hemi-y');
+ const latLon = resolveLayout(angles, axis);
+ return {
+ layout,
+ angles,
+ tilesX: latLon.tilesX,
+ tilesY: latLon.tilesY,
+ latLon,
+ };
+}
+
async function composeAtlas(
tilePngs: Buffer[],
tileSize: number,
@@ -242,7 +346,7 @@ async function composeAtlas(
create: { width, height, channels: 4, background: bg },
})
.composite(composites)
- .png()
+ .png({ compressionLevel: 9, adaptiveFiltering: false })
.toBuffer();
return bgColor === 'transparent' && edgeBleedPx > 0
@@ -259,6 +363,42 @@ function uniqueAuxLayers(layers: ImposterAuxLayer[]): ImposterAuxLayer[] {
return out;
}
+async function installHarnessRoutes(page: Page): Promise<void> {
+ const threeRoot = dirname(dirname(nodeRequire.resolve('three')));
+ await page.route(`${HARNESS_ORIGIN}/three/**`, async (route) => {
+ const url = new URL(route.request().url());
+ const rel = decodeURIComponent(url.pathname.replace(/^\/three\//, ''));
+ const filePath = resolve(threeRoot, rel);
+ const rootWithSep = threeRoot.endsWith(sep) ? threeRoot : `${threeRoot}${sep}`;
+ if (filePath !== threeRoot && !filePath.startsWith(rootWithSep)) {
+ await route.abort();
+ return;
+ }
+ if (!existsSync(filePath)) {
+ await route.abort();
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: contentTypeFor(filePath),
+ body: readFileSync(filePath),
+ });
+ });
+}
+
+function contentTypeFor(filePath: string): string {
+ switch (extname(filePath).toLowerCase()) {
+ case '.js':
+ return 'application/javascript';
+ case '.wasm':
+ return 'application/wasm';
+ case '.json':
+ return 'application/json';
+ default:
+ return 'application/octet-stream';
+ }
+}
+
export async function bleedTransparentRgb(png: Buffer, radius: number): Promise<Buffer> {
if (radius <= 0) return png;
const { data, info } = await sharp(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
@@ -308,14 +448,17 @@ export async function bleedTransparentRgb(png: Buffer, radius: number): Promise<
dst = tmp;
}
- return sharp(src, { raw: { width, height, channels: 4 } }).png().toBuffer();
+ return sharp(src, { raw: { width, height, channels: 4 } })
+ .png({ compressionLevel: 9, adaptiveFiltering: false })
+ .toBuffer();
}
// ============================================================================
-// In-browser harness — three.js 0.184 from CDN, with loader + render helpers.
+// In-browser harness - local three.js modules, with loader + render helpers.
// ============================================================================
-function buildHarnessHtml(): string {
+function buildHarnessHtml(opts: { deterministic: boolean }): string {
+ const antialias = opts.deterministic ? 'false' : 'true';
return `<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
@@ -323,8 +466,8 @@ function buildHarnessHtml(): string {
<script type="importmap">
{
"imports": {
- "three": "https://unpkg.com/[email protected]/build/three.module.js",
- "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
+ "three": "${HARNESS_ORIGIN}/three/build/three.module.js",
+ "three/addons/": "${HARNESS_ORIGIN}/three/examples/jsm/"
}
}
</script>
@@ -334,10 +477,11 @@ function buildHarnessHtml(): string {
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
const W = () => renderer.domElement.width;
const app = document.getElementById('app');
-const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
+const renderer = new THREE.WebGLRenderer({ antialias: ${antialias}, alpha: true, preserveDrawingBuffer: true });
renderer.setPixelRatio(1);
renderer.setSize(1024, 1024);
renderer.outputColorSpace = THREE.SRGBColorSpace;
@@ -367,6 +511,9 @@ window.__imposterLoadGlb = async (dataUrl, tileSize) => {
renderer.setSize(tileSize, tileSize);
}
const loader = new GLTFLoader();
+ const dracoLoader = new DRACOLoader();
+ dracoLoader.setDecoderPath('${HARNESS_ORIGIN}/three/examples/jsm/libs/draco/');
+ loader.setDRACOLoader(dracoLoader);
return new Promise((resolve, reject) => {
loader.load(dataUrl, (gltf) => {
root = gltf.scene;
@@ -447,6 +594,7 @@ window.__imposterRenderTile = ({ dir, layer, bgColor, colorLayer, tileSize }) =>
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);
+ if (Math.abs(d.dot(camera.up)) > 0.97) camera.up.set(0, 0, 1);
camera.lookAt(boundsCenter);
// Background.
diff --git a/imposter/index.ts b/imposter/index.ts
index b52bd82f..cf7a50a0 100644
--- a/imposter/index.ts
+++ b/imposter/index.ts
@@ -10,7 +10,12 @@
*/
export { bakeImposter, openImposterSession } from './bake';
-export type { BakeImposterOptions, BakeImposterResult, ImposterSession } from './bake';
+export type {
+ BakeImposterOptions,
+ BakeImposterResult,
+ ImposterSession,
+ OpenImposterSessionOptions,
+} from './bake';
export {
ATLAS_PROFILES,
@@ -18,6 +23,13 @@ export {
isAtlasProfileName,
validateAgainstAtlasProfile,
} from './atlas-profiles';
+
+export { validateImposterSidecar } from './validate';
+export type {
+ ImposterValidationIssue,
+ ImposterValidationResult,
+ ValidateImposterOptions,
+} from './validate';
export type {
AtlasProfileLimits,
AtlasProfileMetaInput,
@@ -28,6 +40,7 @@ export type {
} from './atlas-profiles';
export {
+ IMPOSTER_LEGACY_SCHEMA_VERSION,
IMPOSTER_SCHEMA_VERSION,
ImposterMetaSchema,
} from './schema';
@@ -48,6 +61,7 @@ export type {
ImposterMeta,
ImposterAngleCount,
ImposterAxis,
+ LatLonImposterAxis,
ImposterLayout,
ImposterAuxLayer,
ImposterBgColor,
@@ -67,8 +81,20 @@ export type {
AnimatedImposterWarning,
} from './animated-schema';
-export { resolveLayout, enumerateTiles, dirFromAzEl } from './projection';
-export type { TileCamera, TileLayout } from './projection';
+export {
+ dirFromAzEl,
+ enumerateOctahedralTiles,
+ enumerateTiles,
+ octaDecode,
+ octaEncode,
+ resolveLayout,
+} from './projection';
+export type {
+ OctahedralGrid,
+ OctahedralTileCamera,
+ TileCamera,
+ TileLayout,
+} from './projection';
export {
resolveClips,
diff --git a/imposter/projection.ts b/imposter/projection.ts
index 1766ded2..5c81b4a2 100644
--- a/imposter/projection.ts
+++ b/imposter/projection.ts
@@ -42,6 +42,24 @@ export interface TileLayout {
axis: ImposterAxis;
}
+export interface OctahedralGrid {
+ x: number;
+ y: number;
+}
+
+export interface OctahedralTileCamera {
+ /** Tile column (0 = leftmost). */
+ i: number;
+ /** Tile row (0 = topmost). */
+ j: number;
+ /** Octahedral encoded U coordinate at tile center, -1..1. */
+ u: number;
+ /** Octahedral encoded V coordinate at tile center, -1..1. */
+ v: number;
+ /** Unit direction FROM target center TOWARD camera. */
+ dir: [number, number, number];
+}
+
/**
* Resolve grid dimensions + angle sequences for a given (angles, axis) combo.
* Throws on unsupported combinations.
@@ -125,6 +143,56 @@ export function dirFromAzEl(az: number, el: number): [number, number, number] {
return [x, y, z];
}
+/** Enumerate an octahedral atlas grid, left-to-right top-to-bottom. */
+export function enumerateOctahedralTiles(grid: OctahedralGrid): OctahedralTileCamera[] {
+ if (!Number.isInteger(grid.x) || !Number.isInteger(grid.y) || grid.x <= 0 || grid.y <= 0) {
+ throw new Error('octahedral grid dimensions must be positive integers');
+ }
+ const out: OctahedralTileCamera[] = [];
+ for (let j = 0; j < grid.y; j++) {
+ for (let i = 0; i < grid.x; i++) {
+ const u = ((i + 0.5) / grid.x) * 2 - 1;
+ const v = 1 - ((j + 0.5) / grid.y) * 2;
+ out.push({ i, j, u, v, dir: octaDecode(u, v) });
+ }
+ }
+ return out;
+}
+
+/**
+ * Decode 2D octahedral coordinates into a Kiln world-frame direction.
+ * The Y component is world-up, matching the animated imposter baker.
+ */
+export function octaDecode(u: number, v: number): [number, number, number] {
+ let x = u;
+ const y = 1 - Math.abs(u) - Math.abs(v);
+ let z = v;
+ if (y < 0) {
+ const ox = x;
+ x = (1 - Math.abs(z)) * Math.sign(ox || 1);
+ z = (1 - Math.abs(ox)) * Math.sign(z || 1);
+ }
+ const len = Math.hypot(x, y, z) || 1;
+ return [x / len, y / len, z / len];
+}
+
+/** Encode a Kiln world-frame direction into octahedral coordinates. */
+export function octaEncode(dir: [number, number, number]): [number, number] {
+ const len = Math.hypot(dir[0], dir[1], dir[2]) || 1;
+ let x = dir[0] / len;
+ const y = dir[1] / len;
+ let z = dir[2] / len;
+ const denom = Math.abs(x) + Math.abs(y) + Math.abs(z) || 1;
+ x /= denom;
+ z /= denom;
+ if (y < 0) {
+ const ox = x;
+ x = (1 - Math.abs(z)) * Math.sign(ox || 1);
+ z = (1 - Math.abs(ox)) * Math.sign(z || 1);
+ }
+ return [x, z];
+}
+
function evenAzimuths(count: number): number[] {
const out: number[] = [];
for (let i = 0; i < count; i++) out.push((i / count) * Math.PI * 2);
diff --git a/imposter/schema.ts b/imposter/schema.ts
index 6f3aa056..c1cfafde 100644
--- a/imposter/schema.ts
+++ b/imposter/schema.ts
@@ -7,16 +7,18 @@
* - 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.
+ * Static lat/lon sidecars shipped as version 1. Version 2 adds static
+ * octahedral layouts while keeping v1 lat/lon readers valid.
*/
import { z } from 'zod';
-export const IMPOSTER_SCHEMA_VERSION = 1 as const;
+export const IMPOSTER_LEGACY_SCHEMA_VERSION = 1 as const;
+export const IMPOSTER_SCHEMA_VERSION = 2 as const;
export type ImposterAngleCount = 8 | 16 | 32;
-export type ImposterAxis = 'y' | 'hemi-y';
+export type LatLonImposterAxis = 'y' | 'hemi-y';
+export type ImposterAxis = LatLonImposterAxis | 'octahedral';
export type ImposterLayout = 'latlon' | 'octahedral';
export type ImposterAuxLayer = 'albedo' | 'normal' | 'depth';
export type ImposterBgColor = 'magenta' | 'transparent';
@@ -24,11 +26,21 @@ export type ImposterColorLayer = 'baseColor' | 'beauty';
export type ImposterNormalSpace = 'capture-view';
export type ImposterTextureColorSpace = 'srgb';
-export const ImposterMetaSchema = z.object({
- version: z.literal(IMPOSTER_SCHEMA_VERSION),
+const finiteNumber = z.number().finite();
+const directionTuple = z.tuple([finiteNumber, finiteNumber, finiteNumber]);
+const bboxSchema = z.object({
+ min: z.tuple([finiteNumber, finiteNumber, finiteNumber]),
+ max: z.tuple([finiteNumber, finiteNumber, finiteNumber]),
+});
+const sourceSchema = z.object({
+ path: z.string().optional(),
+ bytes: z.number().int().nonnegative(),
+ tris: z.number().int().nonnegative(),
+});
+const commonMetaSchema = z.object({
/** Total viewpoints baked into the atlas. */
- angles: z.union([z.literal(8), z.literal(16), z.literal(32)]),
+ angles: z.number().int().positive(),
/** Atlas grid dimensions — tiles across / down. */
tilesX: z.number().int().positive(),
tilesY: z.number().int().positive(),
@@ -41,41 +53,24 @@ export const ImposterMetaSchema = z.object({
/** 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(),
+ yOffset: finiteNumber,
/** 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'. */
+ /** Axis convention. 'y' = full sphere, 'hemi-y' = upper hemi, 'octahedral' = octa map. */
+ axis: z.enum(['y', 'hemi-y', 'octahedral']),
+ /** Redundant helper for shaders - true if axis === 'hemi-y'. False for octahedral. */
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()]),
- }),
+ bbox: bboxSchema,
/** Source mesh stats for provenance. */
- source: z.object({
- path: z.string().optional(),
- bytes: z.number().int().nonnegative(),
- tris: z.number().int().nonnegative(),
- }),
+ source: sourceSchema,
/** Auxiliary layers packed alongside albedo (as separate PNGs). */
auxLayers: z.array(z.enum(['albedo', 'normal', 'depth'])),
@@ -91,7 +86,36 @@ export const ImposterMetaSchema = z.object({
edgeBleedPx: z.number().int().nonnegative().default(0),
/** Color atlas storage space. PNG color layers are authored as sRGB. */
textureColorSpace: z.literal('srgb').default('srgb'),
-}).superRefine((meta, ctx) => {
+});
+
+const latLonMetaSchema = commonMetaSchema.extend({
+ version: z.union([z.literal(IMPOSTER_LEGACY_SCHEMA_VERSION), z.literal(IMPOSTER_SCHEMA_VERSION)]),
+ angles: z.union([z.literal(8), z.literal(16), z.literal(32)]),
+ axis: z.enum(['y', 'hemi-y']),
+ layout: z.literal('latlon'),
+ /**
+ * 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()),
+});
+
+const octahedralMetaSchema = commonMetaSchema.extend({
+ version: z.literal(IMPOSTER_SCHEMA_VERSION),
+ axis: z.literal('octahedral'),
+ hemi: z.literal(false),
+ layout: z.literal('octahedral'),
+ directionEncoding: z.literal('octahedral'),
+ /** Per-tile unit direction vectors, row-major, from target center toward camera. */
+ directions: z.array(directionTuple),
+});
+
+function refineCommon(meta: z.infer<typeof commonMetaSchema>, ctx: z.RefinementCtx): void {
if (meta.colorLayer === 'baseColor' && !meta.auxLayers.includes('normal')) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
@@ -99,6 +123,61 @@ export const ImposterMetaSchema = z.object({
message: "baseColor production imposters must include a 'normal' aux layer",
});
}
-});
+ if (meta.atlasWidth !== meta.tilesX * meta.tileSize) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['atlasWidth'],
+ message: 'atlasWidth must equal tilesX * tileSize',
+ });
+ }
+ if (meta.atlasHeight !== meta.tilesY * meta.tileSize) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['atlasHeight'],
+ message: 'atlasHeight must equal tilesY * tileSize',
+ });
+ }
+}
+
+export const ImposterMetaSchema = z.union([
+ latLonMetaSchema.superRefine((meta, ctx) => {
+ refineCommon(meta, ctx);
+ if (meta.azimuths.length !== meta.tilesX) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['azimuths'],
+ message: 'azimuths length must match tilesX',
+ });
+ }
+ if (meta.elevations.length !== meta.tilesY) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['elevations'],
+ message: 'elevations length must match tilesY',
+ });
+ }
+ }),
+ octahedralMetaSchema.superRefine((meta, ctx) => {
+ refineCommon(meta, ctx);
+ if (meta.directions.length !== meta.tilesX * meta.tilesY) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['directions'],
+ message: 'directions length must match tilesX * tilesY',
+ });
+ }
+ for (let idx = 0; idx < meta.directions.length; idx++) {
+ const dir = meta.directions[idx]!;
+ const len = Math.hypot(dir[0], dir[1], dir[2]);
+ if (Math.abs(len - 1) > 1e-4) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['directions', idx],
+ message: 'direction must be a unit vector',
+ });
+ }
+ }
+ }),
+]);
export type ImposterMeta = z.infer<typeof ImposterMetaSchema>;
diff --git a/imposter/validate.ts b/imposter/validate.ts
new file mode 100644
index 00000000..7fb7908c
--- /dev/null
+++ b/imposter/validate.ts
@@ -0,0 +1,154 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { extname, resolve } from 'node:path';
+import sharp from 'sharp';
+
+import {
+ isAtlasProfileName,
+ validateAgainstAtlasProfile,
+ type AtlasProfileName,
+ type AtlasProfileValidationResult,
+ type AtlasProfileViolation,
+} from './atlas-profiles';
+import { ImposterMetaSchema, type ImposterAuxLayer, type ImposterMeta } from './schema';
+
+export interface ImposterValidationIssue {
+ field: string;
+ message: string;
+}
+
+export interface ValidateImposterOptions {
+ profile?: AtlasProfileName;
+ checkFiles?: boolean;
+}
+
+export interface ImposterValidationResult {
+ ok: boolean;
+ sidecarPath: string;
+ meta: ImposterMeta | null;
+ issues: ImposterValidationIssue[];
+ profile?: AtlasProfileValidationResult;
+}
+
+export async function validateImposterSidecar(
+ sidecarPathInput: string,
+ opts: ValidateImposterOptions = {},
+): Promise<ImposterValidationResult> {
+ const sidecarPath = resolve(sidecarPathInput);
+ const issues: ImposterValidationIssue[] = [];
+
+ let raw: unknown;
+ try {
+ raw = JSON.parse(readFileSync(sidecarPath, 'utf-8'));
+ } catch (err) {
+ return {
+ ok: false,
+ sidecarPath,
+ meta: null,
+ issues: [{ field: 'sidecar', message: err instanceof Error ? err.message : String(err) }],
+ };
+ }
+
+ const parsed = ImposterMetaSchema.safeParse(raw);
+ if (!parsed.success) {
+ return {
+ ok: false,
+ sidecarPath,
+ meta: null,
+ issues: parsed.error.issues.map((issue) => ({
+ field: issue.path.join('.') || 'sidecar',
+ message: issue.message,
+ })),
+ };
+ }
+
+ const meta = parsed.data;
+ validateBbox(meta, issues);
+ if (meta.angles !== meta.tilesX * meta.tilesY) {
+ issues.push({
+ field: 'angles',
+ message: 'angles must match tilesX * tilesY',
+ });
+ }
+
+ let profile: AtlasProfileValidationResult | undefined;
+ if (opts.profile) {
+ if (!isAtlasProfileName(opts.profile)) {
+ issues.push({ field: 'profile', message: `unknown atlas profile: ${opts.profile}` });
+ } else {
+ profile = validateAgainstAtlasProfile(meta, opts.profile);
+ for (const violation of profile.violations) {
+ issues.push(profileViolationToIssue(violation));
+ }
+ }
+ }
+
+ if (opts.checkFiles !== false) {
+ await validatePngFiles(sidecarPath, meta, issues);
+ }
+
+ return {
+ ok: issues.length === 0,
+ sidecarPath,
+ meta,
+ issues,
+ ...(profile ? { profile } : {}),
+ };
+}
+
+function validateBbox(meta: ImposterMeta, issues: ImposterValidationIssue[]): void {
+ const { min, max } = meta.bbox;
+ for (let axis = 0; axis < 3; axis++) {
+ const lo = min[axis]!;
+ const hi = max[axis]!;
+ if (!(hi >= lo)) {
+ issues.push({
+ field: `bbox.${axis}`,
+ message: 'bbox max must be greater than or equal to min',
+ });
+ }
+ }
+}
+
+async function validatePngFiles(
+ sidecarPath: string,
+ meta: ImposterMeta,
+ issues: ImposterValidationIssue[],
+): Promise<void> {
+ const base = sidecarPath.replace(new RegExp(`${escapeRegExp(extname(sidecarPath))}$`), '');
+ const expected = { width: meta.atlasWidth, height: meta.atlasHeight };
+ await validatePng(`${base}.png`, 'albedo', expected, issues);
+ for (const layer of meta.auxLayers) {
+ if (layer === 'albedo') continue;
+ await validatePng(`${base}.${layer}.png`, layer, expected, issues);
+ }
+}
+
+async function validatePng(
+ filePath: string,
+ layer: ImposterAuxLayer,
+ expected: { width: number; height: number },
+ issues: ImposterValidationIssue[],
+): Promise<void> {
+ if (!existsSync(filePath)) {
+ issues.push({ field: `auxLayers.${layer}`, message: `missing PNG: ${filePath}` });
+ return;
+ }
+ const meta = await sharp(filePath).metadata();
+ if (meta.width !== expected.width || meta.height !== expected.height) {
+ issues.push({
+ field: `auxLayers.${layer}`,
+ message: `PNG dimensions ${meta.width}x${meta.height} do not match sidecar ${expected.width}x${expected.height}`,
+ });
+ }
+}
+
+function profileViolationToIssue(violation: AtlasProfileViolation): ImposterValidationIssue {
+ return {
+ field: `profile.${violation.field}`,
+ message: violation.message,
+ };
+}
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
diff --git a/index.ts b/index.ts
index fadab75a..29b4d9a0 100644
--- a/index.ts
+++ b/index.ts
@@ -188,9 +188,13 @@ export type {
BakeImposterOptions,
BakeImposterResult,
ImposterSession,
+ OpenImposterSessionOptions,
+ ImposterValidationIssue,
+ ImposterValidationResult,
ImposterMeta,
ImposterAngleCount,
ImposterAxis,
+ LatLonImposterAxis,
ImposterLayout,
ImposterAuxLayer,
ImposterBgColor,
@@ -223,6 +227,7 @@ export type {
NpcCharacterPackManifest,
NpcCharacterPackOutputMetrics,
NpcCharacterPackValidationReport,
+ ValidateImposterOptions,
ValidateNpcCharacterPackOptions,
} from './imposter';
export {
@@ -240,11 +245,19 @@ export {
ATLAS_PROFILES,
ATLAS_PROFILE_NAMES,
ImposterMetaSchema,
+ IMPOSTER_LEGACY_SCHEMA_VERSION,
IMPOSTER_SCHEMA_VERSION,
+ dirFromAzEl,
+ enumerateOctahedralTiles,
+ enumerateTiles,
estimateAnimatedImposterStorage,
isAtlasProfileName,
+ octaDecode,
+ octaEncode,
+ resolveLayout,
validateAgainstAtlasProfile,
validateAnimatedImposterPreBake,
+ validateImposterSidecar,
bakeAnimatedImposter,
enumerateOctahedralGrid,
openAnimatedImposterSession,
diff --git a/primitives.ts b/primitives.ts
index bd3a9316..f420b184 100644
--- a/primitives.ts
+++ b/primitives.ts
@@ -10,6 +10,12 @@
*/
import * as THREE from 'three';
+import * as gears from './gears';
+import * as ops from './ops';
+import * as solids from './solids';
+import * as textures from './textures';
+import * as uv from './uv';
+import * as uvShapes from './uv-shapes';
type Vec3Tuple = [number, number, number];
@@ -1057,25 +1063,8 @@ export function validateAsset(
export function buildSandboxGlobals(
usage?: Record<string, number>
): Record<string, unknown> {
- // CSG ops are async — the executor awaits build() so agents can
- // `await boolDiff(...)` inside build().
- //
- // Lazy-required at call-time so the Three.js-only path doesn't pay the
- // manifold WASM init unless an agent actually uses CSG.
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const solids = require('./solids') as typeof import('./solids');
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const ops = require('./ops') as typeof import('./ops');
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const uv = require('./uv') as typeof import('./uv');
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const textures = require('./textures') as typeof import('./textures');
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const gears = require('./gears') as typeof import('./gears');
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const uvShapes = require('./uv-shapes') as typeof import('./uv-shapes');
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const THREE = require('three') as typeof import('three');
+ // CSG ops remain lazy at their own call sites, so importing the wrapper here
+ // is safe for Node ESM builds and still avoids manifold WASM init unless used.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const wrap = <F extends (...args: any[]) => any>(name: string, fn: F): F => {
diff --git a/textures.ts b/textures.ts
index 9d87298c..b8b5a9f2 100644
--- a/textures.ts
+++ b/textures.ts
@@ -9,9 +9,6 @@
*/
import * as THREE from 'three';
-import { readFileSync } from 'node:fs';
-import path from 'node:path';
-import sharp from 'sharp';
export type TextureSource = string | Buffer | Uint8Array;
@@ -36,15 +33,18 @@ export interface EncodedTextureData {
export async function loadTexture(source: TextureSource): Promise<THREE.DataTexture> {
let bytes: Uint8Array;
if (typeof source === 'string') {
+ const fs = await import('node:fs');
+ const path = await import('node:path');
const abs = path.isAbsolute(source) ? source : path.resolve(source);
- bytes = new Uint8Array(readFileSync(abs));
- } else if (Buffer.isBuffer(source)) {
+ bytes = new Uint8Array(fs.readFileSync(abs));
+ } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(source)) {
bytes = new Uint8Array(source);
} else {
bytes = source;
}
const mime = sniffMime(bytes);
+ const sharp = (await import('sharp')).default;
// Decode to RGBA via sharp so we have a live Texture for editor preview
// and for any client-side work (projection baking, normal-map inspect).