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
chore(core): copy kiln primitives + prompt + validation
Matt Kissingerfc618f5c3c27
diff --git a/primitives.ts b/primitives.tsnew file mode 100644index 00000000..4035683f--- /dev/null+++ b/primitives.ts@@ -0,0 +1,393 @@+/**+ * Kiln Primitives Library+ *+ * High-level helpers for 3D asset creation.+ * Claude generates code using these primitives to keep files small.+ *+ * Copied from packages/client/src/lib/kiln/primitives.ts as the canonical+ * source in @pixel-forge/core. The headless variant in scripts/export-glb.ts+ * was verified structurally identical; the two have been reconciled here.+ */++import * as THREE from 'three';++// =============================================================================+// Geometry Helpers+// =============================================================================++/**+ * Creates the root Object3D for an asset.+ */+export function createRoot(name: string): THREE.Object3D {+ const root = new THREE.Object3D();+ root.name = name;+ return root;+}++/**+ * Creates a pivot (empty Object3D) for skeletal animation.+ * Pivots are the joints that get animated; meshes are children.+ */+export function createPivot(+ name: string,+ position: [number, number, number] = [0, 0, 0],+ parent?: THREE.Object3D+): THREE.Object3D {+ const pivot = new THREE.Object3D();+ pivot.name = `Joint_${name}`;+ pivot.position.set(...position);+ if (parent) parent.add(pivot);+ return pivot;+}++/**+ * Creates a mesh with automatic pivot wrapping for animation.+ * The mesh is automatically added to `parent` if provided.+ *+ * Returns the added Object3D (mesh or pivot) for reference.+ * NOTE: Do NOT call .add() on the return value - it's already added!+ */+export function createPart(+ name: string,+ geometry: THREE.BufferGeometry,+ material: THREE.Material,+ options: {+ position?: [number, number, number];+ rotation?: [number, number, number];+ scale?: [number, number, number];+ pivot?: boolean; // Wrap in pivot for animation+ parent?: THREE.Object3D;+ } = {}+): THREE.Object3D {+ const mesh = new THREE.Mesh(geometry, material);+ mesh.name = `Mesh_${name}`;++ if (options.position) mesh.position.set(...options.position);+ if (options.rotation) mesh.rotation.set(+ THREE.MathUtils.degToRad(options.rotation[0]),+ THREE.MathUtils.degToRad(options.rotation[1]),+ THREE.MathUtils.degToRad(options.rotation[2]),+ );+ if (options.scale) mesh.scale.set(...options.scale);++ if (options.pivot) {+ const pivot = new THREE.Object3D();+ pivot.name = `Joint_${name}`;+ pivot.add(mesh);+ mesh.position.set(0, 0, 0); // Reset - pivot controls position+ if (options.position) pivot.position.set(...options.position);+ if (options.parent) options.parent.add(pivot);+ return pivot; // Return the pivot (the animatable node)+ }++ if (options.parent) options.parent.add(mesh);+ return mesh; // Return the mesh+}++// =============================================================================+// Common Shapes (game-ready low-poly)+// =============================================================================++export function capsuleGeo(+ radius: number,+ height: number,+ segments = 6+): THREE.CapsuleGeometry {+ return new THREE.CapsuleGeometry(radius, height, 2, segments);+}++export function cylinderGeo(+ radiusTop: number,+ radiusBottom: number,+ height: number,+ segments = 8+): THREE.CylinderGeometry {+ return new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments);+}++export function boxGeo(+ width: number,+ height: number,+ depth: number+): THREE.BoxGeometry {+ return new THREE.BoxGeometry(width, height, depth);+}++export function sphereGeo(+ radius: number,+ widthSegments = 8,+ heightSegments = 6+): THREE.SphereGeometry {+ return new THREE.SphereGeometry(radius, widthSegments, heightSegments);+}++export function coneGeo(+ radius: number,+ height: number,+ segments = 8+): THREE.ConeGeometry {+ return new THREE.ConeGeometry(radius, height, segments);+}++export function torusGeo(+ radius: number,+ tube: number,+ radialSegments = 8,+ tubularSegments = 12+): THREE.TorusGeometry {+ return new THREE.TorusGeometry(radius, tube, radialSegments, tubularSegments);+}++export function planeGeo(+ width: number,+ height: number,+ widthSegments = 1,+ heightSegments = 1+): THREE.PlaneGeometry {+ return new THREE.PlaneGeometry(width, height, widthSegments, heightSegments);+}++// =============================================================================+// Materials+// =============================================================================++export function gameMaterial(+ color: number | string,+ options: {+ metalness?: number;+ roughness?: number;+ emissive?: number | string;+ emissiveIntensity?: number;+ flatShading?: boolean;+ } = {}+): THREE.MeshStandardMaterial {+ return new THREE.MeshStandardMaterial({+ color,+ metalness: options.metalness ?? 0,+ roughness: options.roughness ?? 0.8,+ emissive: options.emissive ?? 0x000000,+ emissiveIntensity: options.emissiveIntensity ?? 1,+ flatShading: options.flatShading ?? true,+ });+}++export function basicMaterial(+ color: number | string,+ options: { transparent?: boolean; opacity?: number } = {}+): THREE.MeshBasicMaterial {+ return new THREE.MeshBasicMaterial({+ color,+ transparent: options.transparent ?? false,+ opacity: options.opacity ?? 1,+ });+}++export function glassMaterial(+ color: number | string,+ options: { opacity?: number; roughness?: number; metalness?: number } = {}+): THREE.MeshStandardMaterial {+ return new THREE.MeshStandardMaterial({+ color,+ transparent: true,+ opacity: options.opacity ?? 0.35,+ roughness: options.roughness ?? 0.1,+ metalness: options.metalness ?? 0,+ side: THREE.DoubleSide,+ });+}++export function lambertMaterial(+ color: number | string,+ options: { flatShading?: boolean; emissive?: number | string } = {}+): THREE.MeshLambertMaterial {+ return new THREE.MeshLambertMaterial({+ color,+ flatShading: options.flatShading ?? true,+ emissive: options.emissive ?? 0x000000,+ });+}++// =============================================================================+// Animation Helpers+// =============================================================================++export function rotationTrack(+ jointName: string,+ keyframes: Array<{ time: number; rotation: [number, number, number] }>+): THREE.QuaternionKeyframeTrack {+ const times: number[] = [];+ const values: number[] = [];+ const euler = new THREE.Euler();+ const quat = new THREE.Quaternion();++ for (const kf of keyframes) {+ times.push(kf.time);+ euler.set(+ THREE.MathUtils.degToRad(kf.rotation[0]),+ THREE.MathUtils.degToRad(kf.rotation[1]),+ THREE.MathUtils.degToRad(kf.rotation[2])+ );+ quat.setFromEuler(euler);+ values.push(quat.x, quat.y, quat.z, quat.w);+ }++ return new THREE.QuaternionKeyframeTrack(+ `${jointName}.quaternion`,+ times,+ values+ );+}++export function positionTrack(+ jointName: string,+ keyframes: Array<{ time: number; position: [number, number, number] }>+): THREE.VectorKeyframeTrack {+ const times: number[] = [];+ const values: number[] = [];++ for (const kf of keyframes) {+ times.push(kf.time);+ values.push(...kf.position);+ }++ return new THREE.VectorKeyframeTrack(+ `${jointName}.position`,+ times,+ values+ );+}++export function scaleTrack(+ jointName: string,+ keyframes: Array<{ time: number; scale: [number, number, number] }>+): THREE.VectorKeyframeTrack {+ const times: number[] = [];+ const values: number[] = [];++ for (const kf of keyframes) {+ times.push(kf.time);+ values.push(...kf.scale);+ }++ return new THREE.VectorKeyframeTrack(`${jointName}.scale`, times, values);+}++export function createClip(+ name: string,+ duration: number,+ tracks: THREE.KeyframeTrack[]+): THREE.AnimationClip {+ return new THREE.AnimationClip(name, duration, tracks);+}++// =============================================================================+// Common Animation Patterns+// =============================================================================++export function idleBreathing(+ bodyJoint: string,+ duration = 2,+ amount = 0.02+): THREE.AnimationClip {+ const y = 0;+ return createClip('Idle', duration, [+ positionTrack(bodyJoint, [+ { time: 0, position: [0, y, 0] },+ { time: duration / 2, position: [0, y + amount, 0] },+ { time: duration, position: [0, y, 0] },+ ]),+ ]);+}++export function bobbingAnimation(+ rootName: string,+ duration = 2,+ height = 0.1+): THREE.AnimationClip {+ return createClip('Bob', duration, [+ positionTrack(rootName, [+ { time: 0, position: [0, 0, 0] },+ { time: duration / 2, position: [0, height, 0] },+ { time: duration, position: [0, 0, 0] },+ ]),+ ]);+}++export function spinAnimation(+ jointName: string,+ duration = 2,+ axis: 'x' | 'y' | 'z' = 'y'+): THREE.AnimationClip {+ const rotation: [number, number, number] = [0, 0, 0];+ const idx = axis === 'x' ? 0 : axis === 'y' ? 1 : 2;+ const rotations: Array<{ time: number; rotation: [number, number, number] }> =+ [];++ for (let i = 0; i <= 4; i++) {+ const r: [number, number, number] = [...rotation];+ r[idx] = (i * 90) % 360;+ rotations.push({ time: (i * duration) / 4, rotation: r });+ }++ return createClip('Spin', duration, [rotationTrack(jointName, rotations)]);+}++// =============================================================================+// Utilities+// =============================================================================++export function countTriangles(root: THREE.Object3D): number {+ let count = 0;+ root.traverse((child) => {+ if (child instanceof THREE.Mesh) {+ const geometry = child.geometry;+ if (geometry.index) {+ count += geometry.index.count / 3;+ } else {+ const position = geometry.getAttribute('position');+ if (position) count += position.count / 3;+ }+ }+ });+ return Math.floor(count);+}++export function countMaterials(root: THREE.Object3D): number {+ const materials = new Set<THREE.Material>();+ root.traverse((child) => {+ if (child instanceof THREE.Mesh) {+ if (Array.isArray(child.material)) {+ child.material.forEach((m) => materials.add(m));+ } else {+ materials.add(child.material);+ }+ }+ });+ return materials.size;+}++export function getJointNames(root: THREE.Object3D): string[] {+ const joints: string[] = [];+ root.traverse((child) => {+ if (child.name.startsWith('Joint_')) {+ joints.push(child.name);+ }+ });+ return joints;+}++/**+ * The full sandbox globals used when executing Kiln code. Kept in one place+ * so render.ts and any future evaluator share the same surface area as what+ * the LLM expects.+ */+export function buildSandboxGlobals(): Record<string, unknown> {+ return {+ createRoot, createPivot, createPart,+ capsuleGeo, cylinderGeo, boxGeo, sphereGeo, coneGeo, torusGeo, planeGeo,+ gameMaterial, basicMaterial, glassMaterial, lambertMaterial,+ rotationTrack, positionTrack, scaleTrack, createClip,+ spinAnimation, bobbingAnimation, idleBreathing,+ Math, console,+ };+}diff --git a/prompt.ts b/prompt.tsnew file mode 100644index 00000000..0d73c873--- /dev/null+++ b/prompt.ts@@ -0,0 +1,266 @@+/**+ * Kiln System Prompts & User Prompt Builders+ *+ * Copied from packages/shared/kiln-prompts.ts for the core spike so the+ * headless pipeline has no run-time dependency on the shared package's+ * prompt content. Duplication is intentional - W2 will dedupe once the+ * editor migration lands.+ *+ * Local types mirror @pixel-forge/shared api-types so we stay additive.+ */++export type RenderMode = 'glb' | 'tsl' | 'both';+export type AssetCategory = 'character' | 'prop' | 'vfx' | 'environment';+export type AssetStyle = 'low-poly' | 'stylized' | 'voxel' | 'detailed' | 'realistic';++// =============================================================================+// Style Templates+// =============================================================================++export const STYLE_TEMPLATES: Record<AssetStyle, string> = {+ 'low-poly': `## Style: Low-Poly+Generate assets with a low-poly aesthetic:+- Use 6-8 segments for cylinders, spheres, cones+- Flat shading enabled (flatShading: true)+- Minimal detail, geometric forms+- Bold, solid colors+- No small decorative elements+- Chunky proportions`,++ 'stylized': `## Style: Stylized Cartoon+Generate assets with a stylized cartoon aesthetic:+- Use 12-16 segments for smoother curves+- Exaggerated proportions (big heads, small bodies for characters)+- Bright, saturated colors+- Smooth shading for organic forms+- Can include small decorative details+- Playful, whimsical shapes`,++ 'voxel': `## Style: Voxel+Generate assets with a voxel/Minecraft-like aesthetic:+- Use ONLY box geometry (boxGeo)+- No spheres, cylinders, or curved shapes+- Build forms from stacked/arranged cubes+- Grid-aligned positions (use 0.25 or 0.5 unit increments)+- Flat shading always+- Blocky proportions`,++ 'detailed': `## Style: Detailed+Generate assets with more geometric detail:+- Use 24-32 segments for smooth surfaces+- Include small decorative elements (buttons, rivets, trim)+- Layered construction with multiple parts+- Subtle color variations+- Can use metallic/roughness for PBR looks+- Realistic proportions`,++ 'realistic': `## Style: Realistic+Generate assets with realistic proportions and detail:+- Use 32-64 segments for very smooth surfaces+- Accurate real-world proportions+- Multiple materials with PBR properties (metalness, roughness)+- Include fine details (seams, edges, bevels)+- Subtle color gradients+- Higher triangle budgets allowed`+};++// =============================================================================+// System Prompt (GLB mode - spike only cares about this)+// =============================================================================++export const KILN_SYSTEM_PROMPT = `You are an expert procedural 3D asset generator. Create game-ready models with character and style.++CRITICAL: NO import/export statements. Code runs in a sandbox with primitives as globals.++<file-format>+const meta = { name: "AssetName", category: "prop" };++function build() {+ const root = createRoot("AssetName");+ // Build scene graph with pivots and meshes+ return root;+}++function animate(root) {+ // Return animation clips (optional)+ return [clip1, clip2];+}+</file-format>++<api>+// Scene (no imports needed - globals)+createRoot(name: string): Object3D+createPivot(name: string, position: [x,y,z], parent: Object3D): Object3D+createPart(name, geo, mat, opts): void // AUTO-ADDS to parent! Do NOT call .add() on it++// createPart usage - it automatically adds to parent:+createPart("Name", geometry, material, { position: [x,y,z], parent: parentObj });+// WRONG: parent.add(createPart(...)) // DO NOT DO THIS+// RIGHT: createPart("Name", geo, mat, { parent: parentObj }); // auto-adds++// Geometry+boxGeo(width, height, depth)+sphereGeo(radius, widthSegs=8, heightSegs=6)+cylinderGeo(radiusTop, radiusBot, height, segments=8)+coneGeo(radius, height, segments=8)+capsuleGeo(radius, height, segments=6)+torusGeo(radius, tube, radialSegs=8, tubularSegs=12)+planeGeo(width, height, widthSegs=1, heightSegs=1)++// Materials+gameMaterial(0xcolor, {metalness?, roughness?, emissive?, flatShading?})+lambertMaterial(0xcolor, {flatShading?, emissive?})+glassMaterial(0xcolor, {opacity?, roughness?, metalness?}) // transparent, DoubleSide - cockpits, windows++// Animation - IMPORTANT: keyframes use "rotation" or "position" keys, NOT "value"+rotationTrack(jointName: string, keyframes: [{time, rotation: [x,y,z]}]) // rotation in DEGREES+positionTrack(jointName: string, keyframes: [{time, position: [x,y,z]}])+createClip(name: string, duration: number, tracks: Track[])+spinAnimation(jointName, duration, axis: 'x'|'y'|'z') // returns a clip+bobbingAnimation(rootName, duration, height) // returns a clip++// animate() must return an ARRAY of clips+function animate(root) { return [clip1, clip2]; }+</api>++<architecture>+Use Pivot+Mesh pattern for animated parts:+- Joint_* = pivot node (animate this) - created by createPivot or createPart with pivot:true+- Mesh_* = geometry node (child of pivot)++For animations, track names must use "Joint_" prefix:+- createPivot("Body", ...) creates "Joint_Body" - animate with rotationTrack("Joint_Body", ...)+- createPart("Wheel", ..., {pivot: true}) creates "Joint_Wheel" - animate it+</architecture>++<quality>+- Give your asset personality and character+- Use appropriate level of detail for the category+- Colors should be cohesive and intentional+- Animations should feel natural and loop seamlessly+- Name parts descriptively (Body, LeftArm, Wheel)+</quality>++<rules>+- Colors as hex: 0xff0000+- Y-up, ground at Y=0+- Animate pivots only (Joint_* names)+- Loops: end keyframe = start keyframe+- Track names: "Joint_Name" format (must exist in scene)+- animate() MUST return an ARRAY: return [clip]+- createClip needs 3 args: createClip(name, duration, tracks)+- NO "export" statements - just define meta, build, animate+- Output ONLY valid JavaScript code (no TypeScript types)+- NEVER call .add() on createPart result - it auto-adds to parent+- Z-FIGHTING PREVENTION: No two mesh faces may be coplanar or near-coplanar. All decorative geometry (decals, markings, edge strips, reinforcements, trim) must be fully outside the parent mesh - never intersecting or flush. Offset at least 0.01 from the nearest surface. If a box is 0.6 wide (edges at x=+-0.3), place edge trim at x=+-0.31, NOT x=+-0.29. Minimum 0.01 thickness for flat parts.+</rules>++<critical-animation-format>+WRONG: { time: 0, value: [0,0,0] }+RIGHT: { time: 0, rotation: [0,0,0] } for rotationTrack (degrees)+RIGHT: { time: 0, position: [0,0,0] } for positionTrack+</critical-animation-format>++<example>+const meta = { name: "Chest", category: "prop" };++function build() {+ const root = createRoot("Chest");++ // Base - no animation needed, no pivot+ createPart("Base", boxGeo(1, 0.4, 0.8), gameMaterial(0x8B4513), {+ position: [0, 0.2, 0],+ parent: root+ });++ // Lid - needs animation, so use createPivot + createPart+ const lidPivot = createPivot("Lid", [0, 0.4, -0.35], root);+ createPart("LidMesh", boxGeo(1, 0.15, 0.8), gameMaterial(0x8B4513), {+ position: [0, 0.075, 0.35],+ parent: lidPivot+ });++ return root;+}++function animate(root) {+ // Animate Joint_Lid (created by createPivot("Lid", ...))+ return [createClip("Open", 2, [+ rotationTrack("Joint_Lid", [+ {time: 0, rotation: [0, 0, 0]},+ {time: 1, rotation: [-60, 0, 0]}, // degrees!+ {time: 2, rotation: [0, 0, 0]}+ ])+ ])];+}+</example>`;++// =============================================================================+// Prompt Helpers+// =============================================================================++export interface AssetBudget {+ maxTriangles?: number;+ maxMaterials?: number;+}++export interface KilnGenerateRequest {+ prompt: string;+ mode: RenderMode;+ category: AssetCategory;+ style?: AssetStyle;+ budget?: AssetBudget;+ includeAnimation?: boolean;+ existingCode?: string;+ referenceImageUrl?: string;+}++export function getSystemPrompt(mode: RenderMode): string {+ // Spike only supports GLB mode; tsl/both fall back to GLB so future callers+ // don't throw. W2 will pull the real TSL / Both prompts.+ void mode;+ return KILN_SYSTEM_PROMPT;+}++export function buildUserPrompt(request: KilnGenerateRequest): string {+ const parts: string[] = [];++ if (request.style && STYLE_TEMPLATES[request.style]) {+ parts.push(STYLE_TEMPLATES[request.style]);+ parts.push('');+ }++ if (request.budget) {+ parts.push('## Constraints');+ if (request.budget.maxTriangles) {+ parts.push(`- Triangle budget: ${request.budget.maxTriangles}`);+ }+ if (request.budget.maxMaterials) {+ parts.push(`- Material limit: ${request.budget.maxMaterials}`);+ }+ parts.push('');+ }++ if (request.existingCode) {+ parts.push(`## Current Code\n\n\`\`\`typescript\n${request.existingCode}\n\`\`\`\n\n## Edit Request\n\n${request.prompt}`);+ } else {+ parts.push(`## Task\n\nCreate a ${request.category}: ${request.prompt}`);+ }++ if (request.includeAnimation !== false) {+ parts.push(`+## Animation Requirements+Include an animate() function that returns an array of AnimationClips.+Use createPivot() for parts that need animation, then animate them with rotationTrack/positionTrack.+Track names MUST match pivot names exactly (e.g., createPivot("Lid",...) -> rotationTrack("Joint_Lid",...)).+Make animations loop seamlessly (end keyframe = start keyframe values).`);+ } else {+ parts.push(`+## No Animation+Do NOT include an animate() function. Only create the static geometry in build().`);+ }++ parts.push('\n\nGenerate the complete code.');++ return parts.join('\n');+}diff --git a/validation.ts b/validation.tsnew file mode 100644index 00000000..dc417f53--- /dev/null+++ b/validation.ts@@ -0,0 +1,60 @@+/**+ * Kiln Code Validation+ *+ * Validates generated Kiln code before returning it to the caller.+ * Catches common Claude output issues (exports, wrong keyframe format,+ * missing meta/build).+ *+ * Copied from packages/shared/kiln-validation.ts for the core spike.+ */++export interface ValidationResult {+ valid: boolean;+ errors: string[];+}++export function validate(code: string): ValidationResult {+ const errors: string[] = [];++ if (!code || typeof code !== 'string' || code.trim().length === 0) {+ return { valid: false, errors: ['Empty or missing code'] };+ }++ // Must have meta object+ if (!/const\s+meta\s*=/.test(code)) {+ errors.push('Missing `const meta = { ... }` declaration');+ }++ // Must have build function+ if (!/function\s+build\s*\(/.test(code)) {+ errors.push('Missing `function build()` declaration');+ }++ // No import statements (sandbox globals)+ if (/^\s*import\s+/m.test(code)) {+ errors.push('Contains import statements - code must use sandbox globals only');+ }++ // No export statements+ if (/^\s*export\s+/m.test(code)) {+ errors.push('Contains export statements - just define meta, build, animate');+ }++ // Detect wrong keyframe format: { time: N, value: [...] }+ if (/\{\s*time:\s*[^,]+,\s*value:\s*\[/.test(code)) {+ errors.push('Uses `value:` in keyframes - must use `rotation:` or `position:` instead');+ }++ // Syntax check via Function constructor+ try {+ new Function(code);+ } catch (e) {+ errors.push(`Syntax error: ${e instanceof Error ? e.message : String(e)}`);+ }++ return { valid: errors.length === 0, errors };+}++// Compatibility alias - matches the shared package's exported name so call+// sites can swap over cleanly during the W2 dedupe.+export const validateKilnCode = validate;