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.

Roll in Pixel Forge foundation cleanup

Matt Kissingerd88ee01117c5
diff --git a/imposter/__tests__/animated-schema.test.ts b/imposter/__tests__/animated-schema.test.ts
index 91c08846..048daeff 100644
--- a/imposter/__tests__/animated-schema.test.ts
+++ b/imposter/__tests__/animated-schema.test.ts
@@ -106,6 +106,25 @@ describe('AnimatedImposterMetaSchema', () => {
expect(decoded).toEqual(VALID);
});
+ test('accepts source attachments for baked weapons', () => {
+ const withAttachment = {
+ ...VALID,
+ source: {
+ ...VALID.source,
+ attachments: [
+ {
+ id: 'ak47',
+ kind: 'weapon',
+ sourcePath: 'tmp/weapon-rig-lab/weapons/ak47.glb',
+ bytes: 67_588,
+ hash: '1fab1876b236f1cf2c5759cb7e669c5badf7fc4195fd6640c35f46c515c43ce8',
+ },
+ ],
+ },
+ };
+ expect(AnimatedImposterMetaSchema.parse(withAttachment).source.attachments?.[0]?.id).toBe('ak47');
+ });
+
test('rejects the static imposter kind', () => {
const bad = { ...VALID, kind: 'imposter' };
expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();
diff --git a/imposter/__tests__/animated-validate.test.ts b/imposter/__tests__/animated-validate.test.ts
index 342e4d77..93b0a23f 100644
--- a/imposter/__tests__/animated-validate.test.ts
+++ b/imposter/__tests__/animated-validate.test.ts
@@ -75,6 +75,15 @@ describe('validateAnimatedImposterPreBake', () => {
expect(report.clipResolution.clips.walking?.resolved).toBe('Walk');
});
+ test('accepts 7x7 as the centered-front review grid', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ viewGrid: { x: 7, y: 7 },
+ });
+ expect(report.ok).toBe(true);
+ expect(report.warnings.map((issue) => issue.code)).not.toContain('ANIMATED_IMPOSTER_VIEW_GRID_UNPROVEN');
+ });
+
test('blocks non-skinned sources', () => {
const report = validateAnimatedImposterPreBake({
...VALID,
@@ -110,6 +119,22 @@ describe('validateAnimatedImposterPreBake', () => {
expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_CLIP_FALLBACK');
});
+ test('allows a logical target to use an explicit raw source clip fallback', () => {
+ const report = validateAnimatedImposterPreBake({
+ ...VALID,
+ source: {
+ ...VALID.source,
+ clipNames: ['Armature|Walk_Fight_Forward|baselayer'],
+ },
+ clipTargets: ['shoot'],
+ clipFallbacks: [{ target: 'shoot', rawName: 'Armature|Walk_Fight_Forward|baselayer' }],
+ });
+ expect(report.ok).toBe(true);
+ expect(report.clipResolution.clips.shoot?.rawName).toBe('Armature|Walk_Fight_Forward|baselayer');
+ expect(report.clipResolution.clips.shoot?.matchedBy).toBe('fallback');
+ expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_CLIP_FALLBACK');
+ });
+
test('blocks if no requested clips resolve', () => {
const report = validateAnimatedImposterPreBake({
...VALID,
diff --git a/imposter/__tests__/bake.test.ts b/imposter/__tests__/bake.test.ts
index 79638c0d..e18d1f56 100644
--- a/imposter/__tests__/bake.test.ts
+++ b/imposter/__tests__/bake.test.ts
@@ -13,8 +13,9 @@ import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import sharp from 'sharp';
-import { bakeImposter } from '../bake';
+import { bakeImposter, bleedTransparentRgb } from '../bake';
import { ImposterMetaSchema } from '../schema';
const LIVE = process.env.KILN_IMPOSTER_LIVE === '1';
@@ -49,8 +50,10 @@ describe.if(LIVE)('bakeImposter (live)', () => {
angles: 16,
axis: 'hemi-y',
tileSize: 256,
- auxLayers: ['depth'],
+ auxLayers: ['normal', 'depth'],
bgColor: 'transparent',
+ colorLayer: 'baseColor',
+ edgeBleedPx: 2,
sourcePath: fixture,
});
@@ -63,17 +66,46 @@ describe.if(LIVE)('bakeImposter (live)', () => {
expect(meta.atlasHeight).toBe(1024);
expect(meta.source.tris).toBeGreaterThan(0);
expect(meta.worldSize).toBeGreaterThan(0);
+ expect(meta.colorLayer).toBe('baseColor');
+ expect(meta.auxLayers).toContain('normal');
+ expect(meta.normalSpace).toBe('capture-view');
+ expect(meta.edgeBleedPx).toBe(2);
// Albedo atlas is a valid PNG buffer.
expect(result.atlas.byteLength).toBeGreaterThan(1000);
expect(result.atlas.subarray(0, 4).toString('hex')).toBe('89504e47'); // PNG magic
+ // Aux normal atlas present.
+ expect(result.aux.normal).toBeTruthy();
+ expect(result.aux.normal!.byteLength).toBeGreaterThan(1000);
+
// Aux depth atlas present.
expect(result.aux.depth).toBeTruthy();
expect(result.aux.depth!.byteLength).toBeGreaterThan(1000);
}, 60_000);
});
+describe('bleedTransparentRgb', () => {
+ test('extends RGB into transparent pixels without changing alpha', async () => {
+ const input = Buffer.from([
+ 0, 0, 0, 0, 80, 140, 30, 255,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ ]);
+ const png = await sharp(input, { raw: { width: 2, height: 2, channels: 4 } }).png().toBuffer();
+ const out = await bleedTransparentRgb(png, 1);
+ const { data } = await sharp(out).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+
+ expect(data[0]).toBe(80);
+ expect(data[1]).toBe(140);
+ expect(data[2]).toBe(30);
+ expect(data[3]).toBe(0);
+ expect(data[4]).toBe(80);
+ expect(data[5]).toBe(140);
+ expect(data[6]).toBe(30);
+ expect(data[7]).toBe(255);
+ });
+});
+
// When LIVE is off, still run at least one placeholder so bun reports the file.
describe.if(!LIVE)('bakeImposter (skipped)', () => {
test('set KILN_IMPOSTER_LIVE=1 to run', () => {
diff --git a/imposter/__tests__/npc-character-pack.test.ts b/imposter/__tests__/npc-character-pack.test.ts
new file mode 100644
index 00000000..6ba0c6d7
--- /dev/null
+++ b/imposter/__tests__/npc-character-pack.test.ts
@@ -0,0 +1,229 @@
+import { describe, expect, test } from 'bun:test';
+
+import {
+ NpcCharacterPackManifestSchema,
+ validateNpcCharacterPack,
+} from '../npc-character-pack';
+
+function makeManifest(): unknown {
+ const clips = [
+ ['idle', ['idle']],
+ ['patrol_walk', ['patrolling']],
+ ['traverse_run', ['seeking_cover']],
+ ['walk_fight_forward', ['engaging', 'advancing']],
+ ['death_fall_back', ['dead']],
+ ] as const;
+
+ return {
+ id: 'test-pack',
+ createdFrom: { base: 'test' },
+ policy: {
+ promoteToWarAssets: false,
+ recoil: 'Runtime procedural.',
+ excludedClips: [{ id: 'walk_forward_while_shooting', reason: 'Rejected in review.' }],
+ },
+ socketContract: {
+ characterForward: '+Z',
+ weaponForward: '+X',
+ rightHandBone: 'RightHand',
+ leftHandBone: 'LeftHand',
+ runtimeNotes: ['Attach weapon at runtime.'],
+ },
+ factions: {
+ nva: { label: 'NVA regular', headgear: 'pith-cap', primaryWeapon: 'ak47' },
+ },
+ clips: clips.map(([id, states]) => ({
+ id,
+ label: id,
+ tijStates: states,
+ status: 'candidate',
+ note: 'Test clip.',
+ })),
+ outputs: clips.map(([id, states]) => ({
+ faction: 'nva',
+ clip: id,
+ label: `nva ${id}`,
+ path: `tmp/${id}.glb`,
+ bytes: 1000,
+ tijStates: states,
+ status: 'candidate',
+ primaryWeapon: 'ak47',
+ })),
+ };
+}
+
+function makePackagedManifest(): unknown {
+ const source = makeManifest() as {
+ id: string;
+ socketContract: unknown;
+ factions: unknown;
+ clips: Array<{
+ id: string;
+ label: string;
+ tijStates: string[];
+ status: string;
+ note: string;
+ }>;
+ outputs: Array<{
+ faction: string;
+ clip: string;
+ label: string;
+ path: string;
+ bytes: number;
+ tijStates: string[];
+ status: string;
+ primaryWeapon: string;
+ }>;
+ };
+
+ return {
+ schemaVersion: 1,
+ id: source.id,
+ sourceManifest: '../../source/manifest.json',
+ generatedAt: '2026-04-28T00:00:00.000Z',
+ promoteToWarAssets: false,
+ note: 'Review-only package.',
+ settings: {
+ viewGrid: { x: 7, y: 7, count: 49 },
+ tileSize: 96,
+ framesPerClip: 8,
+ textureLayout: 'atlas',
+ textureFormat: 'rgba8-debug',
+ },
+ socketContract: source.socketContract,
+ factions: source.factions,
+ clips: source.clips,
+ weapons: {},
+ combinedGlbs: {
+ nva: {
+ uri: 'glb-combined/nva.glb',
+ bytes: 2000,
+ hash: 'abc',
+ animations: source.clips.map((clip) => clip.id),
+ },
+ },
+ entries: source.outputs.map((output) => ({
+ faction: output.faction,
+ factionLabel: 'NVA regular',
+ clip: output.clip,
+ clipLabel: output.label,
+ status: output.status,
+ tijStates: output.tijStates,
+ primaryWeapon: output.primaryWeapon,
+ glb: {
+ uri: output.path,
+ bytes: output.bytes,
+ hash: 'abc',
+ },
+ impostor: {
+ dir: `impostors/${output.faction}/${output.clip}`,
+ sidecar: `impostors/${output.faction}/${output.clip}/animated-imposter.json`,
+ atlas: `impostors/${output.faction}/${output.clip}/animated-albedo-packed.png`,
+ frameStrip: `impostors/${output.faction}/${output.clip}/animated-frame-strip.png`,
+ atlasHash: 'abc',
+ sidecarValid: true,
+ storage: {
+ colorBytes: 100,
+ totalRawBytes: 100,
+ envelopeBytes: 1000,
+ fitsEnvelope: true,
+ },
+ warnings: [],
+ },
+ })),
+ totals: {
+ entries: source.outputs.length,
+ glbBytes: source.outputs.reduce((sum, output) => sum + output.bytes, 0),
+ atlasPngBytes: 1000,
+ rawImpostorBytes: 500,
+ warnings: 0,
+ },
+ };
+}
+
+describe('NpcCharacterPackManifestSchema', () => {
+ test('accepts the minimum TIJ character pack contract', () => {
+ expect(() => NpcCharacterPackManifestSchema.parse(makeManifest())).not.toThrow();
+ });
+
+ test('accepts the packaged review bundle contract', () => {
+ expect(() => NpcCharacterPackManifestSchema.parse(makePackagedManifest())).not.toThrow();
+ });
+});
+
+describe('validateNpcCharacterPack', () => {
+ test('accepts a complete manifest without filesystem checks', async () => {
+ const report = await validateNpcCharacterPack(makeManifest(), { checkFiles: false });
+ expect(report.ok).toBe(true);
+ expect(report.blockers).toEqual([]);
+ expect(report.metrics.factions.nva?.outputs).toBe(5);
+ expect(report.metrics.factions.nva?.clips).toBe(5);
+ });
+
+ test('accepts a packaged review manifest without filesystem checks', async () => {
+ const report = await validateNpcCharacterPack(makePackagedManifest(), { checkFiles: false });
+ expect(report.ok).toBe(true);
+ expect(report.blockers).toEqual([]);
+ expect(report.metrics.factions.nva?.outputs).toBe(5);
+ });
+
+ test('blocks missing GLB files when file checks are enabled', async () => {
+ const report = await validateNpcCharacterPack(makeManifest(), {
+ checkFiles: true,
+ inspectGlbs: false,
+ rootDir: process.cwd(),
+ });
+ expect(report.ok).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_OUTPUT_MISSING');
+ });
+
+ test('blocks outputs for unknown factions', async () => {
+ const manifest = makeManifest() as { outputs: Array<{ faction: string }> };
+ manifest.outputs[0]!.faction = 'unknown';
+ const report = await validateNpcCharacterPack(manifest, { checkFiles: false });
+ expect(report.ok).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_UNKNOWN_FACTION');
+ });
+
+ test('blocks missing hand socket names', async () => {
+ const manifest = makeManifest() as { socketContract: { rightHandBone: string; leftHandBone: string } };
+ manifest.socketContract.rightHandBone = '';
+ manifest.socketContract.leftHandBone = ' ';
+ const report = await validateNpcCharacterPack(manifest, { checkFiles: false });
+ expect(report.ok).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_RIGHT_HAND_BONE_MISSING');
+ expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_LEFT_HAND_BONE_MISSING');
+ });
+
+ test('reports invalid TIJ state mappings through the schema gate', async () => {
+ const manifest = makeManifest() as { clips: Array<{ tijStates: string[] }> };
+ manifest.clips[0]!.tijStates = ['dance'];
+ const report = await validateNpcCharacterPack(manifest, { checkFiles: false });
+ expect(report.ok).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_SCHEMA_INVALID');
+ });
+
+ test('blocks rejected clips from production outputs', async () => {
+ const manifest = makeManifest() as {
+ clips: Array<{ id: string; label: string; tijStates: string[]; status: string; note: string }>;
+ outputs: Array<{ clip: string; label: string; path: string; tijStates: string[] }>;
+ };
+ manifest.clips.push({
+ id: 'walk_forward_while_shooting',
+ label: 'Rejected walk shoot',
+ tijStates: ['engaging'],
+ status: 'rejected',
+ note: 'Rejected in review.',
+ });
+ manifest.outputs.push({
+ ...manifest.outputs[0]!,
+ clip: 'walk_forward_while_shooting',
+ label: 'Rejected output',
+ path: 'tmp/rejected.glb',
+ tijStates: ['engaging'],
+ });
+ const report = await validateNpcCharacterPack(manifest, { checkFiles: false });
+ expect(report.ok).toBe(false);
+ expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_EXCLUDED_CLIP_OUTPUT');
+ });
+});
diff --git a/imposter/__tests__/schema.test.ts b/imposter/__tests__/schema.test.ts
index 28bc3d2d..69e2fcf1 100644
--- a/imposter/__tests__/schema.test.ts
+++ b/imposter/__tests__/schema.test.ts
@@ -26,6 +26,10 @@ const VALID: ImposterMeta = {
source: { path: 'foo.glb', bytes: 12345, tris: 987 },
auxLayers: ['albedo', 'depth'],
bgColor: 'transparent',
+ colorLayer: 'beauty',
+ normalSpace: 'capture-view',
+ edgeBleedPx: 0,
+ textureColorSpace: 'srgb',
};
describe('ImposterMetaSchema', () => {
@@ -58,4 +62,25 @@ describe('ImposterMetaSchema', () => {
const noPath = { ...VALID, source: { bytes: 0, tris: 0 } };
expect(() => ImposterMetaSchema.parse(noPath)).not.toThrow();
});
+
+ test('defaults legacy sidecars to the beauty contract', () => {
+ const legacy = { ...VALID };
+ delete (legacy as Partial<ImposterMeta>).colorLayer;
+ delete (legacy as Partial<ImposterMeta>).normalSpace;
+ delete (legacy as Partial<ImposterMeta>).edgeBleedPx;
+ delete (legacy as Partial<ImposterMeta>).textureColorSpace;
+
+ const decoded = ImposterMetaSchema.parse(legacy);
+ expect(decoded.colorLayer).toBe('beauty');
+ expect(decoded.normalSpace).toBe('capture-view');
+ expect(decoded.edgeBleedPx).toBe(0);
+ expect(decoded.textureColorSpace).toBe('srgb');
+ });
+
+ test('requires normal output for baseColor production bakes', () => {
+ const bad = { ...VALID, colorLayer: 'baseColor' as const, auxLayers: ['albedo'] };
+ expect(() => ImposterMetaSchema.parse(bad)).toThrow();
+ const ok = { ...bad, auxLayers: ['albedo', 'normal'] };
+ expect(() => ImposterMetaSchema.parse(ok)).not.toThrow();
+ });
});
diff --git a/imposter/animated-bake.ts b/imposter/animated-bake.ts
index 81bf25d4..67b4cc84 100644
--- a/imposter/animated-bake.ts
+++ b/imposter/animated-bake.ts
@@ -38,6 +38,7 @@ export interface AnimatedTileCamera {
export interface BakeAnimatedImposterOptions {
clipTargets?: AnimatedClipTarget[];
clipFallbacks?: AnimatedImposterPreBakeInput['clipFallbacks'];
+ attachments?: AnimatedImposterAttachment[];
viewGrid?: { x: number; y: number };
tileSize?: number;
framesPerClip?: number;
@@ -47,6 +48,23 @@ export interface BakeAnimatedImposterOptions {
envelopeBytes?: number;
}
+export interface AnimatedImposterAttachment {
+ id: string;
+ kind: 'weapon';
+ glb: Buffer | string;
+ sourcePath?: string;
+ lengthMeters: number;
+ gripNames?: string[];
+ supportNames?: string[];
+ muzzleNames?: string[];
+ stockNames?: string[];
+ sourceForward?: [number, number, number];
+ pitchTrimDeg?: number;
+ forwardHold?: number;
+ gripOffset?: number;
+ socketMode?: 'shouldered-forward';
+}
+
export interface BakeAnimatedImposterResult {
atlas: Buffer;
frameAtlases: Buffer[];
@@ -73,6 +91,12 @@ interface LoadedAnimatedGlbInfo {
clipDurations: Record<string, number>;
}
+interface BrowserAttachmentInput extends Omit<AnimatedImposterAttachment, 'glb'> {
+ dataUrl: string;
+ bytes: number;
+ hash: string;
+}
+
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');
@@ -133,19 +157,24 @@ async function bakeAnimatedOnPage(
const textureLayout = opts.textureLayout ?? 'atlas';
const colorUri = opts.colorUri ?? 'animated-albedo-packed.png';
const envelopeBytes = opts.envelopeBytes ?? ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES;
+ const attachments = loadBrowserAttachments(opts.attachments ?? []);
if (textureLayout !== 'atlas') {
throw new Error('W2 animated imposter bake currently writes packed 2D atlas output only');
}
const loadInfo = (await page.evaluate(
- async ([dataUrl, tileSz]) => {
+ async ([dataUrl, tileSz, browserAttachments]) => {
const w = globalThis as unknown as {
- __animatedImposterLoadGlb: (dataUrl: string, tileSize: number) => Promise<LoadedAnimatedGlbInfo>;
+ __animatedImposterLoadGlb: (
+ dataUrl: string,
+ tileSize: number,
+ attachments: BrowserAttachmentInput[],
+ ) => Promise<LoadedAnimatedGlbInfo>;
};
- return w.__animatedImposterLoadGlb(dataUrl, tileSz);
+ return w.__animatedImposterLoadGlb(dataUrl, tileSz, browserAttachments);
},
- [`data:model/gltf-binary;base64,${buf.toString('base64')}`, tileSize] as const,
+ [`data:model/gltf-binary;base64,${buf.toString('base64')}`, tileSize, attachments] as const,
)) as LoadedAnimatedGlbInfo;
const preBake = validateAnimatedImposterPreBake({
@@ -228,6 +257,17 @@ async function bakeAnimatedOnPage(
skinned: loadInfo.skinned,
hash: createHash('sha256').update(buf).digest('hex'),
animationClips: loadInfo.clipNames,
+ ...(attachments.length
+ ? {
+ attachments: attachments.map((attachment) => ({
+ id: attachment.id,
+ kind: attachment.kind,
+ ...(attachment.sourcePath ? { sourcePath: attachment.sourcePath } : {}),
+ bytes: attachment.bytes,
+ hash: attachment.hash,
+ })),
+ }
+ : {}),
},
bbox: { min, max, worldSize, yOffset },
projection: 'orthographic',
@@ -244,6 +284,7 @@ async function bakeAnimatedOnPage(
rawName: clip.rawName,
matchedBy: clip.matchedBy,
...(clip.fallbackFor ? { fallbackFor: clip.fallbackFor } : {}),
+ ...(clip.fallbackRawName ? { fallbackRawName: clip.fallbackRawName } : {}),
frameCount: framesPerClip,
durationSec: durationForClip(loadInfo.clipDurations, clip.rawName!, clip.resolved!),
})),
@@ -288,6 +329,19 @@ async function bakeAnimatedOnPage(
};
}
+function loadBrowserAttachments(attachments: AnimatedImposterAttachment[]): BrowserAttachmentInput[] {
+ return attachments.map((attachment) => {
+ const buf = typeof attachment.glb === 'string' ? readFileSync(attachment.glb) : attachment.glb;
+ const { glb: _glb, ...rest } = attachment;
+ return {
+ ...rest,
+ dataUrl: `data:model/gltf-binary;base64,${buf.toString('base64')}`,
+ bytes: buf.byteLength,
+ hash: createHash('sha256').update(buf).digest('hex'),
+ };
+ });
+}
+
async function composeAtlas(
tilePngs: Buffer[],
tileWidth: number,
@@ -382,12 +436,18 @@ const fill = new THREE.DirectionalLight(0xffffff, 0.35);
fill.position.set(-1, 0.5, -1);
scene.add(fill);
+let actorGroup = null;
let root = null;
let mixer = null;
let clips = [];
let boundsRadius = 1;
let boundsCenter = new THREE.Vector3();
let originalMaterials = new Map();
+let bones = {};
+let rootMotionBase = null;
+let weaponPivot = new THREE.Group();
+let currentWeapon = null;
+let currentWeaponMeta = null;
function normalizeClipName(raw) {
let s = raw;
@@ -400,24 +460,58 @@ function findClip(rawName) {
|| clips.find((c) => normalizeClipName(c.name) === normalizeClipName(rawName));
}
-window.__animatedImposterLoadGlb = async (dataUrl, tileSize) => {
- if (root) scene.remove(root);
+window.__animatedImposterLoadGlb = async (dataUrl, tileSize, attachments = []) => {
+ if (actorGroup) scene.remove(actorGroup);
originalMaterials.clear();
+ bones = {};
+ rootMotionBase = null;
+ currentWeapon = null;
+ currentWeaponMeta = null;
+ weaponPivot = new THREE.Group();
if (renderer.domElement.width !== tileSize) renderer.setSize(tileSize, tileSize);
const loader = new GLTFLoader();
return new Promise((resolve, reject) => {
- loader.load(dataUrl, (gltf) => {
+ loader.load(dataUrl, async (gltf) => {
root = gltf.scene;
clips = gltf.animations || [];
mixer = new THREE.AnimationMixer(root);
- scene.add(root);
- const box = new THREE.Box3().setFromObject(root);
+ actorGroup = new THREE.Group();
+ actorGroup.add(root);
+ actorGroup.add(weaponPivot);
+ scene.add(actorGroup);
+ collectBones(root);
+ const firstClip = clips[0];
+ if (firstClip) {
+ const action = mixer.clipAction(firstClip);
+ action.reset();
+ action.setLoop(THREE.LoopRepeat, Infinity);
+ action.play();
+ mixer.setTime(0);
+ root.updateMatrixWorld(true);
+ }
+ rootMotionBase = bones.Hips ? bones.Hips.position.clone() : null;
+
+ if (attachments.length > 0) {
+ currentWeaponMeta = attachments[0];
+ try {
+ const weaponGltf = await loadGltf(loader, currentWeaponMeta.dataUrl);
+ currentWeapon = weaponGltf.scene;
+ normalizeWeapon(currentWeapon, currentWeaponMeta);
+ weaponPivot.add(currentWeapon);
+ updateWeaponSocket();
+ } catch (error) {
+ console.warn('Animated imposter weapon attachment failed', error);
+ }
+ }
+
+ actorGroup.updateMatrixWorld(true);
+ const box = new THREE.Box3().setFromObject(actorGroup);
boundsCenter = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
boundsRadius = Math.sqrt(size.x * size.x + size.y * size.y + size.z * size.z) * 0.5 || 1;
let tris = 0;
let skinned = false;
- root.traverse((obj) => {
+ actorGroup.traverse((obj) => {
if (obj.isSkinnedMesh) skinned = true;
if (obj.isMesh && obj.material) {
originalMaterials.set(obj, obj.material);
@@ -459,9 +553,12 @@ window.__animatedImposterRenderTile = ({ dir, clipRawName, timeSec, tileSize })
action.setLoop(THREE.LoopRepeat, Infinity);
action.play();
mixer.setTime((timeSec || 0) % (clip.duration || 1));
+ lockRootMotion();
root.updateMatrixWorld(true);
+ updateWeaponSocket();
+ actorGroup?.updateMatrixWorld(true);
- root.traverse((o) => {
+ actorGroup.traverse((o) => {
if (o.isMesh && originalMaterials.has(o)) o.material = originalMaterials.get(o);
});
@@ -479,6 +576,215 @@ window.__animatedImposterRenderTile = ({ dir, clipRawName, timeSec, tileSize })
return renderer.domElement.toDataURL('image/png');
};
+function loadGltf(loader, dataUrl) {
+ return new Promise((resolve, reject) => {
+ loader.load(dataUrl, resolve, undefined, reject);
+ });
+}
+
+function collectBones(rootObject) {
+ bones = {};
+ rootObject.traverse((node) => {
+ if (node.isBone) bones[node.name] = node;
+ });
+}
+
+function findNamed(rootObject, names = []) {
+ for (const name of names) {
+ let found = null;
+ rootObject.traverse((node) => {
+ if (!found && node.name === name) found = node;
+ });
+ if (found) return found;
+ }
+ return null;
+}
+
+function centerOfObject(rootObject, object) {
+ if (!object) return null;
+ rootObject.updateMatrixWorld(true);
+ const box = new THREE.Box3().setFromObject(object);
+ if (box.isEmpty()) return null;
+ const center = box.getCenter(new THREE.Vector3());
+ return rootObject.worldToLocal(center.clone());
+}
+
+function normalizeWeapon(weaponRoot, weapon) {
+ weaponRoot.updateMatrixWorld(true);
+ const box = new THREE.Box3().setFromObject(weaponRoot);
+ const size = box.getSize(new THREE.Vector3());
+ const long = Math.max(size.x, size.y, size.z) || 1;
+ const scale = weapon.lengthMeters / long;
+ weaponRoot.scale.setScalar(scale);
+ const gripObject = findNamed(weaponRoot, weapon.gripNames || []);
+ const supportObject = findNamed(weaponRoot, weapon.supportNames || []);
+ const muzzleObject = findNamed(weaponRoot, weapon.muzzleNames || []);
+ const stockObject = findNamed(weaponRoot, weapon.stockNames || []);
+ const grip = centerOfObject(weaponRoot, gripObject) || new THREE.Vector3(0, 0, 0);
+ const support = centerOfObject(weaponRoot, supportObject);
+ const muzzle = centerOfObject(weaponRoot, muzzleObject);
+ const stock = centerOfObject(weaponRoot, stockObject);
+ const muzzleDirection = weapon.sourceForward
+ ? new THREE.Vector3(...weapon.sourceForward)
+ : muzzle
+ ? muzzle.clone().sub(grip)
+ : new THREE.Vector3(1, 0, 0);
+ const alignment = muzzleDirection.lengthSq() > 0.0001
+ ? new THREE.Quaternion().setFromUnitVectors(muzzleDirection.normalize(), new THREE.Vector3(1, 0, 0))
+ : new THREE.Quaternion();
+ weaponRoot.quaternion.copy(alignment);
+ const transformLocal = (point) => point.clone().multiplyScalar(scale).applyQuaternion(weaponRoot.quaternion);
+ const transformedGrip = transformLocal(grip);
+ weaponRoot.position.copy(transformedGrip.multiplyScalar(-1));
+ weaponRoot.userData.stockOffset = stock
+ ? transformLocal(stock).sub(transformLocal(grip))
+ : new THREE.Vector3(-0.28, 0.04, 0);
+ weaponRoot.userData.supportOffset = support
+ ? transformLocal(support).sub(transformLocal(grip))
+ : new THREE.Vector3(0.28, 0.02, 0);
+ weaponRoot.updateMatrixWorld(true);
+}
+
+function worldPosition(name) {
+ const bone = bones[name];
+ if (!bone) return null;
+ return bone.getWorldPosition(new THREE.Vector3());
+}
+
+function rootForward() {
+ const q = root.getWorldQuaternion(new THREE.Quaternion());
+ return new THREE.Vector3(0, 0, 1).applyQuaternion(q).normalize();
+}
+
+function bodyForward() {
+ const hips = bones.Hips || bones.Spine || root;
+ const q = hips.getWorldQuaternion(new THREE.Quaternion());
+ return new THREE.Vector3(0, 0, 1).applyQuaternion(q).normalize();
+}
+
+function lockRootMotion() {
+ if (!rootMotionBase || !bones.Hips) return;
+ bones.Hips.position.x = rootMotionBase.x;
+ bones.Hips.position.z = rootMotionBase.z;
+}
+
+const boneUp = new THREE.Vector3(0, 1, 0);
+
+function setBoneDirectionWorld(bone, directionWorld) {
+ if (!bone?.parent) return;
+ const direction = directionWorld.clone().normalize();
+ if (direction.lengthSq() < 0.0001) return;
+ const parentInv = bone.parent.getWorldQuaternion(new THREE.Quaternion()).invert();
+ const targetLocal = direction.applyQuaternion(parentInv).normalize();
+ bone.quaternion.setFromUnitVectors(boneUp, targetLocal);
+ bone.updateMatrixWorld(true);
+}
+
+function solveArmToTarget(side, target, axes) {
+ const upper = bones[side + 'Arm'];
+ const fore = bones[side + 'ForeArm'];
+ const hand = bones[side + 'Hand'];
+ if (!upper || !fore || !hand || !target) return;
+
+ root.updateMatrixWorld(true);
+ const shoulder = upper.getWorldPosition(new THREE.Vector3());
+ const elbowNow = fore.getWorldPosition(new THREE.Vector3());
+ const handNow = hand.getWorldPosition(new THREE.Vector3());
+ const upperLength = Math.max(0.001, shoulder.distanceTo(elbowNow));
+ const foreLength = Math.max(0.001, elbowNow.distanceTo(handNow));
+ const reach = Math.max(0.08, upperLength + foreLength - 0.025);
+ const targetVector = target.clone().sub(shoulder);
+ const distance = targetVector.length();
+ if (distance < 0.001) return;
+
+ const direction = targetVector.clone().normalize();
+ const clampedTarget = distance > reach
+ ? shoulder.clone().add(direction.clone().multiplyScalar(reach))
+ : target.clone();
+ const clampedDistance = Math.min(distance, reach);
+ const sideSign = side === 'Right' ? 1 : -1;
+ const pole = shoulder.clone()
+ .add(axes.cleanUp.clone().multiplyScalar(-0.24))
+ .add(axes.actorRight.clone().multiplyScalar(0.22 * sideSign))
+ .add(axes.forward.clone().multiplyScalar(0.04));
+ let planeNormal = direction.clone().cross(pole.clone().sub(shoulder)).normalize();
+ if (planeNormal.lengthSq() < 0.0001) planeNormal = axes.actorRight.clone().multiplyScalar(sideSign);
+ const bendDirection = planeNormal.clone().cross(direction).normalize();
+ const along = (upperLength * upperLength - foreLength * foreLength + clampedDistance * clampedDistance) / (2 * clampedDistance);
+ const height = Math.sqrt(Math.max(0, upperLength * upperLength - along * along));
+ const elbow = shoulder.clone()
+ .add(direction.clone().multiplyScalar(along))
+ .add(bendDirection.multiplyScalar(height));
+
+ setBoneDirectionWorld(upper, elbow.clone().sub(shoulder));
+ root.updateMatrixWorld(true);
+ const elbowWorld = fore.getWorldPosition(new THREE.Vector3());
+ setBoneDirectionWorld(fore, clampedTarget.clone().sub(elbowWorld));
+ root.updateMatrixWorld(true);
+}
+
+function updateWeaponSocket() {
+ if (!currentWeapon || !currentWeaponMeta) return;
+ const right = worldPosition('RightHand');
+ const leftShoulder = worldPosition('LeftArm') || worldPosition('LeftShoulder');
+ const rightShoulder = worldPosition('RightArm') || worldPosition('RightShoulder');
+ if (!right) return;
+
+ const up = new THREE.Vector3(0, 1, 0);
+ const travelForward = rootForward();
+ travelForward.y = 0;
+ if (travelForward.lengthSq() < 0.0001) travelForward.set(0, 0, 1);
+ travelForward.normalize();
+ const torsoForward = bodyForward();
+ torsoForward.y = 0;
+ if (torsoForward.lengthSq() < 0.0001) torsoForward.set(0, 0, 1);
+ torsoForward.normalize();
+ const forward = currentWeaponMeta.socketMode === 'shouldered-forward' ? travelForward : torsoForward;
+ let actorRight = new THREE.Vector3().crossVectors(forward, up).normalize();
+ if (leftShoulder && rightShoulder) {
+ const shoulderSpan = rightShoulder.clone().sub(leftShoulder);
+ shoulderSpan.y = 0;
+ if (shoulderSpan.lengthSq() > 0.0001) {
+ shoulderSpan.normalize();
+ if (shoulderSpan.dot(actorRight) < 0) shoulderSpan.multiplyScalar(-1);
+ actorRight = shoulderSpan;
+ }
+ }
+ const cleanUp = new THREE.Vector3().crossVectors(actorRight, forward).normalize();
+ const matrix = new THREE.Matrix4().makeBasis(forward, cleanUp, actorRight);
+ weaponPivot.quaternion.setFromRotationMatrix(matrix);
+ if (currentWeaponMeta.pitchTrimDeg) {
+ weaponPivot.rotateZ(THREE.MathUtils.degToRad(currentWeaponMeta.pitchTrimDeg));
+ }
+
+ const shoulder = rightShoulder || right;
+ const shoulderCenter = leftShoulder && rightShoulder
+ ? leftShoulder.clone().lerp(rightShoulder, 0.5)
+ : shoulder.clone().sub(actorRight.clone().multiplyScalar(0.12));
+ const shoulderPocket = shoulder.clone()
+ .lerp(shoulderCenter, 0.42)
+ .add(cleanUp.clone().multiplyScalar(-0.035));
+ const stockOffset = currentWeapon.userData.stockOffset instanceof THREE.Vector3
+ ? currentWeapon.userData.stockOffset.clone()
+ : new THREE.Vector3(-0.28, 0.04, 0);
+ const stockWorldOffset = stockOffset.applyQuaternion(weaponPivot.quaternion);
+ const offset = currentWeaponMeta.gripOffset || 0;
+ const stockAnchoredGrip = shoulderPocket.clone()
+ .add(forward.clone().multiplyScalar((currentWeaponMeta.forwardHold ?? 0.06) + offset))
+ .sub(stockWorldOffset);
+ weaponPivot.position.copy(stockAnchoredGrip).add(actorRight.clone().multiplyScalar(0.006));
+
+ const supportOffset = currentWeapon.userData.supportOffset instanceof THREE.Vector3
+ ? currentWeapon.userData.supportOffset.clone()
+ : new THREE.Vector3(0.28, 0.02, 0);
+ const supportTarget = weaponPivot.position.clone().add(supportOffset.applyQuaternion(weaponPivot.quaternion));
+ const gripTarget = weaponPivot.position.clone();
+ const axes = { forward, cleanUp, actorRight };
+ solveArmToTarget('Right', gripTarget, axes);
+ solveArmToTarget('Left', supportTarget, axes);
+ root.updateMatrixWorld(true);
+}
+
window.__animatedImposterReady = true;
</script>
</body></html>`;
diff --git a/imposter/animated-schema.ts b/imposter/animated-schema.ts
index 4b458071..f8a4117d 100644
--- a/imposter/animated-schema.ts
+++ b/imposter/animated-schema.ts
@@ -35,6 +35,16 @@ export const AnimatedImposterWarningSchema = z
const Vec3Schema = z.tuple([z.number(), z.number(), z.number()]);
+const AnimatedAttachmentMetaSchema = z
+ .object({
+ id: z.string().min(1),
+ kind: z.enum(['weapon']),
+ sourcePath: z.string().optional(),
+ bytes: z.number().int().nonnegative(),
+ hash: z.string().optional(),
+ })
+ .strict();
+
const AnimatedClipMetaSchema = z
.object({
target: AnimatedClipTargetSchema,
@@ -42,6 +52,7 @@ const AnimatedClipMetaSchema = z
rawName: z.string().nullable(),
matchedBy: z.enum(['exact', 'alias', 'fallback', 'missing']),
fallbackFor: AnimatedClipTargetSchema.optional(),
+ fallbackRawName: z.string().optional(),
frameCount: z.number().int().nonnegative(),
durationSec: z.number().positive().optional(),
})
@@ -73,6 +84,7 @@ export const AnimatedImposterMetaSchema = z
skinned: z.boolean(),
hash: z.string().optional(),
animationClips: z.array(z.string()),
+ attachments: z.array(AnimatedAttachmentMetaSchema).optional(),
})
.strict(),
bbox: z
@@ -296,9 +308,13 @@ export const AnimatedImposterPreBakeInputSchema = z
z
.object({
target: AnimatedClipTargetSchema,
- donor: AnimatedClipTargetSchema,
+ donor: AnimatedClipTargetSchema.optional(),
+ rawName: z.string().min(1).optional(),
})
- .strict(),
+ .strict()
+ .refine((value) => Boolean(value.donor) !== Boolean(value.rawName), {
+ message: 'clip fallback must set exactly one of donor or rawName',
+ }),
)
.default([]),
viewGrid: z
diff --git a/imposter/animated-validate.ts b/imposter/animated-validate.ts
index dd1ccd1e..b27970e6 100644
--- a/imposter/animated-validate.ts
+++ b/imposter/animated-validate.ts
@@ -16,6 +16,7 @@ import {
} from './animated-schema';
import {
applyClipFallbacks,
+ applyRawClipFallbacks,
resolveClips,
type ClipResolutionReport,
type ClipTarget,
@@ -139,6 +140,7 @@ export function validateAnimatedImposterPreBake(
let clipResolution = resolveClips(input.source.clipNames, toClipTargets(input.clipTargets));
if (input.clipFallbacks.length > 0) {
clipResolution = applyClipFallbacks(clipResolution, fallbackMap(input.clipFallbacks));
+ clipResolution = applyRawClipFallbacks(clipResolution, input.source.clipNames, rawFallbacks(input.clipFallbacks));
}
for (const target of input.clipTargets) {
@@ -151,10 +153,11 @@ export function validateAnimatedImposterPreBake(
fixHint: 'Add a clip fallback or remove the target from this bake slice.',
});
} else if (clip.matchedBy === 'fallback') {
+ const donor = clip.fallbackRawName ?? clip.fallbackFor;
add({
code: 'ANIMATED_IMPOSTER_CLIP_FALLBACK',
severity: 'warning',
- message: `${target} will use ${clip.fallbackFor} as a fallback clip.`,
+ message: `${target} will use ${donor} as a fallback clip.`,
fixHint: 'Treat the output as visually provisional until a dedicated clip exists.',
});
}
@@ -175,7 +178,7 @@ export function validateAnimatedImposterPreBake(
code: 'ANIMATED_IMPOSTER_VIEW_GRID_NOT_SQUARE',
severity: 'error',
message: 'The first octahedral view grid must be square.',
- fixHint: 'Use 6x6 or 8x8 for the first implementation slice.',
+ fixHint: 'Use 6x6, 7x7, or 8x8 for the first implementation slice.',
});
}
@@ -184,14 +187,14 @@ export function validateAnimatedImposterPreBake(
code: 'ANIMATED_IMPOSTER_VIEW_GRID_OUT_OF_RANGE',
severity: 'error',
message: 'View grid dimensions must stay between 4 and 16.',
- fixHint: 'Use 6x6 for the storage-safe spike or 8x8 for the quality spike.',
+ fixHint: 'Use 6x6 for the storage-safe spike, 7x7 for centered head-on reads, or 8x8 for the quality spike.',
});
- } else if (input.viewGrid.x !== 6 && input.viewGrid.x !== 8) {
+ } else if (![6, 7, 8].includes(input.viewGrid.x)) {
add({
code: 'ANIMATED_IMPOSTER_VIEW_GRID_UNPROVEN',
severity: 'warning',
- message: 'Only 6x6 and 8x8 view grids are part of the initial validation plan.',
- fixHint: 'Prefer 6x6 or 8x8 until yaw-sweep validation proves another grid.',
+ message: 'Only 6x6, 7x7, and 8x8 view grids are part of the initial validation plan.',
+ fixHint: 'Prefer 6x6, 7x7, or 8x8 until yaw-sweep validation proves another grid.',
});
}
@@ -287,7 +290,19 @@ function fallbackMap(
): Partial<Record<ClipTarget, ClipTarget>> {
const out: Partial<Record<ClipTarget, ClipTarget>> = {};
for (const fallback of fallbacks) {
- out[fallback.target as ClipTarget] = fallback.donor as ClipTarget;
+ if (fallback.donor) {
+ out[fallback.target as ClipTarget] = fallback.donor as ClipTarget;
+ }
+ }
+ return out;
+}
+
+function rawFallbacks(
+ fallbacks: AnimatedImposterPreBakeConfig['clipFallbacks'],
+): Array<{ target: ClipTarget; rawName: string }> {
+ const out: Array<{ target: ClipTarget; rawName: string }> = [];
+ for (const fallback of fallbacks) {
+ if (fallback.rawName) out.push({ target: fallback.target as ClipTarget, rawName: fallback.rawName });
}
return out;
}
diff --git a/imposter/bake.ts b/imposter/bake.ts
index 6f135a6e..1a0f74b8 100644
--- a/imposter/bake.ts
+++ b/imposter/bake.ts
@@ -28,6 +28,7 @@ import type {
ImposterAuxLayer,
ImposterAxis,
ImposterBgColor,
+ ImposterColorLayer,
ImposterMeta,
} from './schema';
import { IMPOSTER_SCHEMA_VERSION } from './schema';
@@ -42,6 +43,10 @@ export interface BakeImposterOptions {
auxLayers?: ImposterAuxLayer[];
/** Background color for the albedo bake. 'transparent' uses RGBA alpha. */
bgColor?: ImposterBgColor;
+ /** 'beauty' preserves legacy lit bakes; 'baseColor' emits unlit color for runtime lighting. */
+ colorLayer?: ImposterColorLayer;
+ /** RGB bleed radius into transparent pixels before atlas packing. Defaults to 2 for baseColor bakes. */
+ edgeBleedPx?: number;
/** Included in meta.source.path for provenance. */
sourcePath?: string;
}
@@ -105,8 +110,17 @@ async function bakeOnPage(
const angles = opts.angles;
const axis: ImposterAxis = opts.axis ?? (angles === 16 ? 'y' : 'hemi-y');
const tileSize = opts.tileSize ?? 512;
- const auxLayers = opts.auxLayers ?? [];
+ const auxLayers = uniqueAuxLayers(opts.auxLayers ?? []);
const bgColor: ImposterBgColor = opts.bgColor ?? 'transparent';
+ const colorLayer: ImposterColorLayer = opts.colorLayer ?? 'beauty';
+ const edgeBleedPx = opts.edgeBleedPx ?? (colorLayer === 'baseColor' && bgColor === 'transparent' ? 2 : 0);
+
+ if (!Number.isInteger(edgeBleedPx) || edgeBleedPx < 0) {
+ throw new Error(`edgeBleedPx must be a non-negative integer (got ${edgeBleedPx})`);
+ }
+ if (colorLayer === 'baseColor' && !auxLayers.includes('normal')) {
+ throw new Error("baseColor imposter bakes require auxLayers to include 'normal'");
+ }
const buf = typeof glb === 'string' ? readFileSync(glb) : glb;
const sourcePath = opts.sourcePath ?? (typeof glb === 'string' ? glb : undefined);
@@ -140,13 +154,14 @@ async function bakeOnPage(
dir: tile.dir,
layer,
bgColor,
+ colorLayer,
tileSize,
},
)) as string;
const png = Buffer.from(dataUrl.split(',')[1]!, 'base64');
tilePngs.push(png);
}
- atlases[layer] = await composeAtlas(tilePngs, tileSize, layout.tilesX, layout.tilesY, bgColor);
+ atlases[layer] = await composeAtlas(tilePngs, tileSize, layout.tilesX, layout.tilesY, bgColor, edgeBleedPx);
}
const albedo = atlases.albedo!;
@@ -189,6 +204,10 @@ async function bakeOnPage(
},
auxLayers: layers,
bgColor,
+ colorLayer,
+ normalSpace: 'capture-view',
+ edgeBleedPx,
+ textureColorSpace: 'srgb',
};
return { atlas: albedo, aux, meta };
@@ -200,6 +219,7 @@ async function composeAtlas(
tilesX: number,
tilesY: number,
bgColor: ImposterBgColor,
+ edgeBleedPx: number,
): Promise<Buffer> {
const width = tilesX * tileSize;
const height = tilesY * tileSize;
@@ -212,15 +232,83 @@ async function composeAtlas(
for (let idx = 0; idx < tilePngs.length; idx++) {
const i = idx % tilesX;
const j = Math.floor(idx / tilesX);
- composites.push({ input: tilePngs[idx]!, left: i * tileSize, top: j * tileSize });
+ const input = bgColor === 'transparent' && edgeBleedPx > 0
+ ? await bleedTransparentRgb(tilePngs[idx]!, edgeBleedPx)
+ : tilePngs[idx]!;
+ composites.push({ input, left: i * tileSize, top: j * tileSize });
}
- return sharp({
+ const atlas = await sharp({
create: { width, height, channels: 4, background: bg },
})
.composite(composites)
.png()
.toBuffer();
+
+ return bgColor === 'transparent' && edgeBleedPx > 0
+ ? bleedTransparentRgb(atlas, edgeBleedPx)
+ : atlas;
+}
+
+function uniqueAuxLayers(layers: ImposterAuxLayer[]): ImposterAuxLayer[] {
+ const out: ImposterAuxLayer[] = [];
+ for (const layer of layers) {
+ if (layer === 'albedo') continue;
+ if (!out.includes(layer)) out.push(layer);
+ }
+ return out;
+}
+
+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 });
+ const width = info.width;
+ const height = info.height;
+ let src = Buffer.from(data);
+ let dst = Buffer.from(data);
+
+ for (let pass = 0; pass < radius; pass++) {
+ let changed = false;
+ src.copy(dst);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const idx = (y * width + x) * 4;
+ if (src[idx + 3] !== 0) continue;
+
+ let r = 0;
+ let g = 0;
+ let b = 0;
+ let n = 0;
+ for (let oy = -1; oy <= 1; oy++) {
+ const ny = y + oy;
+ if (ny < 0 || ny >= height) continue;
+ for (let ox = -1; ox <= 1; ox++) {
+ if (ox === 0 && oy === 0) continue;
+ const nx = x + ox;
+ if (nx < 0 || nx >= width) continue;
+ const ni = (ny * width + nx) * 4;
+ if (src[ni + 3] === 0) continue;
+ r += src[ni]!;
+ g += src[ni + 1]!;
+ b += src[ni + 2]!;
+ n++;
+ }
+ }
+ if (n > 0) {
+ dst[idx] = Math.round(r / n);
+ dst[idx + 1] = Math.round(g / n);
+ dst[idx + 2] = Math.round(b / n);
+ changed = true;
+ }
+ }
+ }
+ if (!changed) break;
+ const tmp = src;
+ src = dst;
+ dst = tmp;
+ }
+
+ return sharp(src, { raw: { width, height, channels: 4 } }).png().toBuffer();
}
// ============================================================================
@@ -269,10 +357,12 @@ let root = null;
let boundsRadius = 1;
let boundsCenter = new THREE.Vector3();
let originalMaterials = new Map();
+let baseColorMaterials = new Map();
window.__imposterLoadGlb = async (dataUrl, tileSize) => {
if (root) scene.remove(root);
originalMaterials.clear();
+ baseColorMaterials.clear();
if (renderer.domElement.width !== tileSize) {
renderer.setSize(tileSize, tileSize);
}
@@ -291,6 +381,8 @@ window.__imposterLoadGlb = async (dataUrl, tileSize) => {
if (obj.isMesh && obj.material) {
originalMaterials.set(obj, obj.material);
const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
+ const baseMats = mats.map((material) => createBaseColorMaterial(material, obj.geometry));
+ baseColorMaterials.set(obj, Array.isArray(obj.material) ? baseMats : baseMats[0]);
for (const m of mats) {
m.side = THREE.FrontSide;
m.needsUpdate = true;
@@ -307,7 +399,22 @@ window.__imposterLoadGlb = async (dataUrl, tileSize) => {
});
};
-window.__imposterRenderTile = ({ dir, layer, bgColor, tileSize }) => {
+function createBaseColorMaterial(source, geometry) {
+ const mat = new THREE.MeshBasicMaterial({
+ color: source.color ? source.color.clone() : new THREE.Color(0xffffff),
+ map: source.map ?? null,
+ alphaMap: source.alphaMap ?? null,
+ vertexColors: Boolean(source.vertexColors || geometry?.attributes?.color),
+ opacity: source.opacity ?? 1,
+ transparent: Boolean(source.transparent || (source.opacity ?? 1) < 1 || source.alphaMap),
+ alphaTest: source.alphaTest ?? 0,
+ side: THREE.FrontSide,
+ });
+ mat.name = source.name ? source.name + '__baseColor' : 'baseColor';
+ return mat;
+}
+
+window.__imposterRenderTile = ({ dir, layer, bgColor, colorLayer, tileSize }) => {
if (!root) throw new Error('no GLB loaded');
if (renderer.domElement.width !== tileSize) renderer.setSize(tileSize, tileSize);
@@ -322,9 +429,15 @@ window.__imposterRenderTile = ({ dir, layer, bgColor, tileSize }) => {
});
root.traverse((o) => { if (o.isMesh) o.material = depthMat; });
} else {
- // albedo — restore originals
+ // albedo: legacy beauty restores original materials, production baseColor
+ // swaps to unlit MeshBasicMaterial so runtime lighting owns the shade.
root.traverse((o) => {
- if (o.isMesh && originalMaterials.has(o)) o.material = originalMaterials.get(o);
+ if (!o.isMesh) return;
+ if (colorLayer === 'baseColor' && baseColorMaterials.has(o)) {
+ o.material = baseColorMaterials.get(o);
+ } else if (originalMaterials.has(o)) {
+ o.material = originalMaterials.get(o);
+ }
});
}
diff --git a/imposter/clip-resolver.ts b/imposter/clip-resolver.ts
index 39d694d3..12fcc2e6 100644
--- a/imposter/clip-resolver.ts
+++ b/imposter/clip-resolver.ts
@@ -72,6 +72,8 @@ export interface ResolvedClip {
matchedBy: 'exact' | 'alias' | 'fallback' | 'missing';
/** If the matcher fell through to a best-guess, note what target was missing and what was used. */
fallbackFor?: ClipTarget;
+ /** If the fallback was a specific source clip, keep the requested raw name for traceability. */
+ fallbackRawName?: string;
}
export interface ClipResolutionReport {
@@ -208,3 +210,50 @@ export function applyClipFallbacks(
}
return next;
}
+
+export function applyRawClipFallbacks(
+ report: ClipResolutionReport,
+ clipNames: string[],
+ fallbacks: Array<{ target: ClipTarget; rawName: string }>,
+): ClipResolutionReport {
+ const next: ClipResolutionReport = {
+ clips: { ...report.clips },
+ missing: [...report.missing],
+ unmapped: [...report.unmapped],
+ };
+ const byRaw = new Map<string, string>();
+ const byNorm = new Map<string, string>();
+ for (const raw of clipNames) {
+ byRaw.set(raw.toLowerCase(), raw);
+ byNorm.set(normalizeClipName(raw).toLowerCase(), raw);
+ }
+
+ for (const fallback of fallbacks) {
+ const current = next.clips[fallback.target];
+ if (current?.resolved) continue;
+
+ const hit =
+ byRaw.get(fallback.rawName.toLowerCase()) ??
+ byNorm.get(normalizeClipName(fallback.rawName).toLowerCase());
+ if (!hit) continue;
+
+ const normalized = normalizeClipName(hit);
+ next.clips[fallback.target] = {
+ target: fallback.target,
+ resolved: normalized,
+ rawName: hit,
+ matchedBy: 'fallback',
+ fallbackRawName: fallback.rawName,
+ };
+
+ const missingIdx = next.missing.indexOf(fallback.target);
+ if (missingIdx >= 0) next.missing.splice(missingIdx, 1);
+
+ const unmappedIdx = next.unmapped.findIndex(
+ (raw) => raw === hit || normalizeClipName(raw).toLowerCase() === normalized.toLowerCase(),
+ );
+ if (unmappedIdx >= 0) next.unmapped.splice(unmappedIdx, 1);
+ }
+
+ return next;
+}
diff --git a/imposter/index.ts b/imposter/index.ts
index d884e951..71e2d5db 100644
--- a/imposter/index.ts
+++ b/imposter/index.ts
@@ -36,6 +36,9 @@ export type {
ImposterLayout,
ImposterAuxLayer,
ImposterBgColor,
+ ImposterColorLayer,
+ ImposterNormalSpace,
+ ImposterTextureColorSpace,
} from './schema';
export type {
AnimatedClipTarget,
@@ -84,3 +87,16 @@ export type {
BakeAnimatedImposterOptions,
BakeAnimatedImposterResult,
} from './animated-bake';
+
+export {
+ NpcCharacterPackManifestSchema,
+ validateNpcCharacterPack,
+} from './npc-character-pack';
+export type {
+ NpcCharacterPackFactionMetrics,
+ NpcCharacterPackIssue,
+ NpcCharacterPackManifest,
+ NpcCharacterPackOutputMetrics,
+ NpcCharacterPackValidationReport,
+ ValidateNpcCharacterPackOptions,
+} from './npc-character-pack';
diff --git a/imposter/npc-character-pack.ts b/imposter/npc-character-pack.ts
new file mode 100644
index 00000000..3a682257
--- /dev/null
+++ b/imposter/npc-character-pack.ts
@@ -0,0 +1,721 @@
+import { existsSync, statSync } from 'node:fs';
+import { isAbsolute, resolve } from 'node:path';
+
+import { NodeIO, type Mesh } from '@gltf-transform/core';
+import { z } from 'zod';
+
+const NpcCharacterPackClipStatusSchema = z.enum(['reference', 'review', 'candidate', 'approved', 'rejected']);
+const NpcCharacterPackTijStateSchema = z.enum([
+ 'idle',
+ 'patrolling',
+ 'alert',
+ 'engaging',
+ 'suppressing',
+ 'advancing',
+ 'retreating',
+ 'seeking_cover',
+ 'defending',
+ 'dead',
+ 'boarding',
+ 'in_vehicle',
+ 'dismounting',
+]);
+
+const NpcCharacterPackIssueSchema = z
+ .object({
+ code: z.string().min(1),
+ severity: z.enum(['info', 'warning', 'error']),
+ message: z.string().min(1),
+ path: z.string().optional(),
+ fixHint: z.string().optional(),
+ })
+ .strict();
+
+const NpcCharacterPackOutputSchema = z
+ .object({
+ faction: z.string().min(1),
+ clip: z.string().min(1),
+ label: z.string().min(1),
+ path: z.string().min(1),
+ bytes: z.number().int().nonnegative(),
+ tijStates: z.array(NpcCharacterPackTijStateSchema).min(1),
+ status: NpcCharacterPackClipStatusSchema,
+ primaryWeapon: z.string().min(1),
+ })
+ .strict();
+
+const NpcCharacterPackSourceManifestSchema = z
+ .object({
+ id: z.string().min(1),
+ createdFrom: z.record(z.string(), z.unknown()).default({}),
+ policy: z
+ .object({
+ promoteToWarAssets: z.boolean(),
+ recoil: z.string().min(1),
+ excludedClips: z
+ .array(
+ z
+ .object({
+ id: z.string().min(1),
+ reason: z.string().min(1),
+ })
+ .strict(),
+ )
+ .default([]),
+ })
+ .strict(),
+ socketContract: z
+ .object({
+ characterForward: z.string().min(1),
+ weaponForward: z.string().min(1),
+ rightHandBone: z.string(),
+ leftHandBone: z.string(),
+ runtimeNotes: z.array(z.string()).default([]),
+ })
+ .strict(),
+ factions: z.record(
+ z.string().min(1),
+ z
+ .object({
+ label: z.string().min(1),
+ headgear: z.string().min(1),
+ primaryWeapon: z.string().min(1),
+ })
+ .strict(),
+ ),
+ clips: z
+ .array(
+ z
+ .object({
+ id: z.string().min(1),
+ label: z.string().min(1),
+ tijStates: z.array(NpcCharacterPackTijStateSchema).min(1),
+ status: NpcCharacterPackClipStatusSchema,
+ note: z.string().min(1),
+ })
+ .strict(),
+ )
+ .min(1),
+ outputs: z.array(NpcCharacterPackOutputSchema).min(1),
+ })
+ .strict();
+
+const NpcCharacterPackPackagedEntrySchema = z
+ .object({
+ faction: z.string().min(1),
+ factionLabel: z.string().min(1),
+ clip: z.string().min(1),
+ clipLabel: z.string().min(1),
+ status: NpcCharacterPackClipStatusSchema,
+ tijStates: z.array(NpcCharacterPackTijStateSchema).min(1),
+ primaryWeapon: z.string().min(1),
+ glb: z
+ .object({
+ uri: z.string().min(1),
+ bytes: z.number().int().nonnegative(),
+ hash: z.string().min(1).optional(),
+ })
+ .strict(),
+ impostor: z
+ .object({
+ dir: z.string().min(1),
+ sidecar: z.string().min(1),
+ atlas: z.string().min(1),
+ frameStrip: z.string().min(1),
+ atlasHash: z.string().min(1).optional(),
+ sidecarValid: z.boolean(),
+ alphaCoverage: z.unknown().optional(),
+ storage: z
+ .object({
+ colorBytes: z.number().int().nonnegative(),
+ normalBytes: z.number().int().nonnegative().optional(),
+ depthBytes: z.number().int().nonnegative().optional(),
+ paletteBytes: z.number().int().nonnegative().optional(),
+ totalRawBytes: z.number().int().nonnegative(),
+ envelopeBytes: z.number().int().positive(),
+ fitsEnvelope: z.boolean(),
+ })
+ .strict(),
+ warnings: z.array(NpcCharacterPackIssueSchema),
+ })
+ .strict(),
+ })
+ .strict();
+
+const NpcCharacterPackPackagedManifestSchema = z
+ .object({
+ schemaVersion: z.literal(1),
+ id: z.string().min(1),
+ sourceManifest: z.string().min(1),
+ generatedAt: z.string().min(1),
+ promoteToWarAssets: z.boolean(),
+ note: z.string().min(1),
+ settings: z
+ .object({
+ viewGrid: z
+ .object({
+ x: z.number().int().positive(),
+ y: z.number().int().positive(),
+ count: z.number().int().positive(),
+ })
+ .strict(),
+ tileSize: z.number().int().positive(),
+ framesPerClip: z.number().int().positive(),
+ textureLayout: z.string().min(1),
+ textureFormat: z.string().min(1),
+ })
+ .strict(),
+ socketContract: z
+ .object({
+ characterForward: z.string().min(1),
+ weaponForward: z.string().min(1),
+ rightHandBone: z.string(),
+ leftHandBone: z.string(),
+ runtimeNotes: z.array(z.string()).default([]),
+ })
+ .strict(),
+ factions: z.record(
+ z.string().min(1),
+ z
+ .object({
+ label: z.string().min(1),
+ headgear: z.string().min(1),
+ primaryWeapon: z.string().min(1),
+ })
+ .strict(),
+ ),
+ clips: z
+ .array(
+ z
+ .object({
+ id: z.string().min(1),
+ label: z.string().min(1),
+ tijStates: z.array(NpcCharacterPackTijStateSchema).min(1),
+ status: NpcCharacterPackClipStatusSchema,
+ note: z.string().min(1),
+ })
+ .strict(),
+ )
+ .min(1),
+ weapons: z.record(z.string(), z.unknown()).default({}),
+ combinedGlbs: z
+ .record(
+ z.string().min(1),
+ z
+ .object({
+ uri: z.string().min(1),
+ bytes: z.number().int().nonnegative(),
+ hash: z.string().min(1).optional(),
+ animations: z.array(z.string()),
+ })
+ .strict(),
+ )
+ .default({}),
+ entries: z.array(NpcCharacterPackPackagedEntrySchema).min(1),
+ totals: z
+ .object({
+ entries: z.number().int().nonnegative(),
+ glbBytes: z.number().int().nonnegative(),
+ atlasPngBytes: z.number().int().nonnegative(),
+ rawImpostorBytes: z.number().int().nonnegative(),
+ warnings: z.number().int().nonnegative(),
+ })
+ .strict(),
+ })
+ .strict();
+
+export const NpcCharacterPackManifestSchema = z.union([
+ NpcCharacterPackSourceManifestSchema,
+ NpcCharacterPackPackagedManifestSchema,
+]);
+
+export type NpcCharacterPackManifest = z.infer<typeof NpcCharacterPackManifestSchema>;
+export type NpcCharacterPackIssue = z.infer<typeof NpcCharacterPackIssueSchema>;
+type NpcCharacterPackSourceManifest = z.infer<typeof NpcCharacterPackSourceManifestSchema>;
+type NpcCharacterPackPackagedManifest = z.infer<typeof NpcCharacterPackPackagedManifestSchema>;
+
+export interface NpcCharacterPackOutputMetrics {
+ faction: string;
+ clip: string;
+ path: string;
+ exists: boolean;
+ expectedBytes: number;
+ actualBytes?: number;
+ triangles?: number;
+ joints?: number;
+ animations?: number;
+ hasRightHandBone?: boolean;
+ hasLeftHandBone?: boolean;
+}
+
+export interface NpcCharacterPackFactionMetrics {
+ outputs: number;
+ clips: number;
+ maxBytes: number;
+ maxTris: number;
+ minJoints: number;
+}
+
+export interface NpcCharacterPackValidationReport {
+ ok: boolean;
+ manifest: NpcCharacterPackManifest | null;
+ blockers: NpcCharacterPackIssue[];
+ warnings: NpcCharacterPackIssue[];
+ metrics: {
+ factions: Record<string, NpcCharacterPackFactionMetrics>;
+ outputs: NpcCharacterPackOutputMetrics[];
+ };
+}
+
+export interface ValidateNpcCharacterPackOptions {
+ rootDir?: string;
+ checkFiles?: boolean;
+ inspectGlbs?: boolean;
+ productionClipIds?: string[];
+}
+
+const DEFAULT_PRODUCTION_CLIP_IDS = [
+ 'idle',
+ 'patrol_walk',
+ 'traverse_run',
+ 'walk_fight_forward',
+ 'death_fall_back',
+];
+
+export async function validateNpcCharacterPack(
+ raw: unknown,
+ opts: ValidateNpcCharacterPackOptions = {},
+): Promise<NpcCharacterPackValidationReport> {
+ const blockers: NpcCharacterPackIssue[] = [];
+ const warnings: NpcCharacterPackIssue[] = [];
+ const add = (issue: NpcCharacterPackIssue) => {
+ if (issue.severity === 'error') blockers.push(issue);
+ else warnings.push(issue);
+ };
+
+ const parsed = NpcCharacterPackManifestSchema.safeParse(raw);
+ if (!parsed.success) {
+ return {
+ ok: false,
+ manifest: null,
+ blockers: [
+ {
+ code: 'NPC_CHARACTER_PACK_SCHEMA_INVALID',
+ severity: 'error',
+ message: parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; '),
+ fixHint: 'Fix the character pack manifest shape before using it as a bake source.',
+ },
+ ],
+ warnings: [],
+ metrics: { factions: {}, outputs: [] },
+ };
+ }
+
+ const rawManifest = parsed.data;
+ const packagedManifest = isPackagedManifest(rawManifest) ? rawManifest : null;
+ const manifest = normalizeManifest(rawManifest);
+ const checkFiles = opts.checkFiles ?? false;
+ const inspectGlbs = opts.inspectGlbs ?? checkFiles;
+ const rootDir = opts.rootDir ?? process.cwd();
+ const productionClipIds = opts.productionClipIds ?? DEFAULT_PRODUCTION_CLIP_IDS;
+ const excludedClipIds = new Set(manifest.policy.excludedClips.map((clip) => clip.id));
+ const factionIds = new Set(Object.keys(manifest.factions));
+ const clipIds = new Set(manifest.clips.map((clip) => clip.id));
+ const outputKeys = new Set<string>();
+ const outputsByFaction = new Map<string, Set<string>>();
+ const metrics: NpcCharacterPackValidationReport['metrics'] = {
+ factions: Object.fromEntries(
+ Object.keys(manifest.factions).map((faction) => [
+ faction,
+ { outputs: 0, clips: 0, maxBytes: 0, maxTris: 0, minJoints: Number.POSITIVE_INFINITY },
+ ]),
+ ),
+ outputs: [],
+ };
+
+ if (packagedManifest) {
+ validatePackagedManifest(packagedManifest, rootDir, checkFiles, add);
+ }
+
+ if (!manifest.socketContract.rightHandBone.trim()) {
+ add({
+ code: 'NPC_CHARACTER_PACK_RIGHT_HAND_BONE_MISSING',
+ severity: 'error',
+ message: 'socketContract.rightHandBone is required.',
+ path: 'socketContract.rightHandBone',
+ fixHint: 'Set the right hand bone used for weapon attachment.',
+ });
+ }
+
+ if (!manifest.socketContract.leftHandBone.trim()) {
+ add({
+ code: 'NPC_CHARACTER_PACK_LEFT_HAND_BONE_MISSING',
+ severity: 'error',
+ message: 'socketContract.leftHandBone is required.',
+ path: 'socketContract.leftHandBone',
+ fixHint: 'Set the left hand bone used for weapon support.',
+ });
+ }
+
+ for (const clip of manifest.clips) {
+ if (excludedClipIds.has(clip.id)) {
+ add({
+ code: 'NPC_CHARACTER_PACK_EXCLUDED_CLIP_DECLARED',
+ severity: 'warning',
+ message: `Excluded clip ${clip.id} is still declared in clips.`,
+ path: `clips.${clip.id}`,
+ fixHint: 'Keep rejected actions out of the production clip list.',
+ });
+ }
+ }
+
+ for (const output of manifest.outputs) {
+ const outputKey = `${output.faction}/${output.clip}`;
+ const metric: NpcCharacterPackOutputMetrics = {
+ faction: output.faction,
+ clip: output.clip,
+ path: output.path,
+ exists: false,
+ expectedBytes: output.bytes,
+ };
+ metrics.outputs.push(metric);
+
+ if (outputKeys.has(outputKey)) {
+ add({
+ code: 'NPC_CHARACTER_PACK_DUPLICATE_OUTPUT',
+ severity: 'error',
+ message: `Duplicate output for ${outputKey}.`,
+ path: `outputs.${outputKey}`,
+ fixHint: 'Keep one GLB per faction and clip id.',
+ });
+ }
+ outputKeys.add(outputKey);
+
+ if (!factionIds.has(output.faction)) {
+ add({
+ code: 'NPC_CHARACTER_PACK_UNKNOWN_FACTION',
+ severity: 'error',
+ message: `Output references unknown faction ${output.faction}.`,
+ path: `outputs.${outputKey}.faction`,
+ fixHint: 'Add the faction to the manifest or remove the output.',
+ });
+ }
+
+ if (!clipIds.has(output.clip)) {
+ add({
+ code: 'NPC_CHARACTER_PACK_UNKNOWN_CLIP',
+ severity: 'error',
+ message: `Output references unknown clip ${output.clip}.`,
+ path: `outputs.${outputKey}.clip`,
+ fixHint: 'Add the clip metadata to the manifest or remove the output.',
+ });
+ }
+
+ if (excludedClipIds.has(output.clip)) {
+ add({
+ code: 'NPC_CHARACTER_PACK_EXCLUDED_CLIP_OUTPUT',
+ severity: 'error',
+ message: `Excluded clip ${output.clip} has an output for ${output.faction}.`,
+ path: `outputs.${outputKey}`,
+ fixHint: 'Do not bake or validate rejected production clips.',
+ });
+ }
+
+ const faction = manifest.factions[output.faction];
+ if (faction && output.primaryWeapon !== faction.primaryWeapon) {
+ add({
+ code: 'NPC_CHARACTER_PACK_WEAPON_MISMATCH',
+ severity: 'warning',
+ message: `${outputKey} uses ${output.primaryWeapon}, but faction default is ${faction.primaryWeapon}.`,
+ path: `outputs.${outputKey}.primaryWeapon`,
+ fixHint: 'Use the faction primary weapon unless this output is an intentional variant.',
+ });
+ }
+
+ const factionClips = outputsByFaction.get(output.faction) ?? new Set<string>();
+ factionClips.add(output.clip);
+ outputsByFaction.set(output.faction, factionClips);
+
+ if (metrics.factions[output.faction]) {
+ const factionMetric = metrics.factions[output.faction]!;
+ factionMetric.outputs += 1;
+ factionMetric.clips = factionClips.size;
+ factionMetric.maxBytes = Math.max(factionMetric.maxBytes, output.bytes);
+ }
+
+ if (checkFiles || inspectGlbs) {
+ await inspectOutputGlb(output, metric, rootDir, inspectGlbs, manifest, add);
+ if (metrics.factions[output.faction]) {
+ const factionMetric = metrics.factions[output.faction]!;
+ factionMetric.maxTris = Math.max(factionMetric.maxTris, metric.triangles ?? 0);
+ factionMetric.minJoints = Math.min(factionMetric.minJoints, metric.joints ?? factionMetric.minJoints);
+ }
+ }
+ }
+
+ for (const factionId of factionIds) {
+ const factionClips = outputsByFaction.get(factionId) ?? new Set<string>();
+ if (factionClips.size === 0) {
+ add({
+ code: 'NPC_CHARACTER_PACK_FACTION_NO_OUTPUTS',
+ severity: 'error',
+ message: `Faction ${factionId} has no GLB outputs.`,
+ path: `factions.${factionId}`,
+ fixHint: 'Generate or remove the faction before baking animated impostors.',
+ });
+ }
+
+ for (const clipId of productionClipIds) {
+ if (!factionClips.has(clipId)) {
+ add({
+ code: 'NPC_CHARACTER_PACK_PRODUCTION_CLIP_MISSING',
+ severity: 'error',
+ message: `Faction ${factionId} is missing production clip ${clipId}.`,
+ path: `outputs.${factionId}.${clipId}`,
+ fixHint: 'Build the same approved production clip set for every faction.',
+ });
+ }
+ }
+ }
+
+ for (const factionMetric of Object.values(metrics.factions)) {
+ if (factionMetric.minJoints === Number.POSITIVE_INFINITY) factionMetric.minJoints = 0;
+ }
+
+ return {
+ ok: blockers.length === 0,
+ manifest,
+ blockers,
+ warnings,
+ metrics,
+ };
+}
+
+function isPackagedManifest(
+ manifest: NpcCharacterPackManifest,
+): manifest is NpcCharacterPackPackagedManifest {
+ return 'entries' in manifest;
+}
+
+function normalizeManifest(manifest: NpcCharacterPackManifest): NpcCharacterPackSourceManifest {
+ if (!isPackagedManifest(manifest)) return manifest;
+
+ return {
+ id: manifest.id,
+ createdFrom: {
+ sourceManifest: manifest.sourceManifest,
+ schemaVersion: manifest.schemaVersion,
+ generatedAt: manifest.generatedAt,
+ },
+ policy: {
+ promoteToWarAssets: manifest.promoteToWarAssets,
+ recoil: 'Runtime procedural.',
+ excludedClips: manifest.clips
+ .filter((clip) => clip.status === 'rejected')
+ .map((clip) => ({ id: clip.id, reason: clip.note })),
+ },
+ socketContract: manifest.socketContract,
+ factions: manifest.factions,
+ clips: manifest.clips,
+ outputs: manifest.entries.map((entry) => ({
+ faction: entry.faction,
+ clip: entry.clip,
+ label: entry.clipLabel,
+ path: entry.glb.uri,
+ bytes: entry.glb.bytes,
+ tijStates: entry.tijStates,
+ status: entry.status,
+ primaryWeapon: entry.primaryWeapon,
+ })),
+ };
+}
+
+function validatePackagedManifest(
+ manifest: NpcCharacterPackPackagedManifest,
+ rootDir: string,
+ checkFiles: boolean,
+ add: (issue: NpcCharacterPackIssue) => void,
+): void {
+ if (manifest.promoteToWarAssets) {
+ add({
+ code: 'NPC_CHARACTER_PACK_REVIEW_ONLY_VIOLATION',
+ severity: 'error',
+ message: 'Packaged NPC manifests must remain review-only.',
+ path: 'promoteToWarAssets',
+ fixHint: 'Set promoteToWarAssets=false and keep generated output under tmp/ until runtime import is approved.',
+ });
+ }
+
+ if (manifest.totals.entries !== manifest.entries.length) {
+ add({
+ code: 'NPC_CHARACTER_PACK_TOTALS_DRIFT',
+ severity: 'error',
+ message: `totals.entries is ${manifest.totals.entries}, but entries contains ${manifest.entries.length}.`,
+ path: 'totals.entries',
+ fixHint: 'Regenerate the package manifest after rebuilding entries.',
+ });
+ }
+
+ for (const [faction, combined] of Object.entries(manifest.combinedGlbs)) {
+ if (!manifest.factions[faction]) {
+ add({
+ code: 'NPC_CHARACTER_PACK_UNKNOWN_COMBINED_FACTION',
+ severity: 'error',
+ message: `combinedGlbs contains unknown faction ${faction}.`,
+ path: `combinedGlbs.${faction}`,
+ fixHint: 'Remove the combined GLB or add the faction metadata.',
+ });
+ }
+ if (checkFiles) {
+ requirePackagedFile(add, `combinedGlbs.${faction}.uri`, combined.uri, rootDir);
+ }
+ }
+
+ for (const entry of manifest.entries) {
+ const key = `${entry.faction}/${entry.clip}`;
+ if (!entry.impostor.sidecarValid) {
+ add({
+ code: 'NPC_CHARACTER_PACK_IMPOSTER_SIDECAR_INVALID',
+ severity: 'error',
+ message: `${key} animated imposter sidecar failed schema validation during packaging.`,
+ path: `entries.${key}.impostor.sidecar`,
+ fixHint: 'Fix the animated imposter sidecar before using this entry as a bake/runtime source.',
+ });
+ }
+ if (!entry.impostor.storage.fitsEnvelope) {
+ add({
+ code: 'NPC_CHARACTER_PACK_IMPOSTER_STORAGE_OVER_BUDGET',
+ severity: 'error',
+ message: `${key} animated imposter exceeds the configured storage envelope.`,
+ path: `entries.${key}.impostor.storage`,
+ fixHint: 'Reduce view grid, frame count, tile size, or texture format before runtime import.',
+ });
+ }
+
+ if (!checkFiles) continue;
+ requirePackagedFile(add, `entries.${key}.glb.uri`, entry.glb.uri, rootDir);
+ requirePackagedFile(add, `entries.${key}.impostor.sidecar`, entry.impostor.sidecar, rootDir);
+ requirePackagedFile(add, `entries.${key}.impostor.atlas`, entry.impostor.atlas, rootDir);
+ requirePackagedFile(add, `entries.${key}.impostor.frameStrip`, entry.impostor.frameStrip, rootDir);
+ }
+}
+
+function requirePackagedFile(
+ add: (issue: NpcCharacterPackIssue) => void,
+ path: string,
+ filePath: string,
+ rootDir: string,
+): void {
+ const absPath = isAbsolute(filePath) ? filePath : resolve(rootDir, filePath);
+ if (!existsSync(absPath)) {
+ add({
+ code: 'NPC_CHARACTER_PACK_FILE_MISSING',
+ severity: 'error',
+ message: `Packaged file is missing: ${filePath}.`,
+ path,
+ fixHint: 'Rebuild the package or fix the manifest path.',
+ });
+ }
+}
+
+async function inspectOutputGlb(
+ output: z.infer<typeof NpcCharacterPackOutputSchema>,
+ metric: NpcCharacterPackOutputMetrics,
+ rootDir: string,
+ inspectGlbs: boolean,
+ manifest: NpcCharacterPackManifest,
+ add: (issue: NpcCharacterPackIssue) => void,
+): Promise<void> {
+ const absPath = isAbsolute(output.path) ? output.path : resolve(rootDir, output.path);
+ if (!existsSync(absPath)) {
+ add({
+ code: 'NPC_CHARACTER_PACK_OUTPUT_MISSING',
+ severity: 'error',
+ message: `Output GLB is missing: ${output.path}.`,
+ path: `outputs.${output.faction}.${output.clip}.path`,
+ fixHint: 'Rebuild the pack or fix the manifest path before baking.',
+ });
+ return;
+ }
+
+ metric.exists = true;
+ metric.actualBytes = statSync(absPath).size;
+ if (metric.actualBytes !== output.bytes) {
+ add({
+ code: 'NPC_CHARACTER_PACK_OUTPUT_BYTES_DRIFT',
+ severity: 'warning',
+ message: `${output.path} is ${metric.actualBytes} bytes, manifest expected ${output.bytes}.`,
+ path: `outputs.${output.faction}.${output.clip}.bytes`,
+ fixHint: 'Refresh the manifest after rebuilding GLBs.',
+ });
+ }
+
+ if (!inspectGlbs) return;
+
+ try {
+ const doc = await new NodeIO().read(absPath);
+ const root = doc.getRoot();
+ metric.triangles = countTriangles(root.listMeshes());
+ metric.animations = root.listAnimations().length;
+ const jointNames = new Set(root.listSkins().flatMap((skin) => skin.listJoints().map((joint) => joint.getName())));
+ const nodeNames = new Set(root.listNodes().map((node) => node.getName()));
+ metric.joints = jointNames.size;
+ metric.hasRightHandBone = jointNames.has(manifest.socketContract.rightHandBone) || nodeNames.has(manifest.socketContract.rightHandBone);
+ metric.hasLeftHandBone = jointNames.has(manifest.socketContract.leftHandBone) || nodeNames.has(manifest.socketContract.leftHandBone);
+
+ if (metric.triangles <= 0) {
+ add({
+ code: 'NPC_CHARACTER_PACK_OUTPUT_NO_TRIS',
+ severity: 'error',
+ message: `${output.path} has no renderable triangles.`,
+ path: `outputs.${output.faction}.${output.clip}.path`,
+ fixHint: 'Use a mesh-backed GLB output.',
+ });
+ }
+ if (metric.joints <= 0) {
+ add({
+ code: 'NPC_CHARACTER_PACK_OUTPUT_NO_SKIN',
+ severity: 'error',
+ message: `${output.path} has no skin joints.`,
+ path: `outputs.${output.faction}.${output.clip}.path`,
+ fixHint: 'Use a skinned character GLB for animated impostor baking.',
+ });
+ }
+ if (output.status !== 'reference' && (metric.animations ?? 0) <= 0) {
+ add({
+ code: 'NPC_CHARACTER_PACK_OUTPUT_NO_ANIMATION',
+ severity: 'error',
+ message: `${output.path} has no animation clips.`,
+ path: `outputs.${output.faction}.${output.clip}.path`,
+ fixHint: 'Select an animated clip GLB or mark this output as reference-only.',
+ });
+ }
+ if (!metric.hasRightHandBone || !metric.hasLeftHandBone) {
+ add({
+ code: 'NPC_CHARACTER_PACK_HAND_BONES_NOT_FOUND',
+ severity: 'error',
+ message: `${output.path} does not expose both configured hand bones.`,
+ path: `outputs.${output.faction}.${output.clip}.path`,
+ fixHint: 'Set socketContract hand bone names to the exported skeleton names.',
+ });
+ }
+ } catch (err) {
+ add({
+ code: 'NPC_CHARACTER_PACK_OUTPUT_INSPECT_FAILED',
+ severity: 'error',
+ message: `${output.path} could not be inspected: ${(err as Error).message}`,
+ path: `outputs.${output.faction}.${output.clip}.path`,
+ fixHint: 'Verify the path points to a valid GLB file.',
+ });
+ }
+}
+
+function countTriangles(meshes: Mesh[]): number {
+ let tris = 0;
+ for (const mesh of meshes) {
+ for (const primitive of mesh.listPrimitives()) {
+ tris += Math.floor((primitive.getIndices()?.getCount() ?? primitive.getAttribute('POSITION')?.getCount() ?? 0) / 3);
+ }
+ }
+ return tris;
+}
diff --git a/imposter/schema.ts b/imposter/schema.ts
index d423d161..6f3aa056 100644
--- a/imposter/schema.ts
+++ b/imposter/schema.ts
@@ -20,6 +20,9 @@ export type ImposterAxis = 'y' | 'hemi-y';
export type ImposterLayout = 'latlon' | 'octahedral';
export type ImposterAuxLayer = 'albedo' | 'normal' | 'depth';
export type ImposterBgColor = 'magenta' | 'transparent';
+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),
@@ -79,6 +82,23 @@ export const ImposterMetaSchema = z.object({
/** Background color used for the bake. 'transparent' uses RGBA alpha. */
bgColor: z.enum(['magenta', 'transparent']),
+
+ /** Color layer contract. Legacy sidecars default to lit beauty output. */
+ colorLayer: z.enum(['baseColor', 'beauty']).default('beauty'),
+ /** Normal layer coordinate contract. Current baker emits capture/view-space normal RGB. */
+ normalSpace: z.literal('capture-view').default('capture-view'),
+ /** RGB bleed radius applied into transparent pixels before atlas packing. */
+ 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) => {
+ if (meta.colorLayer === 'baseColor' && !meta.auxLayers.includes('normal')) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['auxLayers'],
+ message: "baseColor production imposters must include a 'normal' aux layer",
+ });
+ }
});
export type ImposterMeta = z.infer<typeof ImposterMetaSchema>;
diff --git a/index.ts b/index.ts
index bc461600..258297c2 100644
--- a/index.ts
+++ b/index.ts
@@ -190,6 +190,9 @@ export type {
ImposterLayout,
ImposterAuxLayer,
ImposterBgColor,
+ ImposterColorLayer,
+ ImposterNormalSpace,
+ ImposterTextureColorSpace,
AnimatedClipTarget,
AnimatedImposterMeta,
AnimatedImposterPreBakeConfig,
@@ -205,6 +208,12 @@ export type {
AnimatedTileCamera,
BakeAnimatedImposterOptions,
BakeAnimatedImposterResult,
+ NpcCharacterPackFactionMetrics,
+ NpcCharacterPackIssue,
+ NpcCharacterPackManifest,
+ NpcCharacterPackOutputMetrics,
+ NpcCharacterPackValidationReport,
+ ValidateNpcCharacterPackOptions,
} from './imposter';
export {
ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,
@@ -225,6 +234,8 @@ export {
bakeAnimatedImposter,
enumerateOctahedralGrid,
openAnimatedImposterSession,
+ NpcCharacterPackManifestSchema,
+ validateNpcCharacterPack,
} from './imposter';
// =============================================================================