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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(material): export a material's maps as tiling textures with a planar preview (#246)
Matt Kissinger722ef5c5105d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b8705fce..6ac04a20 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -92,6 +92,16 @@ does not publish a package.crosses the boundary, and `PROFILE_BEVEL_COLLAPSE` still names an over-large bevel. Thegeneric rejection now says that `kiln_validate` checks syntax and static rules but cannotsee execution-time failures, and points to reproducing them with `kiln_render`.+- Export a saved material revision's maps as tiling textures with a planar preview+ ([#246](https://github.com/instruktlabs/kiln/issues/246)). `material export <id> <revision>+ --maps <dir> --size <px> [--repeat <metres>] [--tiles <n>]` writes one PNG per map at the+ stated size, a lit `tiles` × `tiles` preview and a `kiln.material-maps.v1` sidecar naming+ each map's slot, colour space, size, repeat, source revision and `sha256`. A V2 layer+ recipe is recompiled at the new size; other maps resample with a wrapped Catmull-Rom filter.+ The preview uses the GPU render port when one is configured and records its renderer and+ `viewFidelity`, so a CPU preview is never read as material evidence. Existing files are+ never replaced. `exportMaterialMaps` and `createMaterialMapExport` from+ `material-library/node` do the same for hosts; `--out` and MCP are unchanged.## 1.4.0 (2026-10-23)diff --git a/docs/material-library.md b/docs/material-library.mdindex 04271666..48e420cf 100644--- a/docs/material-library.md+++ b/docs/material-library.md@@ -118,6 +118,65 @@ Physical repeat scale is recorded metadata. The author still chooses UV scale apmesh. Repeating a one-meter material across a ten-meter wall requires corresponding UV repeats;recording meters does not silently change geometry or UVs.+## Export maps as tiling textures++A destination that takes plain images, such as a game engine's terrain layer, can export one+saved revision's maps as standalone PNGs:++```sh+node kiln.mjs material export coarse-soil RETURNED_REVISION --maps soil-maps --size 1024 --repeat 4+```++The command writes into the named directory, creating it when missing:++- `<id>.<slot>.png` for each map, `--size` pixels square;+- `<id>.preview.png`, the material on a lit plane repeated `--tiles` × `--tiles` (default 3,+ at most 8);+- `<id>.maps.json`, the `kiln.material-maps.v1` sidecar.++`--repeat` is the real-world edge of one tile in metres. It defaults to the recorded+`physicalSizeMeters` when that is square, and is required otherwise. Sizes run from 4 to 4096.+A map already at the requested size is copied byte for byte (`method: "copy"`). A V2 layer+recipe without a height derivation samples UV space, so it is recompiled at a power-of-two size+up to 1024 (`"recipe"`, with the new recipe hash). Every other map is resampled (`"resampled"`)+with a separable Catmull-Rom cubic that follows the map's wrap mode, so a repeating tile stays+seamless; sRGB maps filter in linear light and normal maps are renormalized. Resampling is+deterministic for a given engine and encoder.++The sidecar names the source material and revision, its name, parameters and source/license+records; the size and repeat; and, for each map, its slot, file, usage, colour space (`srgb` for+base colour and emissive, `linear` data for the rest), normal convention or channel packing,+pixel size, byte count, `sha256`, method, wrap and the stored map it came from. Packed maps keep+R=occlusion, G=roughness, B=metallic; split channels in the destination if it wants them apart.++The preview follows the same route as `kiln_render`: the configured GPU renderer (`--render+auto|cpu|gpu`, default `KILN_RENDER` or auto) through the render port, else the CPU raster. Its+`preview.rendererId` and `preview.viewFidelity` record which one drew it. A CPU preview has+`materialFaithful: false` and shows the plane's geometry, not the material; judge the material+only from a `materialFaithful: true` preview. Maps larger than 1024 pixels are resampled to 1024+for the preview plane only (`preview.mapSize`).++Every file must be new. If one already exists the export stops and removes the files it had+already written. `--out` keeps writing the portable JSON payload, and `--maps` and `--out` cannot+be combined. Terrain-layer schemas, blend masks and destination tints belong to the destination,+not to this export. Hosts call the same export from TypeScript:++```ts+import { FileMaterialLibrary, exportMaterialMaps } from '@instruktlabs/kiln/material-library/node';++const library = new FileMaterialLibrary('/workspace/.kiln/materials');+const record = await library.read('coarse-soil', revisionId);+const { sidecar, files } = await exportMaterialMaps(record, {+ outDir: 'soil-maps',+ size: 1024,+ repeatMeters: 4,+ // Optional: a PbrRenderPort for a material-faithful preview; without one the preview is CPU.+ // viewRenderPort, viewRenderTimeoutMs, viewRenderRequired+});+```++`createMaterialMapExport` returns the same files in memory without writing them.+## Host API and portable export```tsdiff --git a/skills/kiln-author-asset/references/projects-and-materials.md b/skills/kiln-author-asset/references/projects-and-materials.mdindex 01ffe2b6..3bf12b2b 100644--- a/skills/kiln-author-asset/references/projects-and-materials.md+++ b/skills/kiln-author-asset/references/projects-and-materials.md@@ -65,6 +65,10 @@ transitive closure. Export a saved material with`node kiln.mjs material export MATERIAL_ID REVISION --out material.json` andimport that complete payload with `material import --file material.json`;copying only the atlas PNG loses editable sources and named regions.+For a destination that takes plain images, such as a terrain layer,+`material export MATERIAL_ID REVISION --maps DIR --size 1024 --repeat 4` writes each map as a+tiling PNG, a `.maps.json` sidecar (slot, colour space, size, repeat, `sha256`) and a tiled+preview; read the preview's `viewFidelity` before judging the material from it.## Create and revise a project when usefuldiff --git a/src/material-library-node.ts b/src/material-library-node.tsindex 1760d514..153e25d7 100644--- a/src/material-library-node.ts+++ b/src/material-library-node.ts@@ -1322,3 +1322,15 @@ export async function createMaterialRecordV2(await verifyMaterialRecord(record, { materials: [...records, record] });return record;}++export {+ createMaterialMapExport,+ exportMaterialMaps,+ MATERIAL_MAP_EXPORT_LIMITS,+ MATERIAL_MAP_RESAMPLE_FILTER,+ type MaterialMapExportMapV1,+ type MaterialMapExportOptionsV1,+ type MaterialMapExportResultV1,+ type MaterialMapExportSidecarV1,+ type MaterialMapExportV1,+} from './material-map-export-node';diff --git a/src/material-map-export-node.ts b/src/material-map-export-node.tsnew file mode 100644index 00000000..cc96a7f3--- /dev/null+++ b/src/material-map-export-node.ts@@ -0,0 +1,592 @@+/**+ * Export one saved material revision as standalone tiling PNGs, a JSON sidecar and a lit+ * planar preview. Standalone: no project, terrain-layer schema, mask or destination tint.+ * The preview reuses the host-injected `PbrRenderPort` through `captureViewsViaPort`, which+ * owns the deadline and reply validation; a failure degrades to the CPU geometry view and the+ * sidecar records its `kiln.view-fidelity.v1` block so a CPU preview is never material evidence.+ */+import { createHash } from 'node:crypto';+import { join, resolve } from 'node:path';+import sharp from 'sharp';+import * as THREE from 'three';+import { writeNewDestinationsAtomic } from './cli-output';+import type { PbrRenderPort, ViewFidelityV1 } from './composer/render-port';+import {+ MATERIAL_LIBRARY_LIMITS,+ MATERIAL_LIBRARY_SLOTS,+ materialPngDimensions,+ validateMaterialRecordShapeAny,+ type MaterialLibrarySlot,+ type MaterialManifest,+ type MaterialRecord,+ type MaterialSourceV1,+} from './material-library';+import { compileProceduralTextureSpecV2 } from './procedural-texture';+import type { PortableSamplerV1 } from './portable-sampler';+import { loadTexture, pbrMaterial, type PbrMaterialOptions } from './textures';++export const MATERIAL_MAP_EXPORT_LIMITS = Object.freeze({+ minSize: 4,+ maxSize: MATERIAL_LIBRARY_LIMITS.maxMapEdge,+ maxRepeatMeters: 100000,+ defaultTiles: 3,+ maxTiles: 8,+ /** Largest map edge bound into the preview plane; larger exports are resampled for it. */+ maxPreviewMapSize: 1024,+});+/**+ * Separable Catmull-Rom cubic (B=0, C=0.5), widened by the scale factor when shrinking. Edges+ * follow the map's wrap (repeat by default for tileable materials), so a tile stays seamless.+ * sRGB maps filter in linear light; normal maps are renormalized. Arithmetic only, no randomness.+ */+export const MATERIAL_MAP_RESAMPLE_FILTER = 'catmull-rom' as const;+const PREVIEW_CAMERA = Object.freeze({ azimuthDeg: 30, elevationDeg: 50 });++type Wrap = PortableSamplerV1['wrapS'];+export interface MaterialMapExportOptionsV1 {+ /** Directory for the files; created when missing. Existing files are never replaced. */+ outDir: string;+ /** Square pixel edge of every exported map. */+ size: number;+ /** Real-world edge of one tile in metres. Defaults to a square `physicalSizeMeters`. */+ repeatMeters?: number;+ /** The preview repeats the material `tiles` × `tiles` times. Default 3. */+ tiles?: number;+ /** Host GPU renderer. Omitted: the preview is a CPU geometry view. */+ viewRenderPort?: PbrRenderPort;+ /** Per-call port deadline in milliseconds. */+ viewRenderTimeoutMs?: number;+ /** Fail instead of degrading when the port cannot render. */+ viewRenderRequired?: boolean;+}+export interface MaterialMapExportMapV1 {+ slot: MaterialLibrarySlot;+ file: string;+ usage: string;+ colorSpace: 'srgb' | 'linear';+ normalConvention?: 'opengl';+ channelPacking?: 'r-occlusion-g-roughness-b-metallic';+ width: number;+ height: number;+ bytes: number;+ sha256: `sha256:${string}`;+ /** `copy`: stored bytes; `recipe`: V2 layer recipe recompiled at `size`; `resampled`. */+ method: 'copy' | 'recipe' | 'resampled';+ wrap: { s: Wrap; t: Wrap };+ recipe?: { compilerId: 'kiln.procedural-texture.v2'; recipeHash: `sha256:${string}` };+ source: { file: string; sha256: `sha256:${string}`; width: number; height: number };+}+export interface MaterialMapExportSidecarV1 {+ version: 'kiln.material-maps.v1';+ material: {+ materialId: string;+ revisionId: string;+ name: string;+ tileable: boolean;+ physicalSizeMeters?: { width: number; height: number };+ parameters: MaterialManifest['parameters'];+ sources: MaterialSourceV1[];+ };+ size: { width: number; height: number };+ repeatMeters: { width: number; height: number };+ resampleFilter: typeof MATERIAL_MAP_RESAMPLE_FILTER;+ maps: MaterialMapExportMapV1[];+ preview: {+ file: string;+ sha256: `sha256:${string}`;+ bytes: number;+ width: number;+ height: number;+ tiles: number;+ planeMeters: number;+ /** Edge of the map images bound into the preview plane. */+ mapSize: number;+ camera: { azimuthDeg: number; elevationDeg: number };+ rendererId: string;+ viewFidelity: ViewFidelityV1;+ };+}+export interface MaterialMapExportV1 {+ sidecar: MaterialMapExportSidecarV1;+ /** File name to bytes, maps first, then the preview and the sidecar. */+ files: { name: string; bytes: Uint8Array }[];+}+export interface MaterialMapExportResultV1 {+ directory: string;+ sidecarPath: string;+ previewPath: string;+ /** Absolute paths of every written file. */+ files: string[];+ sidecar: MaterialMapExportSidecarV1;+}++const digest = (bytes: Uint8Array): `sha256:${string}` =>+ `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+const encodePng = async (pixels: Uint8Array, width: number, height: number) =>+ new Uint8Array(+ await sharp(pixels, { raw: { width, height, channels: 4 } })+ .png({ compressionLevel: 9, adaptiveFiltering: false })+ .toBuffer(),+ );+async function decodePng(bytes: Uint8Array) {+ const { data, info } = await sharp(bytes, {+ limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,+ failOn: 'warning',+ })+ .ensureAlpha()+ .raw({ depth: 'uchar' })+ .toBuffer({ resolveWithObject: true });+ if (info.channels !== 4) throw new Error('Material map must decode to RGBA');+ return { pixels: new Uint8Array(data), width: info.width, height: info.height };+}++/**+ * Check size, tiles and an explicit repeat. Without `physicalSizeMeters` an omitted repeat is+ * left for the record-aware check; with it, the repeat defaults to a square physical size.+ */+export function validateMaterialMapExportOptions(+ options: Pick<MaterialMapExportOptionsV1, 'size' | 'repeatMeters' | 'tiles'>,+ material?: Pick<MaterialManifest, 'materialId' | 'physicalSizeMeters'>,+): { size: number; tiles: number; repeat?: number } {+ const limits = MATERIAL_MAP_EXPORT_LIMITS;+ const { size } = options;+ if (!Number.isInteger(size) || size < limits.minSize || size > limits.maxSize)+ throw new Error(`size must be an integer from ${limits.minSize} to ${limits.maxSize} pixels`);+ const tiles = options.tiles ?? limits.defaultTiles;+ if (!Number.isInteger(tiles) || tiles < 1 || tiles > limits.maxTiles)+ throw new Error(`tiles must be an integer from 1 to ${limits.maxTiles}`);+ let repeat = options.repeatMeters;+ if (repeat === undefined && material) {+ const physical = material.physicalSizeMeters;+ if (!physical || physical.width !== physical.height)+ throw new Error(+ `repeatMeters is required: material ${material.materialId} records no square physicalSizeMeters (CLI: --repeat <metres>)`,+ );+ repeat = physical.width;+ }+ if (+ repeat !== undefined &&+ (!Number.isFinite(repeat) || repeat <= 0 || repeat > limits.maxRepeatMeters)+ )+ throw new Error(+ `repeatMeters must be a positive number of metres up to ${limits.maxRepeatMeters}`,+ );+ return { size, tiles, ...(repeat !== undefined ? { repeat } : {}) };+}++/** One axis of filter taps: wrapped source indices and normalized weights per output. */+function axisTaps(source: number, target: number, wrap: Wrap) {+ const scale = source / target;+ const stretch = Math.max(1, scale);+ const support = 2 * stretch;+ const kernel = (x: number) => {+ const a = Math.abs(x);+ if (a < 1) return 1.5 * a * a * a - 2.5 * a * a + 1;+ if (a < 2) return -0.5 * a * a * a + 2.5 * a * a - 4 * a + 2;+ return 0;+ };+ const address = (index: number) => {+ if (wrap === 'repeat') return ((index % source) + source) % source;+ if (wrap === 'mirrored-repeat') {+ const period = 2 * source;+ const folded = ((index % period) + period) % period;+ return folded < source ? folded : period - 1 - folded;+ }+ return Math.min(source - 1, Math.max(0, index));+ };+ const taps: { index: Int32Array; weight: Float64Array }[] = [];+ for (let out = 0; out < target; out++) {+ const center = (out + 0.5) * scale - 0.5;+ const first = Math.ceil(center - support);+ const last = Math.floor(center + support);+ const index = new Int32Array(last - first + 1);+ const weight = new Float64Array(last - first + 1);+ let total = 0;+ for (let i = first; i <= last; i++) {+ const w = kernel((i - center) / stretch);+ index[i - first] = address(i);+ weight[i - first] = w;+ total += w;+ }+ for (let i = 0; i < weight.length; i++) weight[i]! /= total;+ taps.push({ index, weight });+ }+ return taps;+}++const SRGB_TO_LINEAR = Float64Array.from({ length: 256 }, (_, value) => {+ const c = value / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+});+const linearToSrgb = (value: number) => {+ const c = Math.min(1, Math.max(0, value));+ return c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055;+};+const toByte = (value: number) => Math.round(Math.min(1, Math.max(0, value)) * 255);++/**+ * Deterministic separable resample, one output row at a time so memory stays at the output+ * plus two row buffers even for a 4096-pixel map.+ */+function resampleMaterialMapPixels(+ pixels: Uint8Array,+ width: number,+ height: number,+ target: number,+ options: { colorSpace: 'srgb' | 'linear'; normal?: boolean; wrap: { s: Wrap; t: Wrap } },+): Uint8Array {+ const horizontal = axisTaps(width, target, options.wrap.s);+ const vertical = axisTaps(height, target, options.wrap.t);+ const srgb = options.colorSpace === 'srgb';+ const decode = (channel: number, value: number) =>+ srgb && channel < 3 ? SRGB_TO_LINEAR[value]! : value / 255;+ const column = new Float64Array(width * 4);+ const row = new Float64Array(4);+ const out = new Uint8Array(target * target * 4);+ for (let y = 0; y < target; y++) {+ const { index: rows, weight: rowWeights } = vertical[y]!;+ column.fill(0);+ for (let tap = 0; tap < rows.length; tap++) {+ const offset = rows[tap]! * width * 4;+ const w = rowWeights[tap]!;+ for (let i = 0; i < width * 4; i++) column[i]! += decode(i & 3, pixels[offset + i]!) * w;+ }+ for (let x = 0; x < target; x++) {+ const { index: cols, weight: colWeights } = horizontal[x]!;+ row.fill(0);+ for (let tap = 0; tap < cols.length; tap++) {+ const offset = cols[tap]! * 4;+ const w = colWeights[tap]!;+ for (let c = 0; c < 4; c++) row[c]! += column[offset + c]! * w;+ }+ const o = (y * target + x) * 4;+ if (options.normal) {+ let nx = row[0]! * 2 - 1;+ let ny = row[1]! * 2 - 1;+ let nz = row[2]! * 2 - 1;+ const length = Math.hypot(nx, ny, nz);+ if (length > 1e-6) {+ nx /= length;+ ny /= length;+ nz /= length;+ } else [nx, ny, nz] = [0, 0, 1];+ out[o] = toByte(nx * 0.5 + 0.5);+ out[o + 1] = toByte(ny * 0.5 + 0.5);+ out[o + 2] = toByte(nz * 0.5 + 0.5);+ } else+ for (let c = 0; c < 3; c++) out[o + c] = toByte(srgb ? linearToSrgb(row[c]!) : row[c]!);+ out[o + 3] = toByte(row[3]!);+ }+ }+ return out;+}++type StoredMap = MaterialManifest['maps'][number];+/** A V2 layer recipe samples UV space, so it renders faithfully at another size. */+function regenerableRecipe(map: StoredMap) {+ if ('procedural' in map && map.procedural && !map.procedural.derive) return map.procedural.spec;+ if (+ 'recipe' in map &&+ map.recipe?.kind === 'procedural' &&+ map.recipe.compilerId === 'kiln.procedural-texture.v2' &&+ !map.recipe.derive &&+ map.recipe.spec.schemaVersion === 2+ )+ return map.recipe.spec;+ return undefined;+}++async function exportMap(+ record: MaterialRecord,+ map: StoredMap,+ size: number,+): Promise<{ entry: Omit<MaterialMapExportMapV1, 'file'>; bytes: Uint8Array; pixels: Uint8Array }> {+ const manifest = record.manifest;+ const stored = record.files[map.file]!;+ const fallbackWrap: Wrap = manifest.tileable ? 'repeat' : 'clamp-to-edge';+ const wrap =+ 'sampler' in map && map.sampler+ ? { s: map.sampler.wrapS, t: map.sampler.wrapT }+ : { s: fallbackWrap, t: fallbackWrap };+ let bytes: Uint8Array;+ let pixels: Uint8Array;+ let method: MaterialMapExportMapV1['method'];+ let recipe: MaterialMapExportMapV1['recipe'];+ const spec = regenerableRecipe(map);+ if (map.width === size && map.height === size) {+ bytes = stored.slice();+ pixels = (await decodePng(bytes)).pixels;+ method = 'copy';+ } else if (spec && size <= 1024 && (size & (size - 1)) === 0) {+ // The V2 compiler's own size contract: a power of two from 4 to 1024.+ const compiled = compileProceduralTextureSpecV2({ ...spec, size });+ pixels = compiled.pixels;+ bytes = await encodePng(pixels, size, size);+ method = 'recipe';+ recipe = { compilerId: 'kiln.procedural-texture.v2', recipeHash: compiled.recipeHash };+ } else {+ const decoded = await decodePng(stored);+ pixels = resampleMaterialMapPixels(decoded.pixels, decoded.width, decoded.height, size, {+ colorSpace: map.colorSpace,+ normal: map.slot === 'normal',+ wrap,+ });+ bytes = await encodePng(pixels, size, size);+ method = 'resampled';+ }+ return {+ bytes,+ pixels,+ entry: {+ slot: map.slot,+ usage: map.usage,+ colorSpace: map.colorSpace,+ ...(map.normalConvention ? { normalConvention: map.normalConvention } : {}),+ ...(map.channelPacking ? { channelPacking: map.channelPacking } : {}),+ width: size,+ height: size,+ bytes: bytes.length,+ sha256: digest(bytes),+ method,+ wrap,+ ...(recipe ? { recipe } : {}),+ source: {+ file: map.file,+ sha256: map.sha256 as `sha256:${string}`,+ width: map.width,+ height: map.height,+ },+ },+ };+}++/** A plane of `tiles` × `tiles` repeats, flat on XZ, with the exported maps bound. */+async function previewGlb(+ manifest: MaterialManifest,+ maps: { slot: MaterialLibrarySlot; usage: StoredMap['usage']; png: Uint8Array }[],+ tiles: number,+ planeMeters: number,+): Promise<Uint8Array> {+ const textures = new Map<MaterialLibrarySlot, THREE.Texture>();+ for (const map of maps)+ textures.set(+ map.slot,+ await loadTexture(map.png, {+ usage: map.usage,+ name: `${manifest.materialId}.${map.slot}`,+ }),+ );+ const p = manifest.parameters;+ const options: PbrMaterialOptions = {+ roughness: p.roughness,+ metalness: p.metalness,+ emissiveIntensity: p.emissiveIntensity,+ alphaMode: p.alphaMode,+ ...(p.alphaMode === 'mask' ? { alphaCutoff: p.alphaCutoff } : {}),+ doubleSided: p.doubleSided,+ ...(textures.get('baseColor')+ ? { albedo: textures.get('baseColor') }+ : p.baseColor !== undefined+ ? { albedo: p.baseColor }+ : {}),+ ...(textures.get('normal') ? { normal: textures.get('normal') } : {}),+ ...(textures.get('metallicRoughness')+ ? { metallicRoughness: textures.get('metallicRoughness') }+ : {}),+ ...(textures.get('emissive')+ ? { emissive: textures.get('emissive') }+ : p.emissive !== undefined+ ? { emissive: p.emissive }+ : {}),+ ...(textures.get('occlusion') ? { aoMap: textures.get('occlusion') } : {}),+ };+ const material = pbrMaterial(options);+ material.name = manifest.name;+ if (textures.has('baseColor') && p.baseColor !== undefined) material.color.setHex(p.baseColor);+ if (textures.has('emissive') && p.emissive !== undefined) material.emissive.setHex(p.emissive);+ const geometry = new THREE.PlaneGeometry(planeMeters, planeMeters);+ geometry.rotateX(-Math.PI / 2);+ const uv = geometry.getAttribute('uv') as THREE.BufferAttribute;+ for (let i = 0; i < uv.count; i++) uv.setXY(i, uv.getX(i) * tiles, uv.getY(i) * tiles);+ const root = new THREE.Group();+ root.name = `${manifest.materialId}-preview`;+ const mesh = new THREE.Mesh(geometry, material);+ mesh.name = 'tiles';+ root.add(mesh);+ // Lazy: the renderer and view modules stay off this entrypoint's load graph.+ const { renderSceneToGLB } = await import('./render');+ return (await renderSceneToGLB(root, { derivative: true })).bytes;+}++async function renderPreview(+ glb: Uint8Array,+ options: MaterialMapExportOptionsV1,+): Promise<{ png: Uint8Array; rendererId: string; viewFidelity: ViewFidelityV1 }> {+ const { captureViewsViaPort, DEFAULT_VIEW_RENDER_TIMEOUT_MS, sha256Bytes } = await import(+ './views/port'+ );+ const capture = { preset: '1x1' as const, cells: [{ ...PREVIEW_CAMERA }] };+ const inputGlbSha256 = await sha256Bytes(glb);+ let degradeReason = 'material-faithful view render port unavailable';+ if (options.viewRenderPort) {+ const ported = await captureViewsViaPort(+ options.viewRenderPort,+ glb,+ options.viewRenderTimeoutMs ?? DEFAULT_VIEW_RENDER_TIMEOUT_MS,+ capture,+ );+ if (ported.ok)+ return {+ png: new Uint8Array(ported.png),+ rendererId: ported.rendererId,+ viewFidelity: {+ version: 'kiln.view-fidelity.v1',+ requested: 'full-preferred',+ delivered: 'full-material',+ materialFaithful: true,+ // The preview plane is a purpose-built derivative, not a persisted artifact.+ exactArtifact: false,+ rendererId: ported.rendererId,+ inputGlbSha256,+ degraded: false,+ },+ };+ degradeReason = ported.reason;+ }+ if (options.viewRenderRequired) throw new Error(`Required GPU render failed: ${degradeReason}`);+ // Lazy, as everywhere: renderer-id.ts reads package metadata at module load.+ const { renderGlbViewGrid, CPU_RASTER_RENDERER_ID } = await import('./views');+ const grid = await renderGlbViewGrid(glb, { capture });+ return {+ png: new Uint8Array(grid.png),+ rendererId: CPU_RASTER_RENDERER_ID,+ viewFidelity: {+ version: 'kiln.view-fidelity.v1',+ requested: 'full-preferred',+ delivered: 'geometry-flat',+ materialFaithful: false,+ exactArtifact: false,+ rendererId: CPU_RASTER_RENDERER_ID,+ inputGlbSha256: grid.inputGlbSha256,+ degraded: true,+ degradeReason,+ reasonCodes: ['FULL_MATERIAL_RENDER_UNAVAILABLE', ...grid.reasonCodes],+ },+ };+}++/** Build every file in memory; nothing is written. */+export async function createMaterialMapExport(+ record: MaterialRecord,+ options: MaterialMapExportOptionsV1,+): Promise<MaterialMapExportV1> {+ if (typeof options.outDir !== 'string' || !options.outDir)+ throw new Error('outDir must name a directory');+ validateMaterialMapExportOptions(options);+ const manifest = validateMaterialRecordShapeAny(record);+ const checked = validateMaterialMapExportOptions(options, manifest);+ const { size, tiles } = checked;+ // With the manifest supplied, an omitted repeat is defaulted or rejected above.+ const repeat = checked.repeat!;+ for (const map of manifest.maps)+ if (digest(record.files[map.file]!) !== map.sha256)+ throw new Error(`Material integrity hash mismatch: ${map.file}`);+ const id = manifest.materialId;+ const ordered = MATERIAL_LIBRARY_SLOTS.flatMap((slot) =>+ manifest.maps.filter((map) => map.slot === slot),+ );+ const files: MaterialMapExportV1['files'] = [];+ const maps: MaterialMapExportMapV1[] = [];+ const previewMaps: { slot: MaterialLibrarySlot; usage: StoredMap['usage']; png: Uint8Array }[] =+ [];+ const previewSize = Math.min(size, MATERIAL_MAP_EXPORT_LIMITS.maxPreviewMapSize);+ for (const map of ordered) {+ const exported = await exportMap(record, map, size);+ const file = `${id}.${map.slot}.png`;+ const { slot, ...entry } = exported.entry;+ maps.push({ slot, file, ...entry });+ files.push({ name: file, bytes: exported.bytes });+ previewMaps.push({+ slot: map.slot,+ usage: map.usage,+ png:+ previewSize === size+ ? exported.bytes+ : await encodePng(+ resampleMaterialMapPixels(exported.pixels, size, size, previewSize, {+ colorSpace: map.colorSpace,+ normal: map.slot === 'normal',+ wrap: exported.entry.wrap,+ }),+ previewSize,+ previewSize,+ ),+ });+ }+ const planeMeters = tiles * repeat;+ const rendered = await renderPreview(+ await previewGlb(manifest, previewMaps, tiles, planeMeters),+ options,+ );+ const previewFile = `${id}.preview.png`;+ files.push({ name: previewFile, bytes: rendered.png });+ const sidecar: MaterialMapExportSidecarV1 = {+ version: 'kiln.material-maps.v1',+ material: {+ materialId: id,+ revisionId: manifest.revisionId,+ name: manifest.name,+ tileable: manifest.tileable,+ ...(manifest.physicalSizeMeters+ ? { physicalSizeMeters: { ...manifest.physicalSizeMeters } }+ : {}),+ parameters: structuredClone(manifest.parameters),+ sources: structuredClone(manifest.sources),+ },+ size: { width: size, height: size },+ repeatMeters: { width: repeat, height: repeat },+ resampleFilter: MATERIAL_MAP_RESAMPLE_FILTER,+ maps,+ preview: {+ file: previewFile,+ sha256: digest(rendered.png),+ bytes: rendered.png.length,+ ...materialPngDimensions(rendered.png),+ tiles,+ planeMeters,+ mapSize: previewSize,+ camera: { ...PREVIEW_CAMERA },+ rendererId: rendered.rendererId,+ viewFidelity: rendered.viewFidelity,+ },+ };+ files.push({+ name: `${id}.maps.json`,+ bytes: new TextEncoder().encode(`${JSON.stringify(sidecar, null, 2)}\n`),+ });+ return { sidecar, files };+}++/**+ * Write the maps, the preview and then the sidecar into `outDir`. Every destination must be+ * new: an existing file stops the export and this call's published files are rolled back.+ */+export async function exportMaterialMaps(+ record: MaterialRecord,+ options: MaterialMapExportOptionsV1,+): Promise<MaterialMapExportResultV1> {+ const created = await createMaterialMapExport(record, options);+ const directory = resolve(options.outDir);+ const outputs = created.files.map(({ name, bytes }) => ({+ path: join(directory, name),+ data: bytes,+ }));+ await writeNewDestinationsAtomic(outputs);+ return {+ directory,+ sidecarPath: outputs.at(-1)!.path,+ previewPath: outputs.at(-2)!.path,+ files: outputs.map(({ path }) => path),+ sidecar: created.sidecar,+ };+}diff --git a/src/material-map-export.test.ts b/src/material-map-export.test.tsnew file mode 100644index 00000000..463b29bc--- /dev/null+++ b/src/material-map-export.test.ts@@ -0,0 +1,347 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import sharp from 'sharp';+import { materialPngDimensions, type MaterialRecord } from './material-library';+import { createMaterialRecordV1, exportMaterialMaps } from './material-library-node';+import type { PbrRenderPort } from './composer/render-port';++const sha = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+const source = {+ id: 'authored',+ kind: 'procedural' as const,+ provider: 'Kiln',+ creator: 'Fixture',+ license: {+ spdx: 'CC0-1.0',+ url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ attribution: '',+ },+ originalFiles: [],+};+const noise = (usage: 'albedo' | 'normal' | 'metallicRoughness', size = 8) => ({+ schemaVersion: 2 as const,+ usage,+ size,+ layers: [+ {+ op: 'noise' as const,+ colorA: 0x404040,+ colorB: 0xc0c0c0,+ seed: 7,+ scale: 4,+ octaves: 2,+ blend: 'normal' as const,+ opacity: 1,+ },+ ],+});++let root: string;+let record: MaterialRecord;+beforeAll(async () => {+ root = await mkdtemp(join(tmpdir(), 'kiln-material-maps-'));+ record = await createMaterialRecordV1({+ materialId: 'leaf-litter',+ name: 'Leaf litter',+ tileable: true,+ physicalSizeMeters: { width: 4, height: 4 },+ sources: [source],+ maps: [+ { slot: 'baseColor', sourceId: 'authored', transforms: [], procedural: noise('albedo') },+ {+ slot: 'normal',+ sourceId: 'authored',+ transforms: [],+ procedural: noise('normal'),+ derive: { kind: 'normal-from-height', strength: 4 },+ },+ {+ slot: 'metallicRoughness',+ sourceId: 'authored',+ transforms: [],+ procedural: noise('metallicRoughness'),+ },+ ],+ });+});+afterAll(async () => {+ await rm(root, { recursive: true, force: true });+});++test('exports each map as a PNG at the stated size with a hashed sidecar and a planar preview', async () => {+ const outDir = join(root, 'cpu');+ const result = await exportMaterialMaps(record, { outDir, size: 16, repeatMeters: 4 });+ const names = (await readdir(outDir)).sort();+ expect(names).toEqual([+ 'leaf-litter.baseColor.png',+ 'leaf-litter.maps.json',+ 'leaf-litter.metallicRoughness.png',+ 'leaf-litter.normal.png',+ 'leaf-litter.preview.png',+ ]);+ const sidecar = JSON.parse(await readFile(join(outDir, 'leaf-litter.maps.json'), 'utf8'));+ expect(sidecar).toEqual(result.sidecar);+ expect(sidecar.version).toBe('kiln.material-maps.v1');+ expect(sidecar.material).toMatchObject({+ materialId: 'leaf-litter',+ revisionId: record.manifest.revisionId,+ name: 'Leaf litter',+ tileable: true,+ });+ expect(sidecar.material.sources[0].license.spdx).toBe('CC0-1.0');+ expect(sidecar.size).toEqual({ width: 16, height: 16 });+ expect(sidecar.repeatMeters).toEqual({ width: 4, height: 4 });+ const bySlot = Object.fromEntries(+ sidecar.maps.map((map: { slot: string }) => [map.slot, map]),+ ) as Record<string, Record<string, unknown>>;+ expect(Object.keys(bySlot).sort()).toEqual(['baseColor', 'metallicRoughness', 'normal']);+ expect(bySlot['baseColor']!['colorSpace']).toBe('srgb');+ expect(bySlot['normal']!['colorSpace']).toBe('linear');+ expect(bySlot['metallicRoughness']!['colorSpace']).toBe('linear');+ expect(bySlot['normal']!['normalConvention']).toBe('opengl');+ expect(bySlot['metallicRoughness']!['channelPacking']).toBe('r-occlusion-g-roughness-b-metallic');+ // A V2 layer recipe is UV-space and is regenerated at the requested size. A height-derived+ // normal depends on texel spacing, so its stored pixels are resampled instead.+ expect(bySlot['baseColor']!['method']).toBe('recipe');+ expect(bySlot['normal']!['method']).toBe('resampled');+ for (const map of sidecar.maps) {+ const bytes = await readFile(join(outDir, map.file));+ expect(materialPngDimensions(bytes)).toEqual({ width: 16, height: 16 });+ expect(map).toMatchObject({ width: 16, height: 16, bytes: bytes.length, sha256: sha(bytes) });+ const stored = record.manifest.maps.find((item) => item.slot === map.slot)!;+ expect(map.source).toEqual({+ file: stored.file,+ sha256: stored.sha256,+ width: stored.width,+ height: stored.height,+ });+ }+ const preview = await readFile(join(outDir, 'leaf-litter.preview.png'));+ expect(sidecar.preview).toMatchObject({+ file: 'leaf-litter.preview.png',+ sha256: sha(preview),+ bytes: preview.length,+ tiles: 3,+ planeMeters: 12,+ });+ // No render port: a CPU geometry view, never material evidence.+ expect(sidecar.preview.rendererId).toStartWith('cpu-raster');+ expect(sidecar.preview.viewFidelity).toMatchObject({+ version: 'kiln.view-fidelity.v1',+ materialFaithful: false,+ delivered: 'geometry-flat',+ rendererId: sidecar.preview.rendererId,+ degraded: true,+ });+ expect(sidecar.preview.viewFidelity.reasonCodes).toContain('FULL_MATERIAL_RENDER_UNAVAILABLE');+ expect(materialPngDimensions(preview).width).toBeGreaterThan(0);+ expect(result.files.sort()).toEqual(names.map((name) => join(outDir, name)).sort());+}, 60_000); // In-process CPU preview plus three PNG encodes; measured below 3 s on an idle host.++test('a stored size passes the exact stored bytes through and resampling is deterministic', async () => {+ const a = await exportMaterialMaps(record, {+ outDir: join(root, 'same-a'),+ size: 8,+ repeatMeters: 2,+ tiles: 2,+ });+ const b = await exportMaterialMaps(record, {+ outDir: join(root, 'same-b'),+ size: 8,+ repeatMeters: 2,+ tiles: 2,+ });+ expect(a.sidecar).toEqual(b.sidecar);+ for (const map of a.sidecar.maps) {+ expect(map.method).toBe('copy');+ expect(map.sha256).toBe(map.source.sha256);+ }+ expect(a.sidecar.preview.tiles).toBe(2);+ expect(a.sidecar.preview.planeMeters).toBe(4);+ const c = await exportMaterialMaps(record, {+ outDir: join(root, 'c'),+ size: 12,+ repeatMeters: 2,+ });+ const d = await exportMaterialMaps(record, {+ outDir: join(root, 'd'),+ size: 12,+ repeatMeters: 2,+ });+ expect(c.sidecar.maps).toEqual(d.sidecar.maps);+}, 60_000);++test('resampled normals stay unit length', async () => {+ const outDir = join(root, 'wrap');+ await exportMaterialMaps(record, { outDir, size: 13, repeatMeters: 4 });+ const { data, info } = await sharp(await readFile(join(outDir, 'leaf-litter.normal.png')))+ .ensureAlpha()+ .raw()+ .toBuffer({ resolveWithObject: true });+ expect(info.width).toBe(13);+ for (let i = 0; i < data.length; i += 4) {+ const [x, y, z] = [0, 1, 2].map((c) => (data[i + c]! / 255) * 2 - 1);+ expect(Math.abs(Math.hypot(x!, y!, z!) - 1)).toBeLessThan(0.02);+ }+});++test('resampling follows the tile edge: a tileable map wraps, a non-tileable one clamps', async () => {+ // One white column at the left edge of an 8 x 8 black base colour map.+ const pixels = new Uint8Array(8 * 8 * 4);+ for (let y = 0; y < 8; y++) pixels.fill(255, y * 32, y * 32 + 4);+ for (let i = 3; i < pixels.length; i += 4) pixels[i] = 255;+ const png = new Uint8Array(+ await sharp(pixels, { raw: { width: 8, height: 8, channels: 4 } })+ .png()+ .toBuffer(),+ );+ const lastColumn = async (tileable: boolean) => {+ const external = await createMaterialRecordV1({+ materialId: tileable ? 'edge-wrap' : 'edge-clamp',+ name: 'Edge',+ tileable,+ sources: [+ {+ id: 'scan',+ kind: 'external',+ provider: 'Fixture',+ creator: 'Fixture',+ assetUrl: 'https://example.com/edge',+ license: source.license,+ originalFiles: [{ name: 'edge.png', sha256: sha(png), bytes: png.length }],+ },+ ],+ maps: [+ {+ slot: 'baseColor',+ sourceId: 'scan',+ transforms: [],+ bytes: png,+ originalFile: 'edge.png',+ },+ ],+ });+ const outDir = join(root, `edge-${tileable}`);+ const { sidecar } = await exportMaterialMaps(external, { outDir, size: 16, repeatMeters: 1 });+ expect(sidecar.maps[0]).toMatchObject({ method: 'resampled' });+ const id = external.manifest.materialId;+ const { data } = await sharp(await readFile(join(outDir, `${id}.baseColor.png`)))+ .raw()+ .toBuffer({ resolveWithObject: true });+ return data[(5 * 16 + 15) * 4]!;+ };+ expect(await lastColumn(true)).toBeGreaterThan(64);+ expect(await lastColumn(false)).toBe(0);+}, 60_000);++test('refuses to replace any existing output and writes nothing', async () => {+ const outDir = join(root, 'existing');+ const first = await exportMaterialMaps(record, { outDir, size: 16, repeatMeters: 4 });+ const before = await Promise.all(first.files.map((file) => readFile(file)));+ await expect(exportMaterialMaps(record, { outDir, size: 16, repeatMeters: 4 })).rejects.toThrow(+ /already exists/,+ );+ expect(await Promise.all(first.files.map((file) => readFile(file)))).toEqual(before);+ // One existing output, published last, rolls back every file this call had published.+ const partial = join(root, 'partial');+ await mkdir(partial);+ await writeFile(join(partial, 'leaf-litter.preview.png'), 'keep');+ await expect(+ exportMaterialMaps(record, { outDir: partial, size: 8, repeatMeters: 1 }),+ ).rejects.toThrow(/already exists/);+ expect(await readdir(partial)).toEqual(['leaf-litter.preview.png']);+ expect(await readFile(join(partial, 'leaf-litter.preview.png'), 'utf8')).toBe('keep');+}, 60_000);++test('rejects bad sizes, repeats and tile counts before writing', async () => {+ const outDir = join(root, 'invalid');+ const cases: [Record<string, unknown>, RegExp][] = [+ [{ size: 0, repeatMeters: 1 }, /size/],+ [{ size: 3, repeatMeters: 1 }, /size/],+ [{ size: 4097, repeatMeters: 1 }, /size/],+ [{ size: 15.5, repeatMeters: 1 }, /size/],+ [{ size: Number.NaN, repeatMeters: 1 }, /size/],+ [{ size: 16, repeatMeters: 0 }, /repeat/],+ [{ size: 16, repeatMeters: -2 }, /repeat/],+ [{ size: 16, repeatMeters: Number.POSITIVE_INFINITY }, /repeat/],+ [{ size: 16, repeatMeters: 1, tiles: 0 }, /tiles/],+ [{ size: 16, repeatMeters: 1, tiles: 9 }, /tiles/],+ [{ size: 16, repeatMeters: 1, tiles: 2.5 }, /tiles/],+ ];+ for (const [options, message] of cases)+ await expect(+ exportMaterialMaps(record, { outDir, ...(options as { size: number }) }),+ ).rejects.toThrow(message);+ await expect(readdir(outDir)).rejects.toThrow();+});++test('repeat defaults to a square physical size and is required otherwise', async () => {+ const defaulted = await exportMaterialMaps(record, { outDir: join(root, 'default'), size: 8 });+ expect(defaulted.sidecar.repeatMeters).toEqual({ width: 4, height: 4 });+ const { physicalSizeMeters: _, ...manifest } = record.manifest;+ const unsized = { ...record, manifest } as MaterialRecord;+ await expect(+ exportMaterialMaps(unsized, { outDir: join(root, 'unsized'), size: 8 }),+ ).rejects.toThrow(/repeat/);+}, 60_000);++test('the preview routes through an injected render port and records its fidelity', async () => {+ const cell = await sharp({+ create: { width: 384, height: 384, channels: 4, background: { r: 90, g: 70, b: 40, alpha: 1 } },+ })+ .png()+ .toBuffer();+ let requests = 0;+ const port: PbrRenderPort = async (request) => {+ requests++;+ expect(request.glb.byteLength).toBeGreaterThan(0);+ return {+ ok: true,+ rendererId: 'fixture-gpu',+ viewsPng: (request.viewDirs ?? [[0, 0, 1]]).map(() => new Uint8Array(cell)),+ };+ };+ const gpu = await exportMaterialMaps(record, {+ outDir: join(root, 'gpu'),+ size: 8,+ repeatMeters: 4,+ viewRenderPort: port,+ });+ expect(requests).toBe(1);+ expect(gpu.sidecar.preview.rendererId).toBe('fixture-gpu');+ expect(gpu.sidecar.preview.viewFidelity).toMatchObject({+ materialFaithful: true,+ delivered: 'full-material',+ degraded: false,+ rendererId: 'fixture-gpu',+ });++ const failing: PbrRenderPort = async () => ({ ok: false, rendererId: '', error: 'no adapter' });+ const degraded = await exportMaterialMaps(record, {+ outDir: join(root, 'degraded'),+ size: 8,+ repeatMeters: 4,+ viewRenderPort: failing,+ });+ expect(degraded.sidecar.preview.rendererId).toStartWith('cpu-raster');+ expect(degraded.sidecar.preview.viewFidelity).toMatchObject({+ materialFaithful: false,+ degraded: true,+ degradeReason: 'no adapter',+ });++ const requiredDir = join(root, 'required');+ await expect(+ exportMaterialMaps(record, {+ outDir: requiredDir,+ size: 8,+ repeatMeters: 4,+ viewRenderPort: failing,+ viewRenderRequired: true,+ }),+ ).rejects.toThrow(/GPU/);+ await expect(readdir(requiredDir)).rejects.toThrow();+}, 60_000);diff --git a/src/project-cli.test.ts b/src/project-cli.test.tsindex fea52d0c..abb58128 100644--- a/src/project-cli.test.ts+++ b/src/project-cli.test.ts@@ -3,6 +3,9 @@ import { spawnSync } from 'node:child_process';import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';+import { existsSync } from 'node:fs';+import { FileWorkspace } from './workspace-node';+import { exportMaterialMaps } from './material-library-node';async function fixture() {const root = await mkdtemp(join(tmpdir(), 'kiln-project-cli-'));@@ -202,3 +205,134 @@ test('material CLI creates deterministic recipes and exports/imports exact portaawait rm(root, { recursive: true, force: true });}}, 60_000); // Eleven compiled-CLI runs: 4.6 to 7.1 s in the gates of 2 October 2026; past 20 s on the same loaded host (6.1 s in that run's coverage step).++test('material export --maps writes sized PNGs, a hashed sidecar and a preview, matching the SDK', async () => {+ const { root, run } = await fixture();+ try {+ const file = join(root, 'material.json');+ await writeFile(+ file,+ JSON.stringify({+ materialId: 'coarse-soil',+ name: 'Coarse soil',+ tileable: true,+ sources: [+ {+ id: 'authored',+ kind: 'procedural',+ provider: 'Kiln',+ creator: 'Fixture',+ license: {+ spdx: 'CC0-1.0',+ url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ attribution: '',+ },+ originalFiles: [],+ },+ ],+ maps: [+ {+ slot: 'baseColor',+ sourceId: 'authored',+ transforms: [],+ procedural: {+ schemaVersion: 2,+ usage: 'albedo',+ size: 8,+ layers: [{ op: 'noise', colorA: 0x554433, colorB: 0x887766, seed: 3, scale: 4 }],+ },+ },+ {+ slot: 'normal',+ sourceId: 'authored',+ transforms: [],+ procedural: {+ schemaVersion: 2,+ usage: 'normal',+ size: 8,+ layers: [{ op: 'noise', colorA: 0, colorB: 0xffffff, seed: 3, scale: 4 }],+ },+ derive: { kind: 'normal-from-height', strength: 4 },+ },+ ],+ }),+ );+ const created = run(['material', 'procedural', '--file', file]);+ expect(created.status, created.stderr).toBe(0);+ const { revisionId } = JSON.parse(created.stdout).materials[0];+ const maps = join(root, 'maps');+ const args = ['material', 'export', 'coarse-soil', revisionId, '--maps', maps];+ // No physical size is recorded, so the repeat must be stated.+ const unsized = run([...args, '--size', '16']);+ expect(unsized.status).toBe(1);+ expect(unsized.stderr).toContain('--repeat');+ for (const bad of [+ ['--size', '0', '--repeat', '4'],+ ['--size', 'large', '--repeat', '4'],+ ['--size', '16.5', '--repeat', '4'],+ ['--size', '16', '--repeat', '-1'],+ ['--size', '16', '--repeat', '4m'],+ ['--size', '16', '--repeat', '4', '--tiles', '0'],+ ['--size', '16', '--repeat', '4', '--out', join(root, 'both.json')],+ ])+ expect(run([...args, ...bad]).status).toBe(1);+ expect(+ run([+ 'material',+ 'export',+ 'coarse-soil',+ revisionId,+ '--out',+ join(root, 'x'),+ '--size',+ '16',+ ]).status,+ ).toBe(1);+ expect(existsSync(maps)).toBe(false);++ const exported = run([...args, '--size', '16', '--repeat', '4']);+ expect(exported.status, exported.stderr).toBe(0);+ const output = JSON.parse(exported.stdout);+ expect(output.materialId).toBe('coarse-soil');+ expect(output.revisionId).toBe(revisionId);+ expect(output.sidecar).toBe(join(maps, 'coarse-soil.maps.json'));+ const sidecar = JSON.parse(await readFile(output.sidecar, 'utf8'));+ expect(sidecar.size).toEqual({ width: 16, height: 16 });+ expect(sidecar.repeatMeters).toEqual({ width: 4, height: 4 });+ expect(sidecar.maps.map((map: { file: string }) => map.file)).toEqual([+ 'coarse-soil.baseColor.png',+ 'coarse-soil.normal.png',+ ]);+ expect(sidecar.preview.file).toBe('coarse-soil.preview.png');+ expect(sidecar.preview.viewFidelity.materialFaithful).toBe(false);+ expect(output.preview.materialFaithful).toBe(false);+ expect(output.preview.rendererId).toBe(sidecar.preview.rendererId);++ // The CLI never replaces an earlier export.+ const before = await readFile(output.sidecar);+ const again = run([...args, '--size', '16', '--repeat', '4']);+ expect(again.status).toBe(1);+ expect(again.stderr).toContain('already exists');+ expect(await readFile(output.sidecar)).toEqual(before);++ // SDK parity: the same record and options produce the same sidecar and bytes.+ const record = await new FileWorkspace(join(root, 'first')).materials.read(+ 'coarse-soil',+ revisionId,+ );+ const sdk = await exportMaterialMaps(record, {+ outDir: join(root, 'sdk'),+ size: 16,+ repeatMeters: 4,+ });+ expect(sdk.sidecar).toEqual(sidecar);++ // The JSON payload export is unchanged.+ const payload = join(root, 'payload.json');+ const json = run(['material', 'export', 'coarse-soil', revisionId, '--out', payload]);+ expect(json.status, json.stderr).toBe(0);+ expect(JSON.parse(await readFile(payload, 'utf8')).records).toHaveLength(1);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+}, 120_000); // Thirteen compiled-CLI runs and one in-process export; budget follows the material test above under load.diff --git a/src/project-cli.ts b/src/project-cli.tsindex 546b2ffa..9b6a0b2c 100644--- a/src/project-cli.ts+++ b/src/project-cli.ts@@ -12,6 +12,8 @@ import {resolveMaterialRecordClosure,} from './material-library-node';import { createProceduralMaterialRecord } from './material-authoring-node';+import { exportMaterialMaps, validateMaterialMapExportOptions } from './material-map-export-node';+import { buildRenderPort, resolveRenderMode } from './cli-render-mode';import { writeNewDestinationsAtomic } from './cli-output';import { localAssetLibrary } from './assets-node';import { exportWorkspaceProjectBundle, importWorkspaceProjectBundle } from './project-bundle-node';@@ -35,6 +37,8 @@ MATERIALSkiln material procedural --file <procedural-material-draft.json>kiln material import --file <portable-material-payload.json>kiln material export <id> <sha256:revision> --out <portable-material-payload.json>+ kiln material export <id> <sha256:revision> --maps <dir> --size <px> [--repeat <metres>]+ [--tiles <n>] [--render auto|cpu|gpu]Project changes create immutable revisions. Updates require the current expectedrevision; supplied top-level fields replace their previous values.@@ -51,6 +55,14 @@ Projects are optional. Authoring stays standalone unless --project or KILN_PROJEselects a project; --no-project overrides that configured default. Use --materialswith an array of exact resourceId/revisionId/sha256 pins for standalone materials.All commands return JSON; export refuses to overwrite an existing destination.++Material export --maps writes <id>.<slot>.png for each map at --size pixels square,+<id>.preview.png (the material on a lit plane repeated --tiles × --tiles, default 3)+and the <id>.maps.json sidecar: each map's slot, colour space, size, sha256 and how it+was produced. A V2 layer recipe is recompiled at a power-of-two size up to 1024; other+sizes resample with a wrapped Catmull-Rom filter. --repeat is the real-world edge of one+tile in metres; it defaults to a square recorded physical size. The sidecar records the+preview's renderer and viewFidelity: a CPU preview shows geometry, not material.`;/** Read only the file the operator explicitly named, with a hard allocation bound. */@@ -78,6 +90,68 @@ async function jsonFile(path: string, limit: number): Promise<unknown> {return JSON.parse((await inputFile(path, limit)).toString('utf8').replace(/^\uFEFF/, ''));}+/** `material export --maps`: a strict decimal reading, then the SDK's own range checks. */+async function exportMaterialMapsCommand(+ materials: FileWorkspace['materials'],+ positional: readonly string[],+ flags: Record<string, string>,+): Promise<unknown> {+ const integer = (name: string) => {+ const value = flags[name];+ if (value === undefined) return undefined;+ if (!/^[0-9]+$/.test(value)) throw new Error(`--${name} must be a whole number`);+ return Number(value);+ };+ const size = integer('size');+ if (size === undefined) throw new Error('material export --maps requires --size <px>');+ const repeat = flags.repeat;+ if (repeat !== undefined && !/^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(repeat))+ throw new Error('--repeat must be a decimal number of metres');+ const tiles = integer('tiles');+ // Validate every option before reading the record or starting a renderer.+ validateMaterialMapExportOptions({+ size,+ ...(repeat !== undefined ? { repeatMeters: Number(repeat) } : {}),+ ...(tiles !== undefined ? { tiles } : {}),+ });+ const record = await materials.read(positional[0]!, positional[1]!);+ const context = await buildRenderPort(resolveRenderMode(flags.render), undefined);+ const result = await exportMaterialMaps(record, {+ outDir: flags.maps!,+ size,+ ...(repeat !== undefined ? { repeatMeters: Number(repeat) } : {}),+ ...(tiles !== undefined ? { tiles } : {}),+ ...(context.viewRenderPort ? { viewRenderPort: context.viewRenderPort } : {}),+ ...(context.viewRenderTimeoutMs ? { viewRenderTimeoutMs: context.viewRenderTimeoutMs } : {}),+ ...(context.viewRenderRequired ? { viewRenderRequired: true } : {}),+ });+ const { preview } = result.sidecar;+ return {+ materialId: result.sidecar.material.materialId,+ revisionId: result.sidecar.material.revisionId,+ directory: result.directory,+ sidecar: result.sidecarPath,+ files: result.files,+ size: result.sidecar.size,+ repeatMeters: result.sidecar.repeatMeters,+ maps: result.sidecar.maps.map(({ slot, file, colorSpace, method }) => ({+ slot,+ file,+ colorSpace,+ method,+ })),+ preview: {+ file: result.previewPath,+ rendererId: preview.rendererId,+ materialFaithful: preview.viewFidelity.materialFaithful,+ delivered: preview.viewFidelity.delivered,+ ...(preview.viewFidelity.degradeReason+ ? { degradeReason: preview.viewFidelity.degradeReason }+ : {}),+ },+ };+}+export async function projectMain(argv: readonly string[]): Promise<number> {const [family, action] = argv;if (argv.some((value) => value === '--help' || value === '-h')) {@@ -105,7 +179,7 @@ export async function projectMain(argv: readonly string[]): Promise<number> {'material:get': [],'material:procedural': ['file'],'material:import': ['file'],- 'material:export': ['out'],+ 'material:export': ['out', 'maps', 'size', 'repeat', 'tiles', 'render'],};const flags: Record<string, string> = {};const positional: string[] = [];@@ -223,8 +297,14 @@ export async function projectMain(argv: readonly string[]): Promise<number> {manifest,portableSpec: materialLibraryPortableSpec(manifest),};- else {- if (!flags.out) throw new Error('material export requires --out');+ else if (flags.maps !== undefined) {+ if (flags.out) throw new Error('Use --out or --maps, not both');+ output = await exportMaterialMapsCommand(materials, positional, flags);+ } else {+ for (const name of ['size', 'repeat', 'tiles', 'render'])+ if (flags[name] !== undefined)+ throw new Error(`--${name} applies only to material export --maps`);+ if (!flags.out) throw new Error('material export requires --out or --maps');const records = await resolveMaterialRecordClosure([manifest], {readManifest: (id, revision) => materials.readManifest(id, revision),read: (id, revision) => materials.readRecordFiles(id, revision),