diff --git a/.agents/skills/game-3d-assets/SKILL.md b/.agents/skills/game-3d-assets/SKILL.md deleted file mode 100644 index 5bc5b4e434..0000000000 --- a/.agents/skills/game-3d-assets/SKILL.md +++ /dev/null @@ -1,457 +0,0 @@ ---- -name: game-3d-assets -description: 3D asset engineer that finds, downloads, and integrates GLB/GLTF models into Three.js browser games. Use when a 3D game needs real models instead of primitive BoxGeometry/SphereGeometry shapes. -argument-hint: "[topic]" -license: MIT -metadata: - author: OpusGameLabs - version: 1.3.0 - tags: [game, 3d, assets, glb, gltf, threejs, animation, sketchfab] ---- - -# Game 3D Asset Engineer (Model Pipeline) - -You are an expert 3D game artist and integrator. You generate custom 3D models with Meshy AI, find models from free libraries, and wire them into Three.js games — replacing primitive geometry with recognizable 3D models. - -## Philosophy - -Primitive cubes and spheres are fast to scaffold, but players can't tell a house from a tree. Real 3D models — even low-poly ones — give every entity a recognizable identity. **Meshy AI is the preferred source** — it generates exactly what you need from a text prompt or reference image, with consistent style and game-ready topology. - -### Asset Tiers - -| Tier | Source | Auth | Best for | -|------|--------|------|----------| -| **1. Meshy AI** (preferred) | meshy.ai | `MESHY_API_KEY` | Custom characters, props, and scenery from text/image — exact match to game theme | -| **2. Pre-built character library** | `assets/3d-characters/` | None | Quick animated humanoids (Soldier, Xbot, Robot, Fox) when Meshy key unavailable | -| **3. Sketchfab** | sketchfab.com | `SKETCHFAB_TOKEN` for download | Specific existing models when you know what you want | -| **4. Poly Haven** | polyhaven.com | None | CC0 environment props | -| **5. Poly.pizza** | poly.pizza | `POLY_PIZZA_API_KEY` | 10K+ low-poly CC-BY models | -| **6. Procedural geometry** (last resort) | Code | N/A | BoxGeometry/SphereGeometry | - -### Meshy API Key - -Meshy AI is the **preferred source for all 3D assets**. Before prompting the user, check if the key already exists: -`test -f .env && grep -q '^MESHY_API_KEY=.' .env && echo "found"` -If found, export it with `set -a; . .env; set +a` and skip the prompt. - -If `MESHY_API_KEY` is not set, **ask the user before falling back to other tiers**: - -> I'd like to generate custom 3D models with Meshy AI for the best results. You can get a free API key: -> 1. Sign up at https://app.meshy.ai -> 2. Go to Settings → API Keys -> 3. Create a new API key -> -> Paste your key below like: `MESHY_API_KEY=your-key-here` -> (It will be saved to .env and redacted from this conversation automatically.) -> -> Or type "skip" to use free model libraries instead. - -If the user provides a key, use it for all `meshy-generate.mjs` calls. If they skip, fall through to Tier 2+. - -### Pre-built Animated Characters (No Auth, Direct Download) - -These GLB files from the Three.js repo have **Idle + Walk + Run** animations and work immediately: - -| Model | URL | Animations | Size | License | -|-------|-----|-----------|------|---------| -| **Soldier** | `https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/gltf/Soldier.glb` | Idle, Walk, Run, TPose | 2.2 MB | MIT | -| **Xbot** | `https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/gltf/Xbot.glb` | idle, walk, run + additive poses | 2.9 MB | MIT | -| **RobotExpressive** | `https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/gltf/RobotExpressive/RobotExpressive.glb` | Idle, Walking, Running, Dance, Jump + 8 more | 464 KB | MIT | -| **Fox** | `https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Fox/glTF-Binary/Fox.glb` | Survey (idle), Walk, Run | 163 KB | CC0/CC-BY 4.0 | - -### Gesture Characters (from `assets/3d-characters/`) - -These characters have **gesture/performance animations** instead of walk/run. Best for standing-position games (debate, dance-off, boxing, rhythm): - -| Model | Animations | Faces | Size | License | -|-------|-----------|-------|------|---------| -| **Trump** | StillLook (idle), Clap, Dance, Point, Talk, Twist | 1,266 | 1.2 MB | CC-BY (Sketchfab) | -| **Biden** | 1 Mixamo idle/sway | 50,000 | 3.3 MB | CC-BY (Sketchfab) | - -Copy from the character library (no auth needed): -```bash -cp /assets/3d-characters/models/trump.glb public/assets/models/ -cp /assets/3d-characters/models/biden.glb public/assets/models/ -``` - -**Trump clipMap:** -```js -{ - idle: 'root|TrumpStillLook_BipTrump', - clap: 'root|TrumpClap1_BipTrump', - dance: 'root|Trumpdance1_BipTrump', - point: 'root|TrumpPoint_BipTrump', - talk: 'root|TrumpTalk1_BipTrump', - twist: 'root|TrumpTwist_BipTrump' -} -``` - -**Biden clipMap:** -```js -{ idle: 'mixamo.com' } -``` - -**Game design for gesture characters:** Since these lack walk/run, design games where characters are stationary — debate battles, dance-offs, boxing rings, rhythm games, or turn-based encounters. Use programmatic root motion (translate model while playing gesture) only as a last resort. - -Download with curl — no auth needed: -```bash -curl -L -o public/assets/models/Soldier.glb "https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/models/gltf/Soldier.glb" -``` - -**Clip name mapping varies per model.** Always log clip names on load and define a `clipMap` per character: -```js -// Soldier: { idle: 'Idle', walk: 'Walk', run: 'Run' } -// Xbot: { idle: 'idle', walk: 'walk', run: 'run' } (lowercase) -// Robot: { idle: 'Idle', walk: 'Walking', run: 'Running' } -// Fox: { idle: 'Survey', walk: 'Walk', run: 'Run' } -``` - -## Character Selection — Tiered Fallback - -For EACH character in the game, try these tiers in order: - -**Tier 1 — Generate with Meshy AI** (preferred): Generate a custom character model matching the game's art direction. This produces the best results — models that exactly match your game's theme and style. -```bash -# Generate character from text description -MESHY_API_KEY= node scripts/meshy-generate.mjs \ - --mode text-to-3d \ - --prompt "a stylized , low poly game character, full body, t-pose" \ - --polycount 15000 --pbr \ - --output public/assets/models/ --slug - -# Then rig for animation (humanoid characters) -MESHY_API_KEY= node scripts/meshy-generate.mjs \ - --mode rig --task-id \ - --height 1.7 \ - --output public/assets/models/ --slug -rigged -``` -After rigging, the model comes with basic walk/run animations. Log clip names to build the `clipMap`. - -For named personalities, be descriptive: `"a cartoon caricature of , , low poly game character"`. - -**Tier 2 — Pre-built in `assets/3d-characters/`**: If Meshy is unavailable, check `manifest.json` for a name/theme match. Copy the GLB. Done. - -**Tier 3 — Search Sketchfab for character-specific model**: Use `find-3d-asset.mjs`: -```bash -node scripts/find-3d-asset.mjs --query " animated character" --max-faces 10000 --list-only -``` - -**Tier 4 — Generic library fallback**: Use the best thematic match from `assets/3d-characters/`: -- **Soldier** — action/military/generic human (default) -- **Xbot** — sci-fi/tech/futuristic -- **RobotExpressive** — cartoon/casual (most animations, 13 clips) -- **Fox** — nature/animal - -**Multi-character games**: When using Meshy, generate each character with distinct descriptions for visual variety. When falling back to library models, assign different models to each character (e.g., Soldier for one, Xbot for another). - -## Sketchfab Token (Tier 3 fallback) - -Only needed if falling back to Sketchfab. Search is free but **download requires `SKETCHFAB_TOKEN`**. Before prompting, check if the key already exists: -`test -f .env && grep -q '^SKETCHFAB_TOKEN=.' .env && echo "found"` -If found, export it with `set -a; . .env; set +a` and skip the prompt. - -If needed and not set, ask the user: - -> I need a Sketchfab API token to download this model. You can get one for free: -> 1. Sign in at https://sketchfab.com -> 2. Go to https://sketchfab.com/settings/password → "API Token" -> 3. Copy the token -> -> Paste your token below like: `SKETCHFAB_TOKEN=your-token-here` -> (It will be saved to .env and redacted from this conversation automatically.) - -Then use it via: `set -a; . .env; set +a && node scripts/find-3d-asset.mjs ...` - -## Search & Download Script - -Use `scripts/find-3d-asset.mjs` for both character searches AND non-character models (props, scenery, buildings): - -```bash -node scripts/find-3d-asset.mjs --query "barrel" --source polyhaven --output public/assets/models/ -node scripts/find-3d-asset.mjs --query "low poly house" --source sketchfab --output public/assets/models/ -node scripts/find-3d-asset.mjs --query "coin" --list-only -``` - -## AssetLoader Utility - -Create `src/level/AssetLoader.js`. **Critical: use `SkeletonUtils.clone()` for animated models** — regular `.clone()` breaks skeleton bindings and causes T-pose. - -```js -import * as THREE from 'three'; -import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; -import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js'; -import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js'; - -const loader = new GLTFLoader(); -loader.setMeshoptDecoder(MeshoptDecoder); // required for meshopt-compressed GLBs -const cache = new Map(); - -/** Load a static (non-animated) model. Uses regular clone. */ -export async function loadModel(path) { - const gltf = await _load(path); - const clone = gltf.scene.clone(true); - clone.traverse((c) => { - if (c.isMesh) { c.castShadow = true; c.receiveShadow = true; } - }); - return clone; -} - -/** Load an animated (skeletal) model. Uses SkeletonUtils.clone to preserve bone bindings. */ -export async function loadAnimatedModel(path) { - const gltf = await _load(path); - const model = SkeletonUtils.clone(gltf.scene); - model.traverse((c) => { - if (c.isMesh) { c.castShadow = true; c.receiveShadow = true; } - }); - return { model, clips: gltf.animations }; -} - -export function disposeAll() { - cache.forEach((p) => p.then((gltf) => { - gltf.scene.traverse((c) => { - if (c.isMesh) { - c.geometry.dispose(); - if (Array.isArray(c.material)) c.material.forEach(m => m.dispose()); - else c.material.dispose(); - } - }); - })); - cache.clear(); -} - -function _load(path) { - if (!cache.has(path)) { - cache.set(path, new Promise((resolve, reject) => { - loader.load(path, resolve, undefined, - (err) => reject(new Error(`Failed to load: ${path} — ${err.message || err}`))); - })); - } - return cache.get(path); -} -``` - -### Compressed GLB Support - -GLBs optimized by `scripts/optimize-glb.mjs` (or `meshy-generate.mjs` / `find-3d-asset.mjs` which call it automatically) use meshopt compression. The `MeshoptDecoder` import + `loader.setMeshoptDecoder()` call above is required to load these compressed files. Without it, Three.js will fail to parse the geometry buffers. - -### CRITICAL: SkeletonUtils.clone vs .clone() - -| Method | Use for | What happens | -|--------|---------|-------------| -| `gltf.scene.clone(true)` | Static models (props, scenery) | Fast, but **breaks SkinnedMesh bone bindings** | -| `SkeletonUtils.clone(gltf.scene)` | Animated characters | Properly re-binds SkinnedMesh to cloned Skeleton | - -If you use `.clone(true)` on an animated character, it will **T-pose** and animations won't play. Always use `SkeletonUtils.clone()` for anything with skeletal animation. - -## Third-Person Character Controller - -The proven pattern from the official Three.js `webgl_animation_walk` example: - -### Camera: OrbitControls with Target Follow - -```js -import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; - -// Setup -const orbitControls = new OrbitControls(camera, renderer.domElement); -orbitControls.enablePan = false; -orbitControls.enableDamping = true; -orbitControls.maxPolarAngle = Math.PI / 2 - 0.05; // don't go underground -orbitControls.target.set(0, 1, 0); - -// Each frame — move camera and target by same delta as player -const dx = player.position.x - oldX; -const dz = player.position.z - oldZ; -orbitControls.target.x += dx; -orbitControls.target.z += dz; -orbitControls.target.y = player.position.y + 1; -camera.position.x += dx; -camera.position.z += dz; -orbitControls.update(); -``` - -### Movement: Camera-Relative WASD - -```js -const _v = new THREE.Vector3(); -const _q = new THREE.Quaternion(); -const _up = new THREE.Vector3(0, 1, 0); - -// Get camera azimuth from OrbitControls -const azimuth = orbitControls.getAzimuthalAngle(); - -// Build input vector from WASD -let ix = 0, iz = 0; -if (keyW) iz -= 1; -if (keyS) iz += 1; -if (keyA) ix -= 1; -if (keyD) ix += 1; - -// Rotate input by camera azimuth → world space movement -_v.set(ix, 0, iz).normalize(); -_v.applyAxisAngle(_up, azimuth); - -// Move player -player.position.addScaledVector(_v, speed * delta); - -// Rotate model to face movement direction -// +PI offset because most GLB models face +Z but atan2 gives 0 for +Z -const angle = Math.atan2(_v.x, _v.z) + Math.PI; -_q.setFromAxisAngle(_up, angle); -model.quaternion.rotateTowards(_q, turnSpeed * delta); -``` - -### Animation: fadeToAction Pattern - -```js -fadeToAction(name, duration = 0.3) { - const next = actions[name]; - if (!next || next === activeAction) return; - if (activeAction) activeAction.fadeOut(duration); - next.reset().setEffectiveTimeScale(1).setEffectiveWeight(1).fadeIn(duration).play(); - activeAction = next; -} - -// In update loop: -if (isMoving) { - fadeToAction(shiftHeld ? 'run' : 'walk'); -} else { - fadeToAction('idle'); -} -if (mixer) mixer.update(delta); -``` - -## Post-Load Verification (MANDATORY) - -After loading ANY 3D model (Meshy-generated, library, or Sketchfab), **always verify orientation and scale**. Skipping this leads to backwards characters and models that overflow their containers. - -1. **Log bounding box** immediately after loading — size and center -2. **Check facing direction** — most Meshy models face +Z, most library models vary. Set `rotationY` per model in Constants.js. Start with `Math.PI` for Meshy models. -3. **Check scale** — calculate auto-scale to fit target height. Ensure models fit within their environment (e.g., characters inside a ring, players on a platform). -4. **Align to floor** — set `position.y = -box.min.y` to plant feet on ground -5. **Take a Playwright screenshot** to visually confirm facing + fit. Don't skip this. - -See the `meshyai` skill's "Post-Generation Verification" section for detailed code patterns. - -## Common Pitfalls - -1. **T-posing animated characters** — You used `.clone()` instead of `SkeletonUtils.clone()`. The skeleton binding is broken. -2. **Model faces wrong direction** — Meshy models typically face +Z. Add `rotationY: Math.PI` in Constants.js. **Always verify with a screenshot.** -3. **Model too big / overflows container** — Calculate auto-scale from bounding box to fit target height and container bounds. Never assume scale=1.0 is correct. -4. **Animation not playing** — Forgot `mixer.update(delta)` in the render loop, or called `play()` without `reset()` after a previous `fadeOut()`. -5. **Camera fights with OrbitControls** — Never call `camera.lookAt()` when using OrbitControls. It manages lookAt internally. -6. **"Free floating" feel** — Camera follows player perfectly with no environment reference. Add a grid (`THREE.GridHelper`) and place props near spawn so movement is visible. -7. **Clip names differ per model** — Always log `clips.map(c => c.name)` on load and define a `clipMap` per character. Never hardcode clip names. -8. **Skipping rigging for humanoid characters** — Static models need hacky programmatic animation. Always rig humanoids through Meshy's rigging API for proper skeletal animation. - -## Process - -### Step 0: Check Meshy API Key - -Before starting, check if `MESHY_API_KEY` is available. If not, ask the user for one (see "Meshy API Key" section above). If the user skips, proceed with Tier 2+ fallbacks. - -### Step 1: Audit - -- Read `package.json` to confirm Three.js -- Read entity files for `BoxGeometry`, `SphereGeometry`, etc. -- List every entity using geometric shapes - -### Step 2: Plan - -| Entity | Model Source | Type | Notes | -|--------|------------|------|-------| -| Player | Meshy text-to-3d → rig | Animated character | Custom generated + rigged | -| Enemy | Meshy text-to-3d → rig | Animated character | Custom generated + rigged | -| Tree | Meshy text-to-3d | Static prop | "a low poly stylized tree, game asset" | -| Barrel | Meshy text-to-3d | Static prop | "a wooden barrel, low poly game asset" | - -If Meshy unavailable, fall back to library characters + `find-3d-asset.mjs` for props. - -### Step 3: Generate / Download - -```bash -# With Meshy (preferred) — generate each entity -MESHY_API_KEY= node scripts/meshy-generate.mjs \ - --mode text-to-3d \ - --prompt "a heroic knight, low poly game character, full body" \ - --polycount 15000 --pbr \ - --output public/assets/models/ --slug player - -# Rig humanoid characters for animation -MESHY_API_KEY= node scripts/meshy-generate.mjs \ - --mode rig --task-id --height 1.7 \ - --output public/assets/models/ --slug player-rigged - -# Generate static props -MESHY_API_KEY= node scripts/meshy-generate.mjs \ - --mode text-to-3d \ - --prompt "a wooden barrel, low poly game asset" \ - --polycount 5000 \ - --output public/assets/models/ --slug barrel - -# Fallback: library characters -cp /assets/3d-characters/models/Soldier.glb public/assets/models/ - -# Fallback: search free libraries for props -node scripts/find-3d-asset.mjs --query "barrel" --source polyhaven --output public/assets/models/ -``` - -### Step 4: Integrate - -1. Create `src/level/AssetLoader.js` with `SkeletonUtils.clone()` for animated models -2. Add character definitions to Constants.js with `clipMap` per model -3. Set up `OrbitControls` camera with target-follow pattern -4. Implement `fadeToAction()` for animation crossfading -5. Use camera-relative WASD movement with `applyAxisAngle(_up, azimuth)` -6. Add `Math.PI` offset to model facing rotation -7. Add `THREE.GridHelper` to ground for visible movement reference - -### Step 5: Verify - -- Run `npm run dev` and walk around with WASD -- Confirm character animates (Idle when stopped, Walk when moving, Run with Shift) -- Confirm character faces movement direction -- Orbit camera with mouse drag, zoom with scroll -- Run `npm run build` to confirm no errors - -## Troubleshooting - -### Model stuck in T-pose (not animating) -**Cause:** Using `.clone(true)` instead of `SkeletonUtils.clone()` breaks skeleton bindings on animated GLB models. -**Fix:** Always use `SkeletonUtils.clone()` from `three/addons/utils/SkeletonUtils.js` for any model with animations. Regular `.clone()` copies the mesh but not the skeleton bindings. - -### Sketchfab download returns 403 Forbidden -**Cause:** The Sketchfab API requires authentication for model downloads, or the model license doesn't permit downloading. -**Fix:** Ensure `SKETCHFAB_TOKEN` is set in environment. Check the model's license on Sketchfab — only CC-licensed models can be downloaded via API. Try alternative sources (Poly Haven, Poly.pizza) which don't require auth for free models. - -### meshopt decoder error on model load -**Cause:** Some GLB files use meshopt compression which requires a decoder not loaded by default in Three.js. -**Fix:** Add the meshopt decoder before loading: `import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js'; loader.setMeshoptDecoder(MeshoptDecoder);` - -### Animation not playing after model loads -**Cause:** Animation clips not connected to the model's AnimationMixer, or clip names don't match expected values. -**Fix:** Create an `AnimationMixer` for the model, then use `mixer.clipAction(clip).play()`. Log `gltf.animations.map(a => a.name)` to see available clip names — they vary by model source. Define a `clipMap` per character to map generic names (idle, walk, run) to actual clip names. - -### Camera fights with OrbitControls (jittering) -**Cause:** Manual camera position updates conflict with OrbitControls trying to maintain its own camera state. -**Fix:** Don't set `camera.position` directly when using OrbitControls. Instead, update `controls.target` to follow the player, and let OrbitControls manage the camera position relative to the target. Call `controls.update()` once per frame in the animation loop. - -## Security Notes - -- **Third-party model downloads**: Models downloaded from Sketchfab, Poly Haven, and Poly.pizza are binary GLB/GLTF files (3D geometry, textures, animations). They are not executable code and cannot perform arbitrary actions. Three.js's GLTFLoader parses only valid glTF data structures. -- **Meshy AI API**: Meshy generates models server-side from text/image prompts. The API key is stored in a local `.env` file and passed only to the Meshy API. Generated models are downloaded as GLB binaries. -- **API key storage**: All API keys (`MESHY_API_KEY`, `SKETCHFAB_TOKEN`) are stored in the project's `.env` file (which should be gitignored) and loaded via environment variables. Keys are never embedded in game source code or deployed artifacts. -- **Content scope**: Downloaded models are used only as visual assets rendered by Three.js. No text content from third-party sources is interpreted as instructions or commands. - -## Checklist - -- [ ] `AssetLoader.js` uses `SkeletonUtils.clone()` for animated models -- [ ] `clipMap` defined per character model (clip names vary) -- [ ] `OrbitControls` with target-follow (not manual camera.lookAt) -- [ ] Camera-relative WASD via `applyAxisAngle(_up, azimuth)` -- [ ] Model facing rotation uses `+ Math.PI` offset in `atan2` -- [ ] `fadeToAction()` pattern with `reset()` before `fadeIn().play()` -- [ ] `mixer.update(delta)` called every frame -- [ ] Ground grid or reference objects for visible movement -- [ ] `destroy()` disposes geometry + materials + stops mixer -- [ ] `npm run build` succeeds diff --git a/.agents/skills/graphify/.graphify_version b/.agents/skills/graphify/.graphify_version deleted file mode 100644 index a4c112aa06..0000000000 --- a/.agents/skills/graphify/.graphify_version +++ /dev/null @@ -1 +0,0 @@ -0.9.37 \ No newline at end of file diff --git a/.agents/skills/graphify/SKILL.md b/.agents/skills/graphify/SKILL.md deleted file mode 100644 index 388123ab96..0000000000 --- a/.agents/skills/graphify/SKILL.md +++ /dev/null @@ -1,721 +0,0 @@ ---- -name: graphify -description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools." ---- - -# /graphify - -Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md. - -## Usage - -``` -/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault) -/graphify # full pipeline on specific path -/graphify https://github.com// # clone repo then run full pipeline on it -/graphify https://github.com// --branch # clone a specific branch -/graphify ... # clone multiple repos, build each, merge into one cross-repo graph -/graphify --mode deep # thorough extraction, richer INFERRED edges -/graphify --update # incremental - re-extract only new/changed files -/graphify --directed # build directed graph (preserves edge direction: source→target) -/graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy -/graphify --cluster-only # rerun clustering on existing graph -/graphify --no-viz # skip visualization, just report + JSON -/graphify --html # (HTML is generated by default - this flag is a no-op) -/graphify --svg # also export graph.svg (embeds in Notion, GitHub) -/graphify --graphml # export graph.graphml (Gephi, yEd) -/graphify --neo4j # generate graphify-out/cypher.txt for Neo4j -/graphify --neo4j-push bolt://localhost:7687 # push directly to Neo4j -/graphify --falkordb # generate graphify-out/cypher.txt for FalkorDB -/graphify --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB -/graphify --mcp # start MCP stdio server for agent access -/graphify --watch # watch folder, auto-rebuild on code changes (no LLM needed) -/graphify --wiki # build agent-crawlable wiki (index.md + one article per community) -/graphify --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault) -/graphify add # fetch URL, save to ./raw, update graph -/graphify add --author "Name" # tag who wrote it -/graphify add --contributor "Name" # tag who added it to the corpus -/graphify query "" # BFS traversal - broad context -/graphify query "" --dfs # DFS - trace a specific path -/graphify query "" --budget 1500 # cap answer at N tokens -/graphify path "AuthModule" "Database" # shortest path between two concepts -/graphify explain "SwinTransformer" # plain-language explanation of a node -``` - -## What graphify is for - -Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about. - -## What You Must Do When Invoked - -If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return. - -**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Use the JSON argument handoff and safe query block in `references/query.md`. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it. - -If no path was given, use `.` (current directory). Do not ask the user for a path. - -If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path. - -Follow these steps in order. Do not skip steps. - -### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths) - -Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step. - -### Step 1 - Ensure graphify is installed - -First run `mkdir -p graphify-out` (it contains no user input). Then use a -non-shell file-writing tool to create -`graphify-out/.graphify_args.json` with the user-controlled path as JSON: - -```json -{"input_path":"the exact path supplied by the user"} -``` - -Never paste the path into shell or Python source. The blocks below read it from -that inert JSON channel so quotes, backticks, and substitutions remain data. - -```bash -# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs) -PYTHON="" -GRAPHIFY_BIN=$(which graphify 2>/dev/null) -# 1. uv tool installs — most reliable on modern Mac/Linux -if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then - _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null) - if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi -fi -# 2. Read shebang from graphify binary (pipx and direct pip installs) -if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then - _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!') - case "$_SHEBANG" in - *[!a-zA-Z0-9/_.@-]*) ;; - *) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;; - esac -fi -# 3. Fall back to python3 -if [ -z "$PYTHON" ]; then PYTHON="python3"; fi -if ! "$PYTHON" -c "import graphify" 2>/dev/null; then - if command -v uv >/dev/null 2>&1; then - uv tool install --upgrade graphifyy -q 2>&1 | tail -3 - _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null) - if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi - else - "$PYTHON" -m pip install graphifyy -q 2>/dev/null \ - || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3 - fi -fi -# Write interpreter path for all subsequent steps (persists across invocations) -mkdir -p graphify-out -"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)" -# Save scan root so `graphify update` (no args) knows where to look next time. -# User input comes from JSON, never from textual command substitution. -GRAPHIFY_INPUT_PATH=$("$PYTHON" -c 'import json; print(json.load(open("graphify-out/.graphify_args.json", encoding="utf-8"))["input_path"])') -printf '%s\n' "$(cd -- "$GRAPHIFY_INPUT_PATH" && pwd)" > graphify-out/.graphify_root -``` - -If the import succeeds, print nothing and move straight to Step 2. - -**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.** - -### Step 2 - Detect files - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from graphify.detect import detect -from pathlib import Path -result = detect(Path(Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip())) -# Write the sidecar from Python, not a shell redirect, so the same block renders -# on PowerShell hosts without console-encoding drift (#2528). -Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\") -print(f'Detected {result[\"total_files\"]} files') -" -``` - -The resolved scan root is now read from `.graphify_root`. Do NOT cat or print the JSON - read it silently and present a clean summary instead: - -``` -Corpus: X files · ~Y words - code: N files (.py .ts .go ...) - docs: N files (.md .txt ...) - papers: N files (.pdf ...) - images: N files - video: N files (.mp4 .mp3 ...) -``` - -Omit any category with 0 files from the summary. - -Then act on it: -- If `total_files` is 0: stop with "No supported files found in [path]." -- If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106). -- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count: - - Read `scan_root` from the detect JSON (always an absolute path to the resolved input path). - - Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`). - - Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars. - - For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`. - - If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed. - - Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding. -- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not. - -### Step 2.5 - Video and audio (only if video files detected) - -Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3. - -### Step 3 - Extract entities and relationships - -**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it. - -This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens). - -> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one. - -**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user: -> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`). - -Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it. - -> **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill. - -**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.** - -Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers. - -#### Part A - Structural extraction for code files - -For any code files detected, run AST extraction in parallel with Part B subagents: - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.extract import collect_files, extract -from pathlib import Path -import json - -code_files = [] -detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\")) -for f in detect.get('files', {}).get('code', []): - code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)]) - -if code_files: - result = extract(code_files, cache_root=Path(Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip())) - Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\") - print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges') -else: - Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\") - print('No code files - skipping AST extraction') -" -``` - -#### Part B - Semantic extraction (parallel subagents) - -**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`): - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path -Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8') -" -``` - -**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.** - -Before dispatching subagents, print a timing estimate: -- Load `total_words` and file counts from `graphify-out/.graphify_detect.json` -- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25) -- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit)) -- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys" - -**Step B0 - Check extraction cache first** - -Before dispatching any subagents, check which files already have cached extraction results: - -SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument. - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from graphify.cache import check_semantic_cache -from pathlib import Path - -detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\")) -# Only content files go to semantic extraction. Code is already covered structurally -# by the AST pass (Part A); flattening every category here makes subagents re-read -# every source file (#1392). Video is transcribed to a document in Step 2.5 first. -all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])] - -cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip(), prompt_file='SPEC_PATH') - -# Always (re)write the cache file: write hits, else DELETE any leftover from a prior -# run so Part C never merges a stale .graphify_cached.json (#1392). -if cached_nodes or cached_edges or cached_hyperedges: - Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding=\"utf-8\") -else: - Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True) -Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding=\"utf-8\") -print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction') -" -``` - -Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly. - -**Step B1 - Split into chunks** - -Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted. - -**Step B2 - Dispatch ALL subagents in a single message** - -> Uses the `Task` tool for parallel subagent dispatch. -> Call `Task` once per chunk — ALL in the same response so they run in parallel. - -Pass the extraction prompt as the task description: - -``` -Task(description="Your task is to perform the following. Follow the instructions below exactly.\n\n\n[extraction prompt, with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE substituted]\n\n\nExecute this now. Output ONLY the structured JSON response.") -``` - -Each subagent writes its result to its own `graphify-out/.graphify_chunk_NN.json`. Collect results as each `Task` completes and parse each as JSON. - -CHUNK_PATH must be an **absolute** path — derive it before dispatching: -```bash -PROJECT_ROOT=$(pwd) # cwd — where Part C globs graphify-out/ (NOT .graphify_root/scan dir, #1392) -# Then for chunk N: CHUNK_PATH="${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json" -``` - -Subagent prompt template: - -See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH. - -**Step B3 - Collect, cache, and merge** - -Wait for all subagents. For each result: -- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal -- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache -- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip. -- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort - -If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used. - -Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run: -```bash -$(cat graphify-out/.graphify_python) -c " -import json, glob -from pathlib import Path - -chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json')) -all_nodes, all_edges, all_hyperedges = [], [], [] -total_in, total_out = 0, 0 -for c in chunks: - d = json.loads(Path(c).read_text(encoding=\"utf-8\")) - all_nodes += d.get('nodes', []) - all_edges += d.get('edges', []) - all_hyperedges += d.get('hyperedges', []) - total_in += d.get('input_tokens', 0) - total_out += d.get('output_tokens', 0) -Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({ - 'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, - 'input_tokens': total_in, 'output_tokens': total_out, -}, indent=2, ensure_ascii=False), encoding=\"utf-8\") -print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens') -" -``` - -Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939): -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from graphify.cache import save_semantic_cache -from pathlib import Path - -new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} -uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding=\"utf-8\").splitlines() if line] -saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip(), allowed_source_files=uncached, prompt_file='SPEC_PATH') -print(f'Cached {saved} files') -" -``` - -Merge cached + new results into `graphify-out/.graphify_semantic.json`: -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path - -cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} -new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} - -all_nodes = cached['nodes'] + new.get('nodes', []) -all_edges = cached['edges'] + new.get('edges', []) -all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', []) -seen = set() -deduped = [] -for n in all_nodes: - if n['id'] not in seen: - seen.add(n['id']) - deduped.append(n) - -merged = { - 'nodes': deduped, - 'edges': all_edges, - 'hyperedges': all_hyperedges, - 'input_tokens': new.get('input_tokens', 0), - 'output_tokens': new.get('output_tokens', 0), -} -Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\") -print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)') -" -``` -Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json` - -#### Part C - Merge AST + semantic into final extraction - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from pathlib import Path - -ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\")) -sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\")) - -# Merge: AST nodes first, semantic nodes deduplicated by id -seen = {n['id'] for n in ast['nodes']} -merged_nodes = list(ast['nodes']) -for n in sem['nodes']: - if n['id'] not in seen: - merged_nodes.append(n) - seen.add(n['id']) - -merged_edges = ast['edges'] + sem['edges'] -merged_hyperedges = sem.get('hyperedges', []) -merged = { - 'nodes': merged_nodes, - 'edges': merged_edges, - 'hyperedges': merged_hyperedges, - 'input_tokens': sem.get('input_tokens', 0), - 'output_tokens': sem.get('output_tokens', 0), -} -Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\") -total = len(merged_nodes) -edges = len(merged_edges) -print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)') -" -``` - -### Step 4 - Build graph, cluster, analyze, generate outputs - -**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace only `IS_DIRECTED`; the scan root already comes from `.graphify_root`. - -```bash -mkdir -p graphify-out -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.build import build_from_json -from graphify.cluster import cluster, score_all -from graphify.analyze import god_nodes, surprising_connections, suggest_questions -from graphify.report import generate -from graphify.export import to_json -from pathlib import Path - -extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\")) -detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\")) - -# root= mirrors the --update runbook (#1361): relativize source_file to the same -# base so the full build and incremental --update never drift apart on re-extract. -G = build_from_json(extraction, root=Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip(), directed=IS_DIRECTED) -# Guard BEFORE any write: an empty extraction must not clobber a good graph.json / -# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392). -if G.number_of_nodes() == 0: - print('ERROR: Graph is empty - extraction produced no nodes.') - print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.') - raise SystemExit(1) -communities = cluster(G) -cohesion = score_all(G, communities) -tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)} -gods = god_nodes(G) -surprises = surprising_connections(G, communities) -labels = {cid: 'Community ' + str(cid) for cid in communities} -# Placeholder questions - regenerated with real labels in Step 5 -questions = suggest_questions(G, communities, labels) - -# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing -# nothing) when the new graph is smaller than the existing graph.json. Only write -# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so -# they never describe a graph that graph.json doesn't contain (#1392). -wrote = to_json(G, communities, 'graphify-out/graph.json') -if not wrote: - print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).') - print('If this shrink is intentional (you deleted files), re-run a full build with --force.') - raise SystemExit(1) -report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip(), suggested_questions=questions) -Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\") -analysis = { - 'communities': {str(k): v for k, v in communities.items()}, - 'cohesion': {str(k): v for k, v in cohesion.items()}, - 'gods': gods, - 'surprises': surprises, - 'questions': questions, -} -Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\") -print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities') -" -``` - -If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization. - -The scan root is read from `.graphify_root`. - -### Step 4.5 - Graph health check (read-only integrity gate) - -A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts. - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path -from graphify.diagnostics import diagnose_extraction, format_diagnostic_report - -extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\")) -summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip()) -print(format_diagnostic_report(summary)) -flags = [f'{summary[k]} {label}' for k, label in ( - ('dangling_endpoint_edges', 'dangling-endpoint edges'), - ('missing_endpoint_edges', 'missing-endpoint edges'), - ('self_loop_edges', 'self-loop edges'), - ('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'), - ('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'), -) if summary.get(k, 0)] -print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).') -" -``` - -Substitute only `IS_DIRECTED` as in Step 4; the scan root is read from `.graphify_root`. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules). - -### Step 5 - Label communities - -Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading"). - -Then regenerate the report and save the labels for the visualizer: - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.build import build_from_json -from graphify.cluster import score_all -from graphify.analyze import god_nodes, surprising_connections, suggest_questions -from graphify.report import generate -from graphify.export import to_json -from pathlib import Path - -extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\")) -detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\")) -analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\")) - -# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity. -G = build_from_json(extraction, root=Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip(), directed=IS_DIRECTED) -communities = {int(k): v for k, v in analysis['communities'].items()} -cohesion = {int(k): v for k, v in analysis['cohesion'].items()} -tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)} - -# LABELS - replace these with the names you chose above -labels = LABELS_DICT - -# Regenerate questions with real community labels (labels affect question phrasing) -questions = suggest_questions(G, communities, labels) - -report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip(), suggested_questions=questions) -Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\") -Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\") -# Re-export so graph.json nodes carry the curated community_name (#2490). -# Same extraction as Step 4, so the #479 shrink-guard passes on node count; -# if it still refuses, surface the guard message - do not force past it. -wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels) -if not wrote: - print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).') - print('If this shrink is intentional (you deleted files), re-run a full build with --force.') -print('Report updated with community labels') -" -``` - -Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`). -The scan root is read from `.graphify_root`. - -### Step 6 - Generate Obsidian vault (opt-in) + HTML - -**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node. - -If `--obsidian` was given: - -- If `--obsidian-dir ` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`. - -```bash -graphify export obsidian -# or with custom dir: graphify export obsidian --dir ~/vaults/my-project -``` - -Generate the HTML graph (always, unless `--no-viz`): - -```bash -graphify export html # auto-aggregates to community view if graph > 5000 nodes -# or: graphify export html --no-viz -``` - -### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) - -These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available. - ---- - -### Step 9 - Save manifest, update cost tracker, clean up, and report - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path -from datetime import datetime, timezone -from graphify.detect import save_manifest - -# Save manifest for --update -detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\")) -extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\")) -# In --update mode, 'all_files' carries the full corpus; 'files' is the changed -# subset. Full-rebuild mode populates only 'files', so the fallback handles that. -# root= relativizes the manifest keys to the scan root (same base as the build), -# so the on-disk manifest is portable across clones/machines and a later --update -# matches cached files instead of missing every one (#1417). -# -# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output: -# a detected file whose chunk failed or was omitted must stay unstamped so the -# next --update re-queues it, otherwise it is marked done and its content is lost -# forever (#2015). This mirrors the library extract path exactly -# (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the -# raw corpus. Code files are always stamped (AST is deterministic); only semantic -# types are gated on output. -from graphify.cli import _stamped_manifest_files -_corpus = detect.get('all_files') or detect['files'] -_manifest_files = _stamped_manifest_files(_corpus, extract, Path(Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip())) -# Files dispatched this run (the changed subset) but NOT stamped above still carry -# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues -# them instead of reading them as unchanged (#1948). -_sem_types = ('document', 'paper', 'image') -_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl} -_stamped = {f for fl in _manifest_files.values() for f in fl} -_cleared = _dispatched - _stamped -# scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root -# files newly excluded since last run are dropped rather than masquerading as -# deletions; untouched files' prior rows are still preserved (#1908). -_scan = {f for fl in _corpus.values() for f in fl} -save_manifest(_manifest_files, root=Path('graphify-out/.graphify_root').read_text(encoding='utf-8').strip(), scan_corpus=_scan, clear_semantic=_cleared or None) - -# Update cumulative cost tracker -input_tok = extract.get('input_tokens', 0) -output_tok = extract.get('output_tokens', 0) - -cost_path = Path('graphify-out/cost.json') -if cost_path.exists(): - cost = json.loads(cost_path.read_text(encoding=\"utf-8\")) -else: - cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0} - -cost['runs'].append({ - 'date': datetime.now(timezone.utc).isoformat(), - 'input_tokens': input_tok, - 'output_tokens': output_tok, - 'files': detect.get('total_files', 0), -}) -cost['total_input_tokens'] += input_tok -cost['total_output_tokens'] += output_tok -cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"utf-8\") - -print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens') -print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)') -" -rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json -find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null -rm -f graphify-out/.needs_update 2>/dev/null || true -``` - -The manifest uses the same resolved scan root from `.graphify_root` as Steps 4-5. - -Tell the user (omit the obsidian line unless --obsidian was given): -``` -Graph complete. Outputs in PATH_TO_DIR/graphify-out/ - - graph.html - interactive graph, open in browser - GRAPH_REPORT.md - audit report - graph.json - raw graph data - obsidian/ - Obsidian vault (only if --obsidian was given) -``` - -If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi - -Replace PATH_TO_DIR with the actual absolute path of the directory that was processed. - -Then paste these sections from GRAPH_REPORT.md directly into the chat: -- God Nodes -- Surprising Connections -- Suggested Questions - -Do NOT paste the full report - just those three sections. Keep it concise. - -Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask: - -> "The most interesting question this graph can answer: **[question]**. Want me to trace it?" - -If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report. - -The graph is the map. Your job after the pipeline is to be the guide. - ---- - -## Interpreter guard for subcommands - -Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first: - -```bash -if [ ! -f graphify-out/.graphify_python ]; then - GRAPHIFY_BIN=$(which graphify 2>/dev/null) - if [ -n "$GRAPHIFY_BIN" ]; then - PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!') - case "$PYTHON" in *[!a-zA-Z0-9/_.@-]*) PYTHON="python3" ;; esac - else - PYTHON="python3" - fi - mkdir -p graphify-out - "$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)" -fi -``` - -## For --update and --cluster-only - -Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows. - ---- - -## For /graphify query - -When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it: - -Use the JSON argument handoff and safe CLI block in `references/query.md`; never interpolate the question into a shell command. - -Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`. - ---- - -## For /graphify add and --watch - -Neither is part of the default build. When the user runs `/graphify add ` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`. - ---- - -## For the commit hook and native AGENTS.md integration - -When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's AGENTS.md, see `references/hooks.md`. - ---- - -## Honesty Rules - -- Never invent an edge. If unsure, use AMBIGUOUS. -- Never skip the corpus check warning. -- Always show token cost in the report. -- Never hide cohesion scores behind symbols - show the raw number. -- Never run HTML viz on a graph with more than 5,000 nodes without warning the user. diff --git a/.agents/skills/graphify/references/add-watch.md b/.agents/skills/graphify/references/add-watch.md deleted file mode 100644 index 45a5424239..0000000000 --- a/.agents/skills/graphify/references/add-watch.md +++ /dev/null @@ -1,65 +0,0 @@ -# graphify reference: add a URL and watch a folder - -Load this when the user ran `/graphify add ` or passed `--watch`. Neither is part of the default build. - -## For /graphify add - -Fetch a URL and add it to the corpus, then update the graph. - -Use a non-shell file-writing tool to create `graphify-out/.graphify_add_args.json`: - -```json -{"url":"exact user URL","author":"optional author","contributor":"optional contributor"} -``` - -Do not paste any of these values into command or Python source. - -```bash -$(cat graphify-out/.graphify_python) -c " -import json, sys -from graphify.ingest import ingest -from pathlib import Path - -try: - args = json.loads(Path('graphify-out/.graphify_add_args.json').read_text(encoding='utf-8')) - out = ingest(args['url'], Path('./raw'), author=args.get('author'), contributor=args.get('contributor')) - print(f'Saved to {out}') -except ValueError as e: - print(f'error: {e}', file=sys.stderr) - sys.exit(1) -except RuntimeError as e: - print(f'error: {e}', file=sys.stderr) - sys.exit(1) -" -``` - -If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph. - -Supported URL types (auto-detected): -- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`) -- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author -- arXiv → abstract + metadata saved as `.md` -- PDF → downloaded as `.pdf` -- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run -- Any webpage → converted to markdown via html2text - ---- - -## For --watch - -Start a background watcher that monitors a folder and auto-updates the graph when files change. - -```bash -$(cat graphify-out/.graphify_python) -m graphify.watch "$(cat graphify-out/.graphify_root)" --debounce 3 -``` - -Run Step 1 with the folder to watch so `.graphify_root` contains its resolved path. Behavior depends on what changed: - -- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically. -- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required). - -Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file. - -Press Ctrl+C to stop. - -For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves. diff --git a/.agents/skills/graphify/references/exports.md b/.agents/skills/graphify/references/exports.md deleted file mode 100644 index 242ff868e0..0000000000 --- a/.agents/skills/graphify/references/exports.md +++ /dev/null @@ -1,87 +0,0 @@ -# graphify reference: extra exports and benchmark - -Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-push`, `--falkordb`, `--falkordb-push`, `--svg`, `--graphml`, `--mcp`), or when the corpus is large enough for the token-reduction benchmark. Each step runs only for its own flag. - -### Step 6b - Wiki (only if --wiki flag) - -**Only run this step if `--wiki` was explicitly given in the original command.** - -Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available. - -```bash -graphify export wiki -``` - -### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag) - -**If `--neo4j`** - generate a Cypher file for manual import: - -```bash -graphify export neo4j -``` - -**If `--neo4j-push `** - push directly to a running Neo4j instance. Ask the user for credentials if not provided: - -```bash -graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD -``` - -Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates. - -### Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag) - -**If `--falkordb`** - generate a Cypher file. The statements are OpenCypher, but FalkorDB's `GRAPH.QUERY` runs one statement at a time (no bulk script import like Neo4j's `cypher-shell`), so prefer `--falkordb-push` to load a graph. Use this only when you want the portable `cypher.txt` artifact: - -```bash -graphify export falkordb -``` - -**If `--falkordb-push `** - push directly to a running FalkorDB instance. Credentials are optional; ask the user only if the instance requires auth: - -```bash -graphify export falkordb --push falkordb://localhost:6379 -``` - -Default URI is `falkordb://localhost:6379` (the scheme is informational - `redis://` or a bare `host:port` work too), auth is optional, and the target graph defaults to `graphify`. Uses MERGE - safe to re-run without creating duplicates. - -### Step 7b - SVG export (only if --svg flag) - -```bash -graphify export svg -``` - -### Step 7c - GraphML export (only if --graphml flag) - -```bash -graphify export graphml -``` - -### Step 7d - MCP server (only if --mcp flag) - -```bash -$(cat graphify-out/.graphify_python) -m graphify.serve graphify-out/graph.json -``` - -This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live. - -To configure in Claude Desktop, add to `claude_desktop_config.json`. Claude Desktop can't run `$(...)`, and under `uv tool install` the system `python3` can't import graphify — so set `command` to the **absolute interpreter path** printed by `cat graphify-out/.graphify_python`: -```json -{ - "mcpServers": { - "graphify": { - "command": "", - "args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"] - } - } -} -``` - -### Step 8 - Token reduction benchmark (only if total_words > 5000) - -If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run: - -```bash -graphify benchmark -``` - -Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora. diff --git a/.agents/skills/graphify/references/extraction-spec.md b/.agents/skills/graphify/references/extraction-spec.md deleted file mode 100644 index 388df7674f..0000000000 --- a/.agents/skills/graphify/references/extraction-spec.md +++ /dev/null @@ -1,70 +0,0 @@ -# graphify reference: extraction subagent prompt - -Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH). - -``` -You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment. -Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble. - -Files (chunk CHUNK_NUM of TOTAL_CHUNKS): -FILE_LIST - -Rules: -- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2") -- INFERRED: reasonable inference (shared data structure, implied dependency) -- AMBIGUOUS: uncertain - flag for review, do not omit - -Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns). - Do not re-extract imports - AST already has those. -Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected. -Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction. `calls` edges MUST stay within one language: a Python function cannot `calls` a JS/TS/Go/Rust/Java symbol and vice versa — cross-language call edges are phantom artifacts, never emit them. -Image files: use vision to understand what the image IS - do not just OCR. - UI screenshot: layout patterns, design decisions, key elements, purpose. - Chart: metric, trend/insight, data source. - Tweet/post: claim as node, author, concepts mentioned. - Diagram: components and connections. - Research figure: what it demonstrates, method, result. - Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS. - -DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps, - shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting. - -Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples: -- Two functions that both validate user input but never call each other -- A class in code and a concept in a paper that describe the same algorithm -- Two error types that handle the same failure mode differently -Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things. - -Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples: -- All classes that implement a common protocol or interface -- All functions in an authentication flow (even if they don't all call each other) -- All concepts from a paper section that form one coherent idea -Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk. - -If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, - contributor onto every node from that file. - -confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default: -- EXTRACTED edges: confidence_score = 1.0 always -- INFERRED edges: pick exactly ONE value from this set — never 0.5: - 0.95 direct structural evidence (shared data structure, named cross-file reference). - 0.85 strong inference (clear functional alignment, no direct symbol link). - 0.75 reasonable inference (shared problem domain + similar shape, requires interpretation). - 0.65 weak inference (thematically related, no shape evidence). - 0.55 speculative but plausible (surface-level co-occurrence only). - Models follow discrete rubrics better than continuous ranges; the bimodal - distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the - range guidance is being collapsed to a binary. If no value above fits, mark - the edge AMBIGUOUS rather than picking 0.4 or below. -- AMBIGUOUS edges: 0.1-0.3 - -Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it. - -Generate the extraction JSON matching this schema exactly: -{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":""}],"input_tokens":0,"output_tokens":0} - -source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate. - -Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost): -CHUNK_PATH -``` diff --git a/.agents/skills/graphify/references/github-and-merge.md b/.agents/skills/graphify/references/github-and-merge.md deleted file mode 100644 index a41ea06e17..0000000000 --- a/.agents/skills/graphify/references/github-and-merge.md +++ /dev/null @@ -1,46 +0,0 @@ -# graphify reference: GitHub clone and cross-repo merge - -Load this when the user passed one or more `https://github.com/...` URLs, or named several local subfolders to merge into one graph. - -### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given) - -**Single repo:** -```bash -LOCAL_PATH=$(graphify clone [--branch ]) -# Use LOCAL_PATH as the target for all subsequent steps -``` - -**Multiple repos (cross-repo graph):** -```bash -# Clone each repo, run the full pipeline on each, then merge -graphify clone # → ~/.graphify/repos// -graphify clone # → ~/.graphify/repos// -# Run /graphify on each local path to produce their graph.json files -# Then merge: -graphify merge-graphs \ - ~/.graphify/repos///graphify-out/graph.json \ - ~/.graphify/repos///graphify-out/graph.json \ - --out graphify-out/cross-repo-graph.json -``` - -Graphify clones into `~/.graphify/repos//` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin. - -**Multiple local subfolders (monorepo or multi-service layout):** - -The skill pipeline writes all intermediate and final outputs to `graphify-out/` in the current working directory. Running the skill on each subfolder separately will clobber the same output dir. Instead, use the CLI directly for each subfolder — it places `graphify-out/` *inside* the scanned path: - -```bash -graphify extract ./core/ # → ./core/graphify-out/graph.json -graphify extract ./service/ # → ./service/graphify-out/graph.json -graphify extract ./platform/ # → ./platform/graphify-out/graph.json -# Add --backend gemini|kimi|openai|deepseek|claude-cli depending on which API key you have set - -# Then merge at the project root: -graphify merge-graphs \ - ./core/graphify-out/graph.json \ - ./service/graphify-out/graph.json \ - ./platform/graphify-out/graph.json \ - --out graphify-out/graph.json -``` - -Once `graphify-out/graph.json` exists, the fast path above takes over: any codebase question runs `graphify query` directly on the merged graph — no re-extraction, no size gate. diff --git a/.agents/skills/graphify/references/hooks.md b/.agents/skills/graphify/references/hooks.md deleted file mode 100644 index 3fb74d1545..0000000000 --- a/.agents/skills/graphify/references/hooks.md +++ /dev/null @@ -1,33 +0,0 @@ -# graphify reference: commit hook and native AGENTS.md integration - -Load this when the user asked to install the post-commit hook or wire graphify into a project's AGENTS.md. - -## For git commit hook - -Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor. - -```bash -graphify hook install # install -graphify hook uninstall # remove -graphify hook status # check -``` - -After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those. - -If a post-commit hook already exists, graphify appends to it rather than replacing it. - ---- - -## For native AGENTS.md integration - -Run once per project to make graphify always-on in your agent sessions: - -```bash -graphify agents install -``` - -This writes a `## graphify` section to the local `AGENTS.md` that instructs your agent to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions. - -```bash -graphify agents uninstall # remove the section -``` diff --git a/.agents/skills/graphify/references/query.md b/.agents/skills/graphify/references/query.md deleted file mode 100644 index 4c3a6ccd56..0000000000 --- a/.agents/skills/graphify/references/query.md +++ /dev/null @@ -1,346 +0,0 @@ -# graphify reference: query, path, explain - -Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise. - -Before any query command, use a non-shell file-writing tool to create -`graphify-out/.graphify_query_args.json`. Keep every user- or model-controlled -string in this JSON file, never in shell or Python source: - -```json -{"original_question":"","expanded_question":"","mode":"bfs","budget":2000,"node_a":"","node_b":"","node_name":"","save_question":"","answer":"","result_type":"query","nodes":[],"outcome":"useful","correction":""} -``` - -Two traversal modes - choose based on the question: - -| Mode | Flag | Best for | -|------|------|----------| -| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first | -| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path | - -First check the graph exists: -```bash -$(cat graphify-out/.graphify_python) -c " -from pathlib import Path -if not Path('graphify-out/graph.json').exists(): - print('ERROR: No graph found. Run /graphify first to build the graph.') - raise SystemExit(1) -" -``` -If it fails, stop and tell the user to run `/graphify ` first. - -### Step 0 — Constrained query expansion (REQUIRED before traversal) - -graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise. - -Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first: - -1. Extract the token vocabulary from node labels: -```bash -$(cat graphify-out/.graphify_python) -c " -import json, re -from pathlib import Path -data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8')) -vocab = set() -for n in data['nodes']: - for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE): - parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c] - for p in parts: - t = p.lower() - if 3 <= len(t) <= 30: - vocab.add(t) -Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)), encoding='utf-8') -print(f'vocab: {len(vocab)} tokens') -" -``` - -2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints: - - You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens. - - If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory. - - If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search. - - Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab. - - Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present. - -3. Print the selection explicitly to the user before running the query, so the expansion is auditable: -``` -Query expanded to (from graph vocab, N tokens): [token1, token2, ...] -``` -If the list is empty, say so plainly and stop — do not proceed to traversal. - -### Step 1 — Traversal - -Build the **expanded query string** by joining the selected tokens with spaces and write it to `expanded_question` in the JSON argument file. Preserve the verbatim question in `original_question` for `save-result`. - -Prefer the CLI when it is installed: -```bash -$(cat graphify-out/.graphify_python) - <<'PY' -import json, subprocess -from pathlib import Path -args = json.loads(Path('graphify-out/.graphify_query_args.json').read_text(encoding='utf-8')) -cmd = ['graphify', 'query', args['expanded_question'], '--budget', str(int(args.get('budget', 2000)))] -if args.get('mode') == 'dfs': - cmd.append('--dfs') -subprocess.run(cmd, check=True) -PY -``` - -If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline: - -1. Find the 1-3 nodes whose label best matches the expanded tokens. -2. Run the appropriate traversal from each starting node. -3. Read the subgraph - node labels, edge relations, confidence tags, source locations. -4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact. -5. If the graph lacks enough information, say so - do not hallucinate edges. - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from networkx.readwrite import json_graph -import networkx as nx -from pathlib import Path - -data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8')) -G = json_graph.node_link_graph(data, edges='links') - -args = json.loads(Path('graphify-out/.graphify_query_args.json').read_text(encoding='utf-8')) -question = args['expanded_question'] -mode = args.get('mode', 'bfs') -terms = [t.lower() for t in question.split() if len(t) >= 3] # match the vocab threshold; keeps api/jwt/ios (#1392) - -# Find best-matching start nodes -scored = [] -for nid, ndata in G.nodes(data=True): - label = ndata.get('label', '').lower() - score = sum(1 for t in terms if t in label) - if score > 0: - scored.append((score, nid)) -scored.sort(reverse=True) -start_nodes = [nid for _, nid in scored[:3]] - -if not start_nodes: - print('No matching nodes found for query terms:', terms) - sys.exit(0) - -subgraph_nodes = set() -subgraph_edges = [] - -if mode == 'dfs': - # DFS: follow one path as deep as possible before backtracking. - # Depth-limited to 6 to avoid traversing the whole graph. - visited = set() - stack = [(n, 0) for n in reversed(start_nodes)] - while stack: - node, depth = stack.pop() - if node in visited or depth > 6: - continue - visited.add(node) - subgraph_nodes.add(node) - for neighbor in G.neighbors(node): - if neighbor not in visited: - stack.append((neighbor, depth + 1)) - subgraph_edges.append((node, neighbor)) -else: - # BFS: explore all neighbors layer by layer up to depth 3. - frontier = set(start_nodes) - subgraph_nodes = set(start_nodes) - for _ in range(3): - next_frontier = set() - for n in frontier: - for neighbor in G.neighbors(n): - if neighbor not in subgraph_nodes: - next_frontier.add(neighbor) - subgraph_edges.append((n, neighbor)) - subgraph_nodes.update(next_frontier) - frontier = next_frontier - -# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token) -token_budget = int(args.get('budget', 2000)) -char_budget = token_budget * 4 - -# Score each node by term overlap for ranked output -def relevance(nid): - label = G.nodes[nid].get('label', '').lower() - return sum(1 for t in terms if t in label) - -ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True) - -lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes'] -for nid in ranked_nodes: - d = G.nodes[nid] - lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]') -for u, v in subgraph_edges: - if u in subgraph_nodes and v in subgraph_nodes: - _raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw - lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}') - -output = '\n'.join(lines) -if len(output) > char_budget: - output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)' -print(output) -" -``` - -Then answer based on the subgraph output above, using only what the graph contains. - -After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node: - -```bash -$(cat graphify-out/.graphify_python) - <<'PY' -import json, subprocess, sys -from pathlib import Path -args = json.loads(Path('graphify-out/.graphify_query_args.json').read_text(encoding='utf-8')) -cmd = [sys.executable, '-m', 'graphify', 'save-result', - '--question', args['save_question'], '--answer', args['answer'], - '--type', args['result_type'], '--nodes', *args.get('nodes', []), - '--outcome', args.get('outcome', 'useful')] -if args.get('correction'): - cmd.extend(['--correction', args['correction']]) -subprocess.run(cmd, check=True) -PY -``` - -Set `save_question`, `answer`, `result_type`, and `nodes` in the JSON argument file first. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph. - -**Work memory (self-improving loop).** Add an `--outcome` so future sessions learn from this one — append `--outcome useful|dead_end|corrected` to the `save-result` command (and `--correction "the right answer"` when correcting): - -- `useful` — the cited nodes answered the question well (they become *preferred sources*). -- `dead_end` — the question/path led nowhere; don't re-derive it next time. -- `corrected` — the saved answer was wrong; `--correction` records what was right. - -At the **start** of graph work, refresh and read the lessons: run `graphify reflect --if-stale` (cheap, deterministic, no LLM; `--if-stale` makes it a no-op when `LESSONS.md` is already newer than every input, e.g. when the git hook just refreshed it), then read `graphify-out/reflections/LESSONS.md`. It lists **preferred sources** (start there), **known dead ends** (skip them), and prior **corrections**. Running `reflect` yourself keeps the lessons current even without the git hook installed; if the post-commit hook *is* installed, `--if-stale` means your session-start run costs almost nothing. - ---- - -## For /graphify path - -Find the shortest path between two named concepts in the graph. Prefer the CLI when installed: - -```bash -$(cat graphify-out/.graphify_python) - <<'PY' -import json, subprocess -from pathlib import Path -args = json.loads(Path('graphify-out/.graphify_query_args.json').read_text(encoding='utf-8')) -subprocess.run(['graphify', 'path', args['node_a'], args['node_b']], check=True) -PY -``` - -If the CLI is unavailable, run it inline: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json, sys -import networkx as nx -from networkx.readwrite import json_graph -from pathlib import Path - -data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8')) -G = json_graph.node_link_graph(data, edges='links') - -args = json.loads(Path('graphify-out/.graphify_query_args.json').read_text(encoding='utf-8')) -a_term = args['node_a'] -b_term = args['node_b'] - -def find_node(term): - term = term.lower() - scored = sorted( - [(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n) - for n in G.nodes()], - reverse=True - ) - return scored[0][1] if scored and scored[0][0] > 0 else None - -src = find_node(a_term) -tgt = find_node(b_term) - -if not src or not tgt: - print(f'Could not find nodes matching: {a_term!r} or {b_term!r}') - sys.exit(0) - -try: - path = nx.shortest_path(G, src, tgt) - print(f'Shortest path ({len(path)-1} hops):') - for i, nid in enumerate(path): - label = G.nodes[nid].get('label', nid) - if i < len(path) - 1: - _raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw - rel = edge.get('relation', '') - conf = edge.get('confidence', '') - print(f' {label} --{rel}--> [{conf}]') - else: - print(f' {label}') -except nx.NetworkXNoPath: - print(f'No path found between {a_term!r} and {b_term!r}') -except nx.NodeNotFound as e: - print(f'Node not found: {e}') -" -``` - -Then explain the path in plain language - what each hop means, why it's significant. - -After writing the explanation, save it back: - -Set `save_question`, `answer`, `result_type` (`path_query`), and `nodes` in the JSON argument file, then use the safe `save-result` block above. - ---- - -## For /graphify explain - -Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed: - -```bash -$(cat graphify-out/.graphify_python) - <<'PY' -import json, subprocess -from pathlib import Path -args = json.loads(Path('graphify-out/.graphify_query_args.json').read_text(encoding='utf-8')) -subprocess.run(['graphify', 'explain', args['node_name']], check=True) -PY -``` - -If the CLI is unavailable, run it inline: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json, sys -import networkx as nx -from networkx.readwrite import json_graph -from pathlib import Path - -data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8')) -G = json_graph.node_link_graph(data, edges='links') - -args = json.loads(Path('graphify-out/.graphify_query_args.json').read_text(encoding='utf-8')) -term = args['node_name'] -term_lower = term.lower() - -# Find best matching node -scored = sorted( - [(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n) - for n in G.nodes()], - reverse=True -) -if not scored or scored[0][0] == 0: - print(f'No node matching {term!r}') - sys.exit(0) - -nid = scored[0][1] -data_n = G.nodes[nid] -print(f'NODE: {data_n.get(\"label\", nid)}') -print(f' source: {data_n.get(\"source_file\",\"unknown\")}') -print(f' type: {data_n.get(\"file_type\",\"unknown\")}') -print(f' degree: {G.degree(nid)}') -print() -print('CONNECTIONS:') -for neighbor in G.neighbors(nid): - _raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw - nlabel = G.nodes[neighbor].get('label', neighbor) - rel = edge.get('relation', '') - conf = edge.get('confidence', '') - src_file = G.nodes[neighbor].get('source_file', '') - print(f' --{rel}--> {nlabel} [{conf}] ({src_file})') -" -``` - -Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations. - -After writing the explanation, save it back: - -Set `save_question`, `answer`, `result_type` (`explain`), and `nodes` in the JSON argument file, then use the safe `save-result` block above. diff --git a/.agents/skills/graphify/references/transcribe.md b/.agents/skills/graphify/references/transcribe.md deleted file mode 100644 index b967f83799..0000000000 --- a/.agents/skills/graphify/references/transcribe.md +++ /dev/null @@ -1,52 +0,0 @@ -# graphify reference: transcribe video and audio - -Load this only when `detect` reported one or more `video` files. A corpus with no video never reads this. - -### Step 2.5 - Transcribe video / audio files (only if video files detected) - -Skip this step entirely if `detect` returned zero `video` files. - -Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3. - -**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed. - -**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."` - -**Step 1 - Write the Whisper prompt yourself.** - -Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example: - -- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."` -- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."` - -**Export** it as `GRAPHIFY_WHISPER_PROMPT` (the exact name the transcriber reads — and it must be `export`ed so the child Python process sees it) for the next command. - -**Step 2 - Transcribe:** - -```bash -export GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed (must be exported) -export GRAPHIFY_WHISPER_PROMPT="" -$(cat graphify-out/.graphify_python) -c " -import json, os, sys -from pathlib import Path -from graphify.transcribe import transcribe_all - -detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\")) -video_files = detect.get('files', {}).get('video', []) -prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.') - -transcript_paths = transcribe_all(video_files, initial_prompt=prompt) -# Write the JSON from Python (NOT a shell '>' redirect): transcribe_all/Whisper -# print progress to stdout, which would otherwise corrupt the JSON file (#1392). -Path('graphify-out/.graphify_transcripts.json').write_text(json.dumps(transcript_paths, ensure_ascii=False), encoding=\"utf-8\") -print(f'Transcribed {len(transcript_paths)} file(s)', file=sys.stderr) -" -``` - -After transcription: -- Read the transcript paths from `graphify-out/.graphify_transcripts.json` -- Add them to the docs list before dispatching semantic subagents in Step 3B -- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs` -- If transcription fails for a file, print a warning and continue with the rest - -**Whisper model:** Default is `base`. If the user passed `--whisper-model `, `export GRAPHIFY_WHISPER_MODEL=` (it must be exported, not just assigned) before running the command above. diff --git a/.agents/skills/graphify/references/update.md b/.agents/skills/graphify/references/update.md deleted file mode 100644 index 3632fd4126..0000000000 --- a/.agents/skills/graphify/references/update.md +++ /dev/null @@ -1,210 +0,0 @@ -# graphify reference: incremental update and cluster-only - -Load this only when the user passed `--update` or `--cluster-only`. A first-time full build never reads this file. - -## For --update (incremental re-extraction) - -Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time. - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.detect import detect_incremental, save_manifest -from pathlib import Path - -result = detect_incremental(Path('INPUT_PATH')) -new_total = result.get('new_total', 0) -print(json.dumps(result, indent=2, ensure_ascii=False)) -Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\") -deleted = list(result.get('deleted_files', [])) -if new_total == 0 and not deleted: - print('No files changed since last run. Nothing to update.') - raise SystemExit(0) -if deleted: - print(f'{len(deleted)} deleted file(s) to prune.') -if new_total > 0: - print(f'{new_total} new/changed file(s) to re-extract.') -" -``` - -Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path -r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\")) -Path('graphify-out/.graphify_detect.json').write_text(json.dumps({ - 'files': r.get('new_files', {}), - 'all_files': r.get('files', {}), - 'total_files': r.get('new_total', 0), - 'total_words': r.get('total_words', 0), - 'skipped_sensitive': r.get('skipped_sensitive', []), - 'needs_graph': True, -}, ensure_ascii=False), encoding=\"utf-8\") -" -``` - -If new files exist, first check whether all changed files are code files: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path - -result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {} -code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'} -new_files = result.get('new_files', {}) -all_changed = [f for files in new_files.values() for f in files] -code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed) -print('code_only:', code_only) -" -``` - -If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8. - -If `code_only` is False (any changed file is a doc/paper/image/video): **first, if any changed file is in `new_files['video']`, run `references/transcribe.md` (Step 2.5) on those files, then rewrite `.graphify_detect.json` to move the resulting transcript paths into `files['document']` and drop `files['video']`** — otherwise raw `.mp4/.mp3` paths are fed to semantic subagents as unreadable media (#1392). Then run the full Steps 3A–3C pipeline as normal. - - -If no new files exist (only deletions), create an empty extraction so the merge step can prune: - -```bash -if [ ! -f graphify-out/.graphify_extract.json ]; then - echo '[graphify update] Only deletions -- creating empty extraction for merge.' - $(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path -Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8') -" -fi -``` - - -Then: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path -from graphify.build import build_merge -from graphify.detect import save_manifest - -# Load new extraction and incremental state -new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\")) -incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\")) -deleted = list(incremental.get('deleted_files', [])) -# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are -# handled by build_merge's replace-on-re-extract (#1344): every source_file in -# new_chunks is dropped from the base before merge, so old/stale nodes don't survive. -# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base -# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot -# now that replace — not the dedup pass — reconciles changed files). -prune = list(deleted) or None - -# Use build_merge() — reads graph.json directly without NetworkX round-trip -# so edge direction (calls, implements, imports) is always preserved (#801). -# Pass root= so prune_sources (absolute paths from detect_incremental) are -# relativized to match the graph's relative source_file values; without it -# nothing is pruned and stale nodes accumulate on every update (#1361). -# directed=IS_DIRECTED: replace IS_DIRECTED with True if --directed was given, else -# False. Without it a --directed --update silently rebuilds undirected and collapses -# reciprocal A<->B edges (#1392). -G = build_merge( - [new_extraction], - graph_path='graphify-out/graph.json', - prune_sources=prune, - root='INPUT_PATH', - directed=IS_DIRECTED, -) -print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges') - -# Write merged result back to .graphify_extract.json so Step 4 sees the full graph -merged_out = { - 'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)], - 'edges': [ - # Explicit source/target last so they win over any stale attrs in d. - {**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')}, - 'source': d.get('_src', u), 'target': d.get('_tgt', v)} - for u, v, d in G.edges(data=True) - ], - # G.graph["hyperedges"] holds hyperedges from both existing graph.json - # and new_extraction (build_merge combines them). Falling back to - # new_extraction only would silently drop prior-run hyperedges (#801). - 'hyperedges': list(G.graph.get('hyperedges', [])), - 'input_tokens': new_extraction.get('input_tokens', 0), - 'output_tokens': new_extraction.get('output_tokens', 0), -} -Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\") -print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)') - -# Save manifest so next --update diffs against today's state, not the -# prior run's baseline (prevents ghost-node reports on subsequent updates). -# root= matches the build_merge call above so the manifest keys stay relative to -# the scan root — portable across clones/machines, so --update keeps matching -# cached files instead of missing every one after a move (#1417). -# -# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output -# THIS run (new_extraction is this run's fresh extraction, read above before the -# merge overwrote the file): a changed doc whose chunk failed must stay unstamped -# so the next --update re-queues it, otherwise it is marked done and its content -# is lost forever (#2015). Mirrors the library extract path -# (cli._stamped_manifest_files + clear_semantic + scan_corpus). -from graphify.cli import _stamped_manifest_files -_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH')) -# Changed semantic files dispatched this run but NOT stamped had their chunk fail -# or be omitted; clear any stale semantic_hash so they are re-queued (#1948). -_sem_types = ('document', 'paper', 'image') -_dispatched = {f for t, fl in incremental.get('new_files', {}).items() if t in _sem_types for f in fl} -_stamped = {f for fl in _manifest_files.values() for f in fl} -_cleared = _dispatched - _stamped -# scan_corpus = the RAW full corpus so in-root files newly excluded since last run -# are dropped rather than masquerading as deletions; untouched rows preserved (#1908). -_scan = {f for fl in incremental['files'].values() for f in fl} -save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None) -print('[graphify update] Manifest saved.') -" -``` - -Then run Steps 4–8 on the merged graph as normal. - -After Step 4, show the graph diff: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from graphify.analyze import graph_diff -from graphify.build import build_from_json -from networkx.readwrite import json_graph -import networkx as nx -from pathlib import Path - -# Load old graph (before update) from backup written before merge -old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None -new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\")) -G_new = build_from_json(new_extract, directed=IS_DIRECTED) - -if old_data: - G_old = json_graph.node_link_graph(old_data, edges='links') - diff = graph_diff(G_old, G_new) - print(diff['summary']) - if diff['new_nodes']: - print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5])) - if diff['new_edges']: - print('New edges:', len(diff['new_edges'])) -" -``` - -Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json` -Clean up after: `rm -f graphify-out/.graphify_old.json` - ---- - -## For --cluster-only - -Skip Steps 1–3. Re-run clustering on the existing graph: - -```bash -graphify cluster-only . -``` - -`graphify cluster-only .` is **self-contained**: it re-clusters, names communities, and regenerates `GRAPH_REPORT.md`, `graph.json`, and `graph.html` from the existing graph. **Do not re-run Steps 5–9** — they read intermediate files (`.graphify_extract.json`, `.graphify_detect.json`, `.graphify_analysis.json`) that a prior build's cleanup (Step 9) already deleted, so they raise `FileNotFoundError` (#1392). When it finishes, present the refreshed `GRAPH_REPORT.md` summary as usual. diff --git a/.agents/skills/threejs-3d-generator/SKILL.md b/.agents/skills/threejs-3d-generator/SKILL.md deleted file mode 100644 index a938101667..0000000000 --- a/.agents/skills/threejs-3d-generator/SKILL.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -name: threejs-3d-generator -description: "Generate, texture, rig, animate, stylize, convert, and download 3D assets for Three.js games using the Tripo API. Use for text-to-3D, image-to-3D, 2D concept to 3D conversion, game-ready GLB/FBX assets, characters, creatures, buildings, props, weapons, terrain pieces, auto-rigging, animation retargeting, model texturing, LEGO/voxel/Minecraft-style stylization, low-poly/quad conversion, and browser asset pipelines. Pair with threejs-image-generator for concepts, texture references, sky/background/terrain textures, logos, icons, and GUI art before image-to-3D generation." ---- - -# Three.js 3D Generator - -## Purpose - -Create production-oriented 3D assets, then prepare them for Three.js games. This is the Three.js game system's 3D-generation layer; it uses Tripo as the provider for text-to-3D, image-to-3D, texturing, rigging, retargeting, stylization, conversion, and downloadable GLB/FBX outputs. - -Resolve `` in the commands below in this order: `~/.claude/skills/threejs-3d-generator`, `~/.codex/skills/threejs-3d-generator`, `~/.agents/skills/threejs-3d-generator`, or repo `skills/threejs-3d-generator`. - -## API Key - -Never store API keys in skill files or client-side game code, and never paste a key value into a report. The script reads `--api-key` or `TRIPO_API_KEY`. - -Step 0, before declaring the key unavailable: run this skill's own probe and paste its literal output into the report. - -```bash -python3 /scripts/threejs_3d_asset.py probe # prints TRIPO_API_KEY=SET|MISSING -``` - -`TRIPO_API_KEY=MISSING` is only a valid skip/blocker reason when this output is shown. Keys defined only in a shell profile can be absent from the process env; if the plain probe prints MISSING unexpectedly, wrap it: `zsh -lc 'source ~/.zprofile 2>/dev/null || true; source ~/.zshrc 2>/dev/null || true; python3 /scripts/threejs_3d_asset.py probe'`. When the director skill is loaded, prefer `threejs-game-director/scripts/probe_asset_credentials.sh`, which probes all three asset keys at once. - -Generated model download URLs expire quickly, so download outputs immediately after successful tasks. - -## Tool Script - -Reference gate: - -- Load `references/api-notes.md` before provider API work, endpoint/task decisions, model-version choices, polling, postprocess, conversion, rigging, animation, or download handling. -- Load `references/threejs-integration.md` before importing Tripo outputs into a browser game or advising GLB/FBX integration. -- Load `references/image-generator-workflows.md` before pairing `threejs-image-generator` with this skill for 2D concepts, texture references, UI art, logos, decals, or image-to-3D inputs. - -Track required references in a reference ledger with yes/no, path, and failure reason. Do not mark an asset pipeline complete while a required reference is skipped. - -Run from the user's current project directory: - -```bash -python3 /scripts/threejs_3d_asset.py --help -``` - -## Common Commands - -Recommended premium game hero model: - -```bash -python3 /scripts/threejs_3d_asset.py text \ - --prompt "game-ready [hero asset], strong readable silhouette, layered hard-surface detail, PBR materials, clean topology for browser game, centered pivot, 3/4 view, no text" \ - --model-version v3.1-20260211 \ - --texture-quality detailed \ - --geometry-quality detailed \ - --wait --download --out-dir assets/models/hero -``` - -Text to 3D: - -```bash -python3 /scripts/threejs_3d_asset.py text \ - --prompt "game-ready sci-fi hover bike, sleek armored panels, readable silhouette, PBR, front facing" \ - --model-version v3.1-20260211 \ - --texture-quality detailed \ - --geometry-quality detailed \ - --wait --download --out-dir assets/models/hover-bike -``` - -Image to 3D from a local `threejs-image-generator` concept: - -```bash -python3 /scripts/threejs_3d_asset.py image \ - --image assets/concepts/hover-bike-front.png \ - --model-version v3.1-20260211 \ - --enable-image-autofix \ - --texture-alignment original_image \ - --texture-quality detailed \ - --wait --download --out-dir assets/models/hover-bike -``` - -Status and download: - -```bash -python3 /scripts/threejs_3d_asset.py status TASK_ID -python3 /scripts/threejs_3d_asset.py download TASK_ID --out-dir assets/models -``` - -Texture, rig, animate, or convert: - -```bash -python3 /scripts/threejs_3d_asset.py postprocess \ - --type texture_model --original-task-id TASK_ID \ - --texture-prompt "brushed gunmetal, orange hazard decals, worn edges" \ - --wait --download --out-dir assets/models/retextured - -python3 /scripts/threejs_3d_asset.py postprocess \ - --type animate_prerigcheck --original-task-id TASK_ID --wait - -# Rig version is routed by --rig-type: biped -> v1.0-20240301 (the v2.x rigger -# fails on humanoids), other body plans -> v2.5-20260210. Only pass -# --model-version to override that routing. -python3 /scripts/threejs_3d_asset.py postprocess \ - --type animate_rig --original-task-id TASK_ID --rig-type biped --spec tripo --wait - -# animate_retarget takes the RIG task ID, not the generation task ID. -# Pass the same --rig-type used for the rig so the version routing matches -# (biped rigs use the legacy path: FBX output, ONE animation per task). -# Non-biped rigs may batch up to 5 presets per task via --animations. -# NEVER pass --animate-in-place: it corrupts the bake (mirrored limbs / exploded -# skinning). Strip root motion in the engine instead. -python3 /scripts/threejs_3d_asset.py postprocess \ - --type animate_retarget --original-task-id RIG_TASK_ID --rig-type quadruped \ - --animations preset:idle,preset:walk,preset:run \ - --wait --download --out-dir assets/models/animated - -python3 /scripts/threejs_3d_asset.py postprocess \ - --type conversion --original-task-id TASK_ID --format GLTF \ - --face-limit 20000 --wait --download --out-dir assets/models/gltf - -python3 /scripts/threejs_3d_asset.py postprocess \ - --type stylize_model --original-task-id TASK_ID --style voxel \ - --wait --download --out-dir assets/models/voxel -``` - -Animated character pipeline (generation -> prerigcheck -> validated rig with retries -> retargets -> downloads). The pipeline routes itself by body plan: biped characters automatically use the v1.0-20240301 anatomical rig with one FBX per animation (plain preset names are mapped onto the preset:biped:* library); creatures use the v2.5-20260210 rig with GLB clips: - -```bash -python3 /scripts/threejs_3d_asset.py character-pipeline \ - --prompt "stylized cyber runner character, T-pose, full body, game-ready outfit, readable silhouette" \ - --animations preset:idle,preset:walk,preset:run,preset:jump \ - --out-dir assets/models/cyber-runner - -# Creature example: stance language matters — generate in the pose the preset expects. -python3 /scripts/threejs_3d_asset.py character-pipeline \ - --prompt "stylized wolf, quadrupedal stance, all four legs planted and separated, full body" \ - --rig-type quadruped --animations preset:quadruped:walk \ - --out-dir assets/models/wolf -``` - -## Three.js Image Generator Pairing - -Use `threejs-image-generator` before 3D generation when the asset benefits from a strong 2D reference: - -- Character concept, full-body T-pose/A-pose, front/side/back variants. -- Building, prop, vehicle, weapon, pickup, enemy, obstacle, or terrain tile reference. -- Style sheet for a whole asset family. -- Texture references: terrain, rock, metal, fabric, decals, skyboxes, backgrounds, UI materials. -- Logos, faction marks, pickup icons, hazard signs, cockpit decals, HUD symbols, and GUI panels. - -Load `references/image-generator-workflows.md` for prompt patterns before generating or editing 2D inputs. - -## Three.js Integration - -Load `references/threejs-integration.md` before importing Tripo outputs into a browser game. In short: - -- Prefer GLB/PBR outputs for Three.js. -- Use `GLTFLoader` for loading. -- Use `AnimationMixer` for rigged/animated GLBs. -- Keep generated model files out of client-side API flows; generation is a tooling step. -- Inspect triangle count, texture count, material count, file size, scale, pivot, bounds, and animation clips. -- Use generated 3D assets as hero/high-fidelity content, then build surrounding prop kits procedurally or with additional `threejs-3d-generator` / `threejs-image-generator` passes. - -## Rigging and Animation Reliability - -Load `references/api-notes.md` for the full parameter tables, retarget mechanics, and the animation prohibitions (the canonical source for all three). The rules that prevent most failures: - -- Generate characters as one fused mesh: keep `--quad` and `--generate-parts` off (`generate_parts` disables texturing; `quad` forces FBX output). -- Require full-body T-pose or A-pose, arms away from body, symmetric, no props fused to the silhouette. Verify the rendered preview is actually in T/A-pose before rigging; regenerate if not. -- Run `animate_prerigcheck` first (it takes no model version) and use the detected `rig_type` for `animate_rig` and preset selection. `riggable=false` means regenerate with a clearer pose, not force-rig. -- `riggable=true` does not guarantee a usable rig. After rigging, validate the skeleton before retargeting: `threejs_3d_asset.py validate-rig rig-model.glb --rig-type biped` (the `character-pipeline` does this automatically). Check both presence AND chain depth: a rig with a 1-bone leg or 2-bone arm warps every clip. -- Auto-rigging is nondeterministic. On validation failure, retry the rig task (~25 credits) before regenerating the model — `character-pipeline --rig-retries N` (default 2) automates this, and `--model-task-id TASK_ID` resumes from an existing generation. Armored/hard-surface characters need the most retries; organic meshes usually rig first try. -- Creatures get exactly one preset (walk/march). For multi-mode creatures (crawl + fly dragons), rig the same model twice — ground rig type for the locomotion preset, `avian` for wing chains — and drive wings procedurally in Three.js or via external clips on a `mixamo`-spec rig. -- Rig version is the main quality lever, and it differs by body plan (measured June 2026). The `character-pipeline` routes this automatically; only override `--rig-model-version` deliberately: - - HUMANOIDS: `v1.0-20240301` (anatomical Mixamo-like skeleton with twist bones + the large `preset:biped:*` clip library: idle, walk, run, slash, jump, dances, ...). The v2.x limb-chain rigger went 0/16 on humanoid meshes — armored or not, T-pose or A-pose — always producing asymmetric chains. - - CREATURES: `v2.5-20260210` (v2.x handles quadruped/avian well: symmetric 5-6 bone chains). -- For v1.0 rigs, retarget with `--model-version default` (omit the version): the retarget enum rejects explicit `v1.0-20240301` (HTTP 400 code 2017) but the server default handles v1.0 rigs. -- v1.0 retargets must use `--out-format fbx` (the script enforces this): Tripo's GLB bake on this path exports twist-bone transforms in the wrong space and limbs collapse into the torso — the FBX of the same task is correct. Load with three.js `FBXLoader` or convert offline. v2.5 creature retargets are fine as GLB. -- Use `--spec tripo` (default) when Tripo presets will be retargeted; `--spec mixamo` rigs cannot be used with Tripo retarget and are only for external animation pipelines. -- `animate_retarget` takes the RIG task ID (not the generation task ID). Batch up to 5 presets per task with `--animations`; batched clips return named `NlaTrack`, `NlaTrack.001`, … in request order — map by index and rename after import. See `references/api-notes.md` for the v1.0-vs-v2.5 batching and out-format rules. -- Only 16 presets exist for v2.5 rigs (no `preset:attack`; use `preset:slash`/`preset:shoot`). Non-biped rig types have a single locomotion preset each; plan extra creature motion procedurally or via external retargeting. -- A creature's MESH STANCE drives how presets read: a quadruped walk on an upright-standing dragon looks like a human walking. Generate creatures in the stance the animation expects (horizontal body, all fours planted) — the pipeline only auto-appends T-pose language for biped rigs. -- After download, run `threejs_3d_asset.py validate-animation clip.glb` (keyframe QA: flags scale tracks, limb-stretching translation tracks, extreme rotations, and reports per-clip duration/channel coverage), then verify motion visually in the engine. -- Never use `--animate-in-place` (verified to corrupt clips: mirrored/crossed limbs on v1.0 rigs, exploded skinning on v2.5 — full detail in `references/api-notes.md`). Keep root motion baked and convert to in-place at import instead; exact engine snippet in `references/threejs-integration.md`. -- After download, inspect `gltf.animations` clip names and counts before wiring the `AnimationMixer`. - -## Quality Rules - -- Improve the user's prompt with material, silhouette, camera/readability, scale, and game-use constraints. -- For riggable characters, include full-body T-pose or A-pose in the prompt or create a T-pose reference image first. -- For Three.js games, request GLB/PBR, reasonable face limits, and texture quality matched to the performance budget. -- For mobile/browser games, favor `smart_low_poly`, `face_limit`, later conversion, or low-poly postprocess when the asset is too expensive. -- Always download output URLs immediately after success. -- Report the credential probe output, reference ledger, task IDs, output paths, model version, texture/geometry settings, animations, conversion settings, Three.js import notes, and any missing/failed steps. diff --git a/.agents/skills/threejs-3d-generator/agents/openai.yaml b/.agents/skills/threejs-3d-generator/agents/openai.yaml deleted file mode 100644 index 3310b7eb39..0000000000 --- a/.agents/skills/threejs-3d-generator/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Three.js 3D Generator" - short_description: "Generate, texture, rig, animate, and convert Three.js game assets" - default_prompt: "Load threejs-3d-generator/SKILL.md (try ~/.codex/skills/threejs-3d-generator/SKILL.md, then ~/.claude/skills, ~/.agents/skills, or repo skills/) and follow it exactly, including its reference gates. Non-negotiables: run the probe before declaring the key unavailable; load api-notes before provider calls; use threejs-image-generator first when a 2D concept/reference would improve the result; download outputs immediately; report task IDs, file paths, and Three.js import notes." diff --git a/.agents/skills/threejs-3d-generator/references/api-notes.md b/.agents/skills/threejs-3d-generator/references/api-notes.md deleted file mode 100644 index 87755f8789..0000000000 --- a/.agents/skills/threejs-3d-generator/references/api-notes.md +++ /dev/null @@ -1,146 +0,0 @@ -# Tripo API Notes - -These notes summarize the official Tripo OpenAPI docs used by this skill. - -## Base API - -- Base URL: `https://api.tripo3d.ai/v2/openapi` -- Auth: `Authorization: Bearer ` -- Task create: `POST /task` -- Task query: `GET /task/:task_id` -- Direct image upload: `POST /upload/sts` with `multipart/form-data` -- STS token upload flow: `POST /upload/sts/token` - -Task responses use `code` and `data`. Treat nonzero `code` as an API error. - -## Task Status - -Ongoing: - -- `queued` -- `running` - -Final: - -- `success` -- `failed` -- `banned` -- `expired` -- `cancelled` -- `unknown` - -Query a task with the same API key that created it. Output download URLs usually expire after a few minutes, so download immediately. - -## Core Task Types - -- `text_to_model`: prompt to model. -- `image_to_model`: uploaded image token or image URL to model. -- `multiview_to_model`: four directional views to model. -- `import_model`: import an uploaded model file. -- `texture_model`: retexture or PBR texture an existing model task. -- `stylize_model`: stylize a model as LEGO, voxel, Voronoi, or Minecraft style when supported. -- `animate_prerigcheck`: check whether a model can be rigged. See "Rigging and Animation". -- `animate_rig`: auto-rig a model. See "Rigging and Animation". -- `animate_retarget`: retarget preset animations onto a rig task. See "Rigging and Animation". -- `conversion`: export/convert model format. -- `mesh_segmentation`: segment model parts. -- `mesh_completion`: complete selected model parts. -- `highpoly_to_lowpoly`: smart low-poly conversion. - -## Rigging and Animation - -Chain: generation task -> `animate_prerigcheck` -> `animate_rig` -> `animate_retarget`. Each step has different task-ID and version semantics; getting them wrong is the main cause of silent rig/animation failures. - -### Source-model requirements - -- Rig/retarget/prerigcheck accept source generation tasks with `model_version` `Turbo-v1.0-20250506` or `v2.0-20240919` and newer. 1.x generation tasks are not supported. `v3.1-20260211` works. -- Generate characters as one fused mesh. `generate_parts` is incompatible with `texture=true`/`pbr=true` and with `quad=true`, so a parts-segmented character cannot be textured and does not fit the rig pipeline. -- Avoid `quad=true` for characters bound for GLB: quad forces FBX output and defaults `face_limit` to 10000 when unset. - -### `animate_prerigcheck` - -- Request takes only `type` and `original_model_task_id`. There is no `model_version` parameter. -- Output: `riggable` (bool) plus detected `rig_type` (`biped`, `quadruped`, `hexapod`, `octopod`, `avian`, `serpentine`, `aquatic`). -- Use the detected `rig_type` to choose the `animate_rig` rig type and compatible presets. -- Official docs note `riggable=false` "doesn't necessarily mean it cannot be rigged". Treat false as a strong warning: the best response is to regenerate with a clearer full-body T-pose, not to force the rig. - -### `animate_rig` - -Version choice is THE quality lever, and the right answer differs by body plan (measured June 2026): - -- HUMANOIDS: use `model_version=v1.0-20240301`. It produces a proper anatomical skeleton (Hip, Pelvis, Spine01/02, Head, L_/R_ Clavicle/Upperarm/Forearm/Hand/Thigh/Calf/Foot/ToeBase plus twist bones) and unlocks the large `preset:biped:*` clip library. The v2.x "Limb chain" rigger went 0/16 on humanoid test meshes (plate armor, fitted armor, T-pose, A-pose — always asymmetric chains like a 9-bone arm vs 4, or a 1-bone leg), while v1.0 produced a clean symmetric skeleton first try with 39-40 channel clips. -- CREATURES (quadruped/hexapod/octopod/avian/serpentine/aquatic): use `model_version=v2.5-20260210`. The v2.x limb-chain rigger handles creatures well (symmetric 5-6 bone chains observed on quadruped and avian dragons). -- `original_model_task_id`: the generation task ID. -- `rig_type`: defaults to `biped`. Pass the prerigcheck-detected type for creatures. -- `spec`: `tripo` (default) or `mixamo`. Only `spec=tripo` rigs can be used with Tripo `animate_retarget`. Choose `mixamo` only when retargeting external animation libraries (Mixamo/custom clips) outside Tripo. -- `out_format`: `glb` (default) or `fbx`. - -### Rig validation gate (mandatory before retargeting) - -`riggable=true` from prerigcheck does NOT guarantee a usable rig. Auto-rigging can silently produce a degenerate skeleton (observed in practice: a biped rig with only 9 bones — Root, Spine_0-2, and one arm; no legs, no right arm, no head). Every retarget on such a rig inherits the damage: clips contain channels only for the mapped bones and the character stays frozen in bind pose at runtime. - -After downloading the rig GLB and before spending retarget credits, validate the skeleton: - -```bash -python3 .../threejs_3d_asset.py validate-rig path/to/rig-model.glb --rig-type biped -``` - -A structurally valid rig has both `_Left_Limb_` and `_Right_Limb_` chains with matching chain depths per limb row (±1 bone is normal variance; healthy rigs are 5/5, 6/6, or 6/5 — broken ones are 9/4, 2/4, or 4/1, and a 1-bone leg cannot bend a knee, warping every clip), at least 3 bones per limb chain for biped/quadruped, two limb rows (`0_` arms, `1_` legs), and a plausible bone count. v1.0 rigs use anatomical names instead (validated as L_/R_ pairs: Clavicle, Upperarm, Forearm, Hand, Thigh, Calf, Foot). The `character-pipeline` command runs this check automatically; `validate-rig` runs it standalone, and `validate-animation` QAs the retargeted clips (scale tracks, limb-stretch translations, durations, channel coverage). - -Auto-rigging is NONDETERMINISTIC: the same model can produce a degenerate skeleton on one attempt and a healthy one on the next. When validation fails, retry the rig task first (~25 credits) before regenerating the model (~30+ credits); `character-pipeline --rig-retries N` does this automatically (default 2). Hard-surface armored characters (plate knights, mechs) fail rig validation far more often than organic meshes — budget several retries or prefer visible-anatomy designs. If retries keep failing, regenerate the base model with clearer limb separation — strict T-pose, arms horizontal, legs apart and fully visible, no long skirt/tabard/cape/props fusing limbs into the body silhouette. Use `character-pipeline --model-task-id TASK_ID` to resume from an existing generation without paying for regeneration. - -### `animate_retarget` - -- `original_model_task_id`: the RIG task ID, not the original generation task ID. -- For v2.5 rigs, pass `model_version: v2.5-20260210`. For v1.0 rigs, OMIT model_version entirely (the CLI accepts `--model-version default`): the retarget enum rejects an explicit `v1.0-20240301` with HTTP 400 `code: 2017` "The version value is invalid", but the server default retargets v1.0 rigs correctly. -- Exactly one of `animation` (single preset string) or `animations` (array, max length 5) is required. Batch clips into one task instead of one task per clip; it is faster and cheaper. -- `out_format`: `glb` (default) or `fbx`. `bake_animation`: default true, glb only. `export_with_geometry`: default true. -- v1.0 RIGS: ONE ANIMATION PER RETARGET TASK. Batching via `animations` makes the FBX contain one armature object per clip (`Armature.001`, `.002`, …) with name-colliding bones; engines bind takes to the wrong skeleton and the body pitches sideways/prone. Submit one task per preset (10 credits each — batching saves nothing). -- v1.0 RIGS MUST RETARGET WITH `out_format=fbx`. Root cause (verified June 2026): Tripo's animation pipeline is FBX-native (their own tutorials are FBX end-to-end and never use GLB for animation). The GLB bake of v1.0 retargets exports twist-bone transforms in the wrong space — and the limb mesh is skinned almost entirely to twist bones, so arms/legs collapse into the torso in every engine (reproduced identically in three.js and Babylon; the FBX of the same task is correct, with real clip names like `walk_normal_m_remap` instead of `NlaTrack`). Load FBX with three.js `FBXLoader`, or convert FBX→GLB offline (Blender / FBX2glTF). v2.5 creature-rig retargets export GLB correctly. -- NEVER set `animate_in_place=true`. Verified June 2026: it corrupts the baked clips — on v1.0 rigs limbs mirror/cross sides (arms fold into the chest, legs cross the midline, "twisted opposite directions"), on v2.5 rigs skinned regions explode into shards. Keep root motion baked and strip the root translation track in the engine instead (see `threejs-integration.md`). Forward-kinematics fingerprint of the corruption: in a walk clip, both hands sit on the same side of the hip instead of mirrored sides. -- Set quality expectations honestly: Tripo's own blog describes auto-rigging as "80-90% of the way there" with shoulders, hips, and fingers needing the most manual refinement. For hero characters, plan a manual pass (or a Mixamo pipeline via `spec=mixamo` + their FBX clips). -- A batched task returns one GLB containing all requested clips, named `NlaTrack`, `NlaTrack.001`, … in request order. Map clips by index, not name. -- Observed credits (June 2026): retarget costs ~10 credits per animation whether batched or separate (batch of 4 = 40); prerigcheck is free (0 credits); rig ~25; text_to_model with detailed texture ~30. Batching saves task count, not credits. Failed rig tasks consume 0 credits, but rig retries on success do — budget ~25 credits per retry when planning character work. -- Out-of-credit error: HTTP 403 with `code: 2010` ("You don't have enough credit"). Surface this to the user as a purchase/top-up blocker; do not retry. - -### Preset catalog (v2.5-20260210 / v2.0-20250506 rigs) - -This is the complete documented list. There is no `preset:attack`; the attack-like presets are `preset:slash` and `preset:shoot`. - -- Biped (11): `preset:idle`, `preset:walk`, `preset:run`, `preset:dive`, `preset:climb`, `preset:jump`, `preset:slash`, `preset:shoot`, `preset:hurt`, `preset:fall`, `preset:turn`. -- Quadruped: `preset:quadruped:walk`. Hexapod: `preset:hexapod:walk`. Octopod: `preset:octopod:walk`. Serpentine: `preset:serpentine:march`. Aquatic: `preset:aquatic:march`. -- Avian: no documented preset for v2.5 rigs. -- The large legacy `preset:biped:*` library (~100 clips: dance variants, etc.) only works with `v1.0-20240301` rigs (biped only). Tradeoff: current-quality v2.5 rig with 16 presets vs legacy v1.0 rig with the big biped clip library. - -Non-biped coverage is one locomotion clip per rig type — there is NO fly, crawl-variant, attack, idle, or hurt preset for creatures. Plan multi-mode creatures (e.g. a dragon that crawls AND flies) as: - -- Ground locomotion: rig the creature's ground rig type (e.g. quadruped) and retarget its walk preset. -- Flight/secondary modes: rig the SAME model task again with `rig_type=avian` (a second ~25-credit rig task on one model is allowed) to get wing limb chains, then drive wing bones procedurally in the engine (sinusoidal flap on the wing chain) or retarget external clips via `spec=mixamo`. -- Per-mode rigs are separate GLBs of the same mesh; swap or crossfade them at the engine level by game state. - -### Riggable-character generation recipe - -- Prompt or reference image: full-body T-pose or A-pose, arms away from body, legs separated, front-facing, symmetric, no props fused into the silhouette, whole body in frame. -- The body must be anatomically complete, including a head. Over-constraining a prompt ("no cape, no shield, slim silhouette") can yield an empty/headless armor shell; the rig task then fails outright (`status: failed`, `error_code: 1001`, no credits consumed). Check the rendered preview for a complete head-to-feet body before rigging. -- Keep `texture`/`pbr` on, `quad` off, `generate_parts` off, and a sane `face_limit`. -- Before rigging, check `rendered_image` actually shows a T/A-pose. If not, regenerate with a stronger pose instruction or a `threejs-image-generator` T-pose reference image instead of rigging a bad pose. -- For non-biped creatures, expect only the single locomotion preset for that rig type; plan extra animations via external retargeting (`spec=mixamo`) or procedural motion in Three.js. - -## Common Output Fields - -- `model`: model download URL. -- `base_model`: untextured/base model URL. -- `pbr_model`: PBR model URL. -- `rendered_image`: preview image URL. -- `generated_image`: generated image URL. -- `generate_multiview_image`: front/left/back/right view URLs. - -## Game Defaults - -- Prefer H3 text/image-to-model: `v3.1-20260211` when quality matters. -- Prefer GLB/PBR for Three.js runtime imports. -- Use `texture_quality=detailed` for high-value hero assets; use `standard` for background assets. -- Use `geometry_quality=detailed` only when the asset needs it and budget allows. -- Use `face_limit`, `smart_low_poly`, conversion, or low-poly postprocess for browser/mobile budgets. -- Use T-pose/A-pose references for rigged characters; keep `quad` and `generate_parts` off for anything that will be rigged. -- Rig/retarget version routing: the CLI routes by `--rig-type` (biped -> `v1.0-20240301`, creatures -> `v2.5-20260210`; v1.0 retargets omit `model_version` because the enum rejects it). Pass `--rig-type` on standalone `postprocess` calls so the routing is correct; only pin `--model-version` to override. Raw API callers must pin explicitly — the server's unpinned defaults are legacy versions. diff --git a/.agents/skills/threejs-3d-generator/references/image-generator-workflows.md b/.agents/skills/threejs-3d-generator/references/image-generator-workflows.md deleted file mode 100644 index 37aef600f3..0000000000 --- a/.agents/skills/threejs-3d-generator/references/image-generator-workflows.md +++ /dev/null @@ -1,55 +0,0 @@ -# Three.js Image Generator Pairing - -Use `threejs-image-generator` when a strong 2D input improves `threejs-3d-generator` output or when the final asset is 2D rather than 3D. The current image provider is Google's Gemini image API. - -## 2D To 3D Reference Images - -Generate clean reference images before image-to-3D for: - -- Characters: full-body T-pose or A-pose, neutral expression, visible hands/feet, no cropped limbs. -- Creatures: side/front silhouettes, clear limb count, readable anatomy. -- Vehicles: front/side/three-quarter concepts, clear wheels/thrusters/wings, material zones. -- Buildings: front elevation, roof silhouette, doors/windows, scale cues. -- Weapons/tools: side view, readable handle/blade/barrel proportions, material callouts. -- Props/pickups: centered object, plain background, strong silhouette, no text baked in unless wanted. -- Terrain/world modules: tileable rocks, cliffs, rails, gates, arena pieces, modular set dressing. - -For the actual prompt wording (image-to-3D reference, riggable character/creature, texture/material, logo/icon/UI, sky/background), use the templates in `threejs-image-generator`'s SKILL.md under "Prompt Patterns" — that skill is the canonical source. The notes here cover only how those references pair into the 3D pipeline. - -## Texture And Material References - -Use `threejs-image-generator` for: - -- Terrain albedo references: rock, sand, mud, snow, moss, cracked asphalt. -- Sci-fi trim sheets, panel lines, decals, hazard stripes, window bands. -- Metal, leather, fabric, glass, ceramic, wood, painted plastic, worn armor. -- Sky, clouds, nebula, city haze, horizon plates, menu backgrounds. -- Faction marks, logos, numbers, signs, pickup icons, hazard labels. - -## UI And Logo Use Cases - -Use `threejs-image-generator` directly, not 3D generation, for: - -- Logos and faction marks. -- HUD icons, item icons, ability icons, pickup symbols. -- Menu backgrounds and loading illustrations. -- Button/icon textures, decals, title art, achievement badges. -- 2D sky/backdrop cards when a 3D model is unnecessary. - -## 3D Generator Handoff - -After generating a 2D reference: - -1. Save the image in the working project, usually `assets/concepts/`. -2. Use the `threejs-3d-generator` `image` command with `--image `. -3. Use `--enable-image-autofix` for rough images. -4. Use `--texture-alignment original_image` when visual match matters. -5. Use `--texture-alignment geometry` when structural accuracy matters. -6. Download generated 3D outputs immediately after success. - -## Avoid - -- Crowded scene images for single-object 3D generation. -- Cropped limbs, hidden backs, extreme perspective, motion blur, or heavy depth of field. -- Tiny UI/logo text in 3D model textures unless text fidelity is noncritical. -- Using 3D generation for pure 2D UI assets. diff --git a/.agents/skills/threejs-3d-generator/references/threejs-integration.md b/.agents/skills/threejs-3d-generator/references/threejs-integration.md deleted file mode 100644 index 38de01122b..0000000000 --- a/.agents/skills/threejs-3d-generator/references/threejs-integration.md +++ /dev/null @@ -1,117 +0,0 @@ -# Three.js Integration - -Use this after `threejs-3d-generator` generates or post-processes a model. - -## Preferred Outputs - -- Three.js runtime: GLB/PBR model first. -- Animation/game-engine interchange: FBX when needed, then convert/import carefully. -- Static web asset exchange: GLTF/GLB. -- 3D print only: STL or 3MF, not for textured game runtime. -- Apple AR: USDZ. - -## Import Pattern - -Use `GLTFLoader`: - -```ts -import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; - -const loader = new GLTFLoader(); -const gltf = await loader.loadAsync('/assets/models/asset/model.glb'); -scene.add(gltf.scene); -``` - -For animation: - -```ts -const mixer = new THREE.AnimationMixer(gltf.scene); -const action = mixer.clipAction(gltf.animations[0]); -action.play(); - -// in loop -mixer.update(deltaSeconds); -``` - -Animation intake notes (the underlying Tripo API behavior and prohibitions — NlaTrack naming, batched-vs-single retarget, `animate_in_place` corruption — are documented canonically in `api-notes.md`; this section is the engine-side fix): - -- A batched retarget returns ONE GLB whose clips are named `NlaTrack`, `NlaTrack.001`, … in request order. The names carry no meaning: map clips to presets by index against the order you requested, rename them after load (`clip.name = 'walk'`), then select by your own names. -- Log `gltf.animations.map(c => `${c.name} ${c.tracks.length} tracks`)` after load. A healthy humanoid clip drives many bones; clips with only a handful of tracks mean the upstream auto-rig was degenerate — fix the rig, not the runtime. -- Do NOT strip or neutralize twist-bone tracks (`UpperarmTwist`, `ForearmTwist`, …) on v1.0 rigs: Tripo skins most of the limb mesh to the twist bones, and their baked values differ greatly from the GLB rest pose — removing the tracks collapses the limbs into the torso. Tripo's slightly open, palm-forward hands are the preset house style, not corruption. -- Never retarget with `animate_in_place=true` (see `api-notes.md` for why it corrupts the bake). Convert to in-place at import instead, and do it precisely: - - Touch ONLY the top root bone's position track (`Root.position`). Tripo FBX clips bake position tracks on EVERY bone with values that differ from FBXLoader's rest transforms; filtering Hip/Pelvis or pattern-matching broadly collapses the skeleton into a hunch. - - Zero the HORIZONTAL components only — keep Y. Vertical root motion IS the animation for jumps (and the bob in gaits); deleting the whole track turns a jump into grounded hand-waving. - -```ts -for (const clip of clips) { - for (const tr of clip.tracks) { - if (tr.name !== 'Root.position') continue; - const v = tr.values, x0 = v[0], z0 = v[2]; - for (let i = 0; i < v.length; i += 3) { v[i] = x0; v[i + 2] = z0; } - } -} -``` - -FBX intake specifics (v1.0 humanoid retargets): - -- `FBXLoader` lives at `three/addons/loaders/FBXLoader.js` and imports `fflate`; bundler projects get it from npm automatically, but import-map/CDN pages must map it (e.g. `"fflate": "https://cdn.jsdelivr.net/npm/fflate@0.8.2/esm/browser.js"`). -- Use ONE FBX per animation (the pipeline does this automatically) and play each file's `animations[0]` as exported. The variant order of duplicate takes differs per file — `animations[0]` is always the correct one. - -- `FBXLoader` emits each take twice under different node-path prefixes (`Armature.001|walk_…` and `Armature|Armature.001|walk_…`). Keep the variant with the SHALLOWER path (fewer `|` segments); the deep variant's tracks bind incorrectly. -- Clips carry real names (`walk_normal_m_remap`, `idle_251105_remap`) — select by keyword (slash arrives as an attack/swing name), not by index. -- Play the clips otherwise untouched. Every loader-side "fix" beyond the single root-position strip has been tested and makes things worse. -- FBXLoader produces Phong materials (darker than GLB PBR). For final art parity, convert FBX→GLB offline (Blender import/export or FBX2glTF) — the corrected animation survives conversion. -- Tripo preset retargeting only works on `spec=tripo` rigs. A `spec=mixamo` rig is for external animation pipelines (Mixamo clips, custom libraries) — retarget those in a DCC tool or at runtime with `SkeletonUtils.retargetClip`, and expect to supply bone-name mappings and check bind-pose orientation when skeleton conventions differ. - -## Asset Intake Checklist - -Inspect before shipping: - -- File size. -- Triangle count. -- Mesh count. -- Material count. -- Texture count and texture dimensions. -- PBR material behavior under the game lighting rig. -- Scale in meters and `auto_size` assumptions. -- Pivot/origin and bounds. -- Collision proxy separate from detailed mesh. -- Animation clip names, durations, root motion, and in-place behavior. -- Mobile memory/performance impact. - -## Game Asset Strategy - -- Use `threejs-3d-generator` for hero assets, characters, creatures, bosses, buildings, weapons, signature props, and complex pickups. -- Use procedural Three.js kits for high-volume repeated detail such as bolts, windows, track plates, rails, debris, markers, and background silhouettes. -- Use `threejs-image-generator` for concept art, texture references, decals, logos, UI icons, and backdrop images. -- Combine: image-generator concept -> 3D-generator model -> Three.js import -> procedural set dressing -> visual scorecard. - -## Performance Discipline - -- Use `face_limit`, `smart_low_poly`, conversion, or low-poly postprocess for browser/mobile budgets. -- Prefer one high-fidelity hero asset plus instanced/procedural supporting detail over many unique heavy models. -- Keep textures compressed or reasonably sized. -- Clone carefully. Share geometry/materials when possible. -- Dispose loaded assets when leaving scenes. -- Run renderer diagnostics after importing: calls, triangles, geometries, textures, materials, file sizes. - -## Common Fixes - -- Model too large/small: normalize bounds in an asset wrapper group. -- Wrong orientation: set a wrapper rotation, or use Tripo image `orientation=align_image` for image inputs. -- Animations move out of place: keep exported root motion intact, then strip only horizontal root-position components in code as shown above. Do not retarget with `animate_in_place=true`. -- Too expensive: lower `face_limit`, use `smart_low_poly`, reduce texture quality/size, or convert with a face limit. -- Materials too dark/bright: check color space, tone mapping, environment, and light exposure. -- Collision too complex: build primitive proxies in Three.js and keep Tripo mesh visual-only. - -## Final Evidence - -Report: - -- 3D generator task IDs. -- Downloaded asset paths. -- Model version and generation options. -- Post-process tasks: texture, rig, animation, conversion. -- Three.js import files changed. -- Renderer diagnostics before/after import. -- Screenshot evidence in active gameplay. diff --git a/.agents/skills/threejs-3d-generator/scripts/threejs_3d_asset.py b/.agents/skills/threejs-3d-generator/scripts/threejs_3d_asset.py deleted file mode 100755 index 49e615a453..0000000000 --- a/.agents/skills/threejs-3d-generator/scripts/threejs_3d_asset.py +++ /dev/null @@ -1,985 +0,0 @@ -#!/usr/bin/env python3 -"""Small Tripo OpenAPI client for skill-driven 3D asset generation.""" - -from __future__ import annotations - -import argparse -import json -import mimetypes -import os -from pathlib import Path -import sys -import time -from typing import Any -from urllib import error, parse, request - -BASE_URL = "https://api.tripo3d.ai/v2/openapi" -FINAL_STATUSES = {"success", "failed", "banned", "expired", "cancelled", "unknown"} -DOWNLOAD_KEYS = ( - "pbr_model", - "model", - "base_model", - "rendered_image", - "generated_image", -) - -RIG_MODEL_VERSION = "v2.5-20260210" -BIPED_PRESETS = ( - "preset:idle", - "preset:walk", - "preset:run", - "preset:dive", - "preset:climb", - "preset:jump", - "preset:slash", - "preset:shoot", - "preset:hurt", - "preset:fall", - "preset:turn", -) -RIG_TYPE_PRESETS = { - "biped": set(BIPED_PRESETS), - "quadruped": {"preset:quadruped:walk"}, - "hexapod": {"preset:hexapod:walk"}, - "octopod": {"preset:octopod:walk"}, - "serpentine": {"preset:serpentine:march"}, - "aquatic": {"preset:aquatic:march"}, - "avian": set(), -} -KNOWN_PRESETS = set().union(*RIG_TYPE_PRESETS.values()) -RETARGET_BATCH_LIMIT = 5 - - -def validate_animations(animations: list[str], rig_type: str | None = None, rig_model_version: str | None = None) -> None: - """Fail fast on presets the API will reject, before any credits are spent.""" - # None = server default (used when retargeting v1.0 rigs); allow both namespaces then. - legacy = None if rig_model_version is None else rig_model_version.startswith("v1.0") - for animation in animations: - if not animation.startswith("preset:"): - continue - if animation.startswith("preset:biped:"): - # The large legacy clip library only works on v1.0-20240301 rigs. - if legacy is False: - raise TripoError( - f"{animation} belongs to the v1.0-20240301 rig's preset library; retarget " - "with --model-version default on a v1.0 rig to use it." - ) - continue - if legacy: - raise TripoError( - f"{animation} is a v2.x preset; v1.0-20240301 rigs use the preset:biped:* " - "library instead (e.g. preset:biped:idle, preset:biped:walk, preset:biped:run)." - ) - if animation not in KNOWN_PRESETS: - hint = "" - if "attack" in animation: - hint = " There is no preset:attack; use preset:slash or preset:shoot." - raise TripoError( - f"Unknown animation preset {animation!r}.{hint} " - f"Valid presets: {', '.join(sorted(KNOWN_PRESETS))}" - ) - if rig_type and rig_type in RIG_TYPE_PRESETS and animation not in RIG_TYPE_PRESETS[rig_type]: - valid = ", ".join(sorted(RIG_TYPE_PRESETS[rig_type])) or "none documented for this rig type" - raise TripoError( - f"{animation} is not compatible with rig_type {rig_type!r}. Valid: {valid}" - ) - - -class TripoError(RuntimeError): - pass - - -def eprint(*parts: object) -> None: - print(*parts, file=sys.stderr) - - -def api_key_from(args: argparse.Namespace) -> str: - key = args.api_key or os.environ.get("TRIPO_API_KEY") - if not key: - raise TripoError("Missing API key. Set TRIPO_API_KEY or pass --api-key.") - return key - - -def json_request(api_key: str, method: str, path: str, payload: dict[str, Any] | None = None) -> dict[str, Any]: - url = f"{BASE_URL}{path}" - body = json.dumps(payload).encode("utf-8") if payload is not None else None - req = request.Request(url, data=body, method=method) - req.add_header("Authorization", f"Bearer {api_key}") - if payload is not None: - req.add_header("Content-Type", "application/json") - try: - with request.urlopen(req, timeout=60) as resp: - raw = resp.read().decode("utf-8") - except error.HTTPError as exc: - raw = exc.read().decode("utf-8", errors="replace") - raise TripoError(f"HTTP {exc.code} {exc.reason}: {raw}") from exc - except error.URLError as exc: - raise TripoError(f"Request failed: {exc.reason}") from exc - data = json.loads(raw) - if data.get("code") != 0: - raise TripoError(json.dumps(data, indent=2)) - return data - - -def multipart_upload(api_key: str, file_path: Path) -> str: - if not file_path.exists(): - raise TripoError(f"Image not found: {file_path}") - if file_path.stat().st_size > 20 * 1024 * 1024: - raise TripoError("Tripo upload limit is 20MB.") - mime = mimetypes.guess_type(str(file_path))[0] or "application/octet-stream" - ext = file_path.suffix.lower().lstrip(".") - if ext == "jpg": - ext = "jpeg" - if ext not in {"png", "jpeg", "webp"}: - raise TripoError("Direct image upload accepts png, jpeg/jpg, or webp.") - - boundary = f"tripo-boundary-{int(time.time() * 1000)}" - content = file_path.read_bytes() - parts = [ - f"--{boundary}\r\n".encode(), - ( - f'Content-Disposition: form-data; name="file"; filename="{file_path.name}"\r\n' - f"Content-Type: {mime}\r\n\r\n" - ).encode(), - content, - f"\r\n--{boundary}--\r\n".encode(), - ] - body = b"".join(parts) - req = request.Request(f"{BASE_URL}/upload/sts", data=body, method="POST") - req.add_header("Authorization", f"Bearer {api_key}") - req.add_header("Content-Type", f"multipart/form-data; boundary={boundary}") - req.add_header("Content-Length", str(len(body))) - try: - with request.urlopen(req, timeout=120) as resp: - raw = resp.read().decode("utf-8") - except error.HTTPError as exc: - raw = exc.read().decode("utf-8", errors="replace") - raise TripoError(f"Upload failed: HTTP {exc.code} {exc.reason}: {raw}") from exc - data = json.loads(raw) - if data.get("code") != 0: - raise TripoError(json.dumps(data, indent=2)) - token = data.get("data", {}).get("image_token") - if not token: - raise TripoError(f"Upload response did not include image_token: {raw}") - return token - - -def submit_task(api_key: str, payload: dict[str, Any]) -> str: - data = json_request(api_key, "POST", "/task", payload) - task_id = data.get("data", {}).get("task_id") - if not task_id: - raise TripoError(f"Task response did not include task_id: {data}") - print(task_id) - return task_id - - -def get_task(api_key: str, task_id: str) -> dict[str, Any]: - return json_request(api_key, "GET", f"/task/{task_id}")["data"] - - -def wait_for_task(api_key: str, task_id: str, interval: int, timeout: int) -> dict[str, Any]: - start = time.monotonic() - while True: - data = get_task(api_key, task_id) - status = data.get("status", "unknown") - progress = data.get("progress", 0) - eprint(f"{task_id}: {status} {progress}%") - if status in FINAL_STATUSES: - return data - if time.monotonic() - start > timeout: - raise TripoError(f"Timed out waiting for task {task_id}") - time.sleep(interval) - - -def safe_name(value: str) -> str: - keep = [] - for char in value.lower(): - if char.isalnum(): - keep.append(char) - elif char in {"-", "_", " "}: - keep.append("-") - name = "".join(keep).strip("-") - while "--" in name: - name = name.replace("--", "-") - return name or "asset" - - -def extension_for(key: str, url: str, content_type: str | None = None) -> str: - path = parse.urlparse(url).path - ext = Path(path).suffix - if ext: - return ext - if content_type: - guessed = mimetypes.guess_extension(content_type.split(";")[0].strip()) - if guessed: - return guessed - if "image" in key: - return ".png" - return ".glb" - - -def download_url(url: str, out_dir: Path, filename_base: str, key: str) -> Path: - req = request.Request(url, method="GET") - with request.urlopen(req, timeout=300) as resp: - content = resp.read() - content_type = resp.headers.get("Content-Type") - ext = extension_for(key, url, content_type) - out_dir.mkdir(parents=True, exist_ok=True) - path = out_dir / f"{filename_base}-{key}{ext}" - path.write_bytes(content) - return path - - -def download_outputs(task: dict[str, Any], out_dir: Path) -> list[Path]: - task_id = task["task_id"] - output = task.get("output") or {} - paths: list[Path] = [] - out_dir.mkdir(parents=True, exist_ok=True) - (out_dir / f"{task_id}.json").write_text(json.dumps(task, indent=2), encoding="utf-8") - for key in DOWNLOAD_KEYS: - url = output.get(key) - if isinstance(url, str) and url.startswith("http"): - path = download_url(url, out_dir, task_id, key) - paths.append(path) - print(path) - multiview = output.get("generate_multiview_image") - if isinstance(multiview, dict): - for key, url in multiview.items(): - if isinstance(url, str) and url.startswith("http"): - path = download_url(url, out_dir, task_id, key) - paths.append(path) - print(path) - if not paths: - eprint("No downloadable output URLs found.") - return paths - - -def glb_node_names(path: Path) -> list[str]: - import struct - with path.open("rb") as handle: - header = handle.read(12) - if len(header) < 12 or header[:4] != b"glTF": - raise TripoError(f"Not a GLB file: {path}") - chunk_len, _chunk_type = struct.unpack(" list[str]: - return [name for name in glb_node_names(path) if name.startswith("tripo::")] - - -LEGACY_BIPED_PAIRED_BONES = ("Clavicle", "Upperarm", "Forearm", "Hand", "Thigh", "Calf", "Foot") - - -def validate_rig_glb(path: Path, rig_type: str) -> tuple[str, list[str]]: - """Validate either rig naming scheme. v2.x rigs use tripo::__Limb_ - chains; v1.0-20240301 rigs use an anatomical Mixamo-like skeleton (Hip, Spine01, - L_Upperarm, R_Calf, twist bones, ...).""" - names = glb_node_names(path) - bones = [n for n in names if n.startswith("tripo::")] - if bones: - return f"{len(bones)} tripo:: bones: {', '.join(sorted(bones))}", validate_rig_bones(bones, rig_type) - left = {n[2:] for n in names if n.startswith("L_")} - right = {n[2:] for n in names if n.startswith("R_")} - if not left and not right: - return "no recognizable rig bones", ["no tripo:: or legacy L_/R_ bones found in rig GLB"] - problems = [] - for part in LEGACY_BIPED_PAIRED_BONES: - if part not in left or part not in right: - problems.append(f"legacy rig missing L_/R_ {part}") - if left != right: - problems.append(f"legacy rig asymmetric bones: {sorted(left.symmetric_difference(right))}") - if rig_type != "biped": - problems.append(f"legacy anatomical skeleton is biped-only; requested rig_type {rig_type!r}") - return f"legacy anatomical skeleton, {len(left)} paired L/R bones: {', '.join(sorted(left))}", problems - - -def validate_rig_bones(bones: list[str], rig_type: str) -> list[str]: - """Return problems with a downloaded rig's skeleton. A passing prerigcheck does - not guarantee a usable rig: degenerate rigs (e.g. spine plus one arm) do occur, - and every later retarget inherits the damage.""" - problems: list[str] = [] - if not bones: - problems.append("no tripo:: bones found in rig GLB") - return problems - rows: dict[str, dict[str, int]] = {} - for bone in bones: - if "_Limb_" not in bone: - continue - row, side = bone.split("::")[-1].split("_")[0:2] - rows.setdefault(row, {}).setdefault(side, 0) - rows[row][side] += 1 - for row, sides in sorted(rows.items()): - if set(sides) != {"Left", "Right"}: - problems.append(f"limb row {row} has only {'/'.join(sorted(sides))} (asymmetric rig)") - continue - left, right = sides["Left"], sides["Right"] - # A knee-less leg or elbow-less arm warps every retargeted clip. Healthy - # Tripo rigs are depth-symmetric (e.g. 5/5, 6/6, occasionally 6/5); broken - # ones are 2/4, 9/4, or 4/1. Tolerate a 1-bone difference. - if abs(left - right) > 1: - problems.append(f"limb row {row} chain depth mismatch: Left={left} vs Right={right}") - if rig_type in {"biped", "quadruped"} and min(left, right) < 3: - problems.append(f"limb row {row} chain too shallow ({min(left, right)} bones; need >=3 for joint articulation)") - if rig_type in {"biped", "quadruped"} and len(rows) < 2: - problems.append(f"only {len(rows)} limb row(s); {rig_type} needs arms and legs (2 rows)") - if rig_type == "biped" and not any(b.startswith("tripo::Head") for b in bones) and len(bones) < 12: - problems.append(f"suspiciously small skeleton ({len(bones)} bones)") - return problems - - -def add_common_model_args(parser: argparse.ArgumentParser) -> None: - parser.add_argument("--model-version", default="v3.1-20260211") - parser.add_argument("--negative-prompt") - parser.add_argument("--model-seed", type=int) - parser.add_argument("--image-seed", type=int) - parser.add_argument("--texture-seed", type=int) - parser.add_argument("--texture-quality", choices=["standard", "detailed", "extreme"]) - parser.add_argument("--geometry-quality", choices=["standard", "detailed"]) - parser.add_argument("--face-limit", type=int) - parser.add_argument("--no-texture", action="store_true") - parser.add_argument("--no-pbr", action="store_true") - parser.add_argument("--smart-low-poly", action="store_true") - parser.add_argument("--quad", action="store_true") - parser.add_argument("--auto-size", action="store_true") - parser.add_argument("--compress", choices=["geometry", "meshopt"]) - parser.add_argument("--generate-parts", action="store_true") - parser.add_argument("--no-export-uv", action="store_true") - - -def apply_common_model_args(args: argparse.Namespace, payload: dict[str, Any]) -> None: - mapping = { - "negative_prompt": args.negative_prompt, - "model_seed": args.model_seed, - "image_seed": args.image_seed, - "texture_seed": args.texture_seed, - "texture_quality": args.texture_quality, - "geometry_quality": args.geometry_quality, - "face_limit": args.face_limit, - "smart_low_poly": True if args.smart_low_poly else None, - "quad": True if args.quad else None, - "auto_size": True if args.auto_size else None, - "compress": args.compress, - "generate_parts": True if args.generate_parts else None, - } - for key, value in mapping.items(): - if value is not None: - payload[key] = value - if args.no_texture: - payload["texture"] = False - if args.no_pbr: - payload["pbr"] = False - if args.no_export_uv: - payload["export_uv"] = False - - -def maybe_wait_and_download(api_key: str, task_id: str, args: argparse.Namespace) -> dict[str, Any] | None: - if not args.wait: - return None - task = wait_for_task(api_key, task_id, args.interval, args.timeout) - print(json.dumps(task, indent=2)) - if task.get("status") != "success": - raise TripoError(f"Task {task_id} ended as {task.get('status')}") - if args.download: - download_outputs(task, Path(args.out_dir)) - return task - - -def cmd_text(args: argparse.Namespace) -> None: - api_key = api_key_from(args) - payload: dict[str, Any] = { - "type": "text_to_model", - "prompt": args.prompt, - "model_version": args.model_version, - } - apply_common_model_args(args, payload) - task_id = submit_task(api_key, payload) - maybe_wait_and_download(api_key, task_id, args) - - -def cmd_image(args: argparse.Namespace) -> None: - api_key = api_key_from(args) - image = args.image - if image.startswith(("http://", "https://")): - file_obj = {"type": "image", "url": image} - else: - token = multipart_upload(api_key, Path(image)) - file_obj = {"type": "image", "file_token": token} - payload: dict[str, Any] = { - "type": "image_to_model", - "file": file_obj, - "model_version": args.model_version, - } - if args.enable_image_autofix: - payload["enable_image_autofix"] = True - if args.texture_alignment: - payload["texture_alignment"] = args.texture_alignment - if args.orientation: - payload["orientation"] = args.orientation - apply_common_model_args(args, payload) - task_id = submit_task(api_key, payload) - maybe_wait_and_download(api_key, task_id, args) - - -def cmd_status(args: argparse.Namespace) -> None: - api_key = api_key_from(args) - print(json.dumps(get_task(api_key, args.task_id), indent=2)) - - -def cmd_download(args: argparse.Namespace) -> None: - api_key = api_key_from(args) - task = get_task(api_key, args.task_id) - if task.get("status") != "success": - raise TripoError(f"Task is {task.get('status')}; download URLs are available after success.") - download_outputs(task, Path(args.out_dir)) - - -def normalized_post_type(value: str) -> str: - aliases = { - "convert_model": "conversion", - "conversion": "conversion", - "retarget": "animate_retarget", - "rig": "animate_rig", - "prerig": "animate_prerigcheck", - "prerigcheck": "animate_prerigcheck", - "lowpoly": "highpoly_to_lowpoly", - } - return aliases.get(value, value) - - -def cmd_postprocess(args: argparse.Namespace) -> None: - api_key = api_key_from(args) - task_type = normalized_post_type(args.type) - payload: dict[str, Any] = { - "type": task_type, - "original_model_task_id": args.original_task_id, - } - default_versions = { - "texture_model": "v3.0-20250812", - "highpoly_to_lowpoly": "P-v2.0-20251225", - } - if task_type == "animate_prerigcheck": - # The prerigcheck request schema has no model_version parameter. - if args.model_version: - eprint("warning: animate_prerigcheck takes no model_version; ignoring it") - elif args.model_version and args.model_version.lower() in {"default", "none"}: - # Omit model_version and let the API choose (needed when retargeting v1.0 rigs: - # the retarget enum rejects v1.0-20240301 as an explicit value). - pass - elif task_type in {"animate_rig", "animate_retarget"} and not args.model_version: - # Route by body plan, same as character-pipeline: the v2.x rigger fails on - # humanoids (0/16, see api-notes.md), so biped must use v1.0. - rig_type = args.rig_type or "biped" - if not args.rig_type: - eprint( - "note: no --rig-type given; assuming biped when choosing the rig model " - "version (pass --rig-type or an explicit --model-version to override)" - ) - resolved = resolve_rig_version(rig_type, None) - if task_type == "animate_retarget" and resolved.startswith("v1.0"): - # The retarget schema rejects explicit v1.0; omitting model_version selects - # the legacy path (which forces FBX output and one animation per task below). - eprint("note: v1.0-rig retarget: omitting model_version (API rejects explicit v1.0)") - else: - payload["model_version"] = resolved - eprint(f"Using model_version={resolved} for rig_type={rig_type}") - else: - model_version = args.model_version or default_versions.get(task_type) - if model_version: - payload["model_version"] = model_version - if task_type == "texture_model": - if not args.texture_prompt: - raise TripoError("--texture-prompt is required for texture_model") - payload["texture_prompt"] = {"text": args.texture_prompt} - if args.texture_quality: - payload["texture_quality"] = args.texture_quality - elif task_type == "animate_rig": - if args.out_format: - payload["out_format"] = args.out_format - if args.rig_type: - payload["rig_type"] = args.rig_type - if args.spec: - payload["spec"] = args.spec - elif task_type == "animate_retarget": - # original_model_task_id must be the RIG task ID for retarget. - # v1.0 rigs (legacy humanoid path): the GLB animation bake is DEFECTIVE — - # limb mesh is skinned to twist bones whose GLB transforms are exported in - # the wrong space, collapsing arms into the torso (verified June 2026; the - # FBX export of the same task is correct). Force FBX on this path. - legacy_retarget = "model_version" not in payload - if legacy_retarget and (args.out_format or "glb") != "fbx": - if args.out_format == "glb": - raise TripoError( - "v1.0-rig retargets must use --out-format fbx: Tripo's GLB bake corrupts " - "twist-bone transforms (limbs collapse into the torso). Load the FBX with " - "three.js FBXLoader, or convert FBX->GLB offline (Blender/FBX2glTF)." - ) - eprint("note: v1.0-rig retarget defaults to out_format=fbx (GLB bake is broken for this path)") - payload["out_format"] = "fbx" - if legacy_retarget and args.animations: - raise TripoError( - "v1.0-rig retargets must request ONE animation per task: batching produces an FBX " - "with one armature per clip (Armature.001, .002, ...) whose name-colliding bones " - "bind to the wrong skeleton and pitch the body. Submit separate tasks with --animation." - ) - if args.animations: - animations = [item.strip() for item in args.animations.split(",") if item.strip()] - validate_animations(animations, rig_model_version=payload.get("model_version")) - if len(animations) > RETARGET_BATCH_LIMIT: - raise TripoError( - f"animate_retarget accepts at most {RETARGET_BATCH_LIMIT} animations per task; " - f"got {len(animations)}. Split into multiple tasks." - ) - payload["animations"] = animations - elif args.animation: - validate_animations([args.animation], rig_model_version=payload.get("model_version")) - payload["animation"] = args.animation - else: - raise TripoError("--animation or --animations is required for animate_retarget") - if args.out_format: - payload["out_format"] = args.out_format - if args.animate_in_place: - eprint( - "warning: animate_in_place is VERIFIED to corrupt retargeted clips " - "(mirrored/crossed limbs on v1.0 rigs, exploded skinning on v2.5 rigs, June 2026). " - "Prefer baked root motion and strip the root translation track in the engine." - ) - payload["animate_in_place"] = True - if args.no_bake_animation: - payload["bake_animation"] = False - if args.no_export_with_geometry: - payload["export_with_geometry"] = False - elif task_type == "conversion": - if not args.format: - raise TripoError("--format is required for conversion") - payload["format"] = args.format - for key in ("face_limit", "texture_size", "flatten_bottom_threshold"): - value = getattr(args, key) - if value is not None: - payload[key] = value - if args.quad: - payload["quad"] = True - if args.force_symmetry: - payload["force_symmetry"] = True - if args.flatten_bottom: - payload["flatten_bottom"] = True - elif task_type == "highpoly_to_lowpoly": - if args.face_limit: - payload["face_limit"] = args.face_limit - elif task_type == "stylize_model": - if not args.style: - raise TripoError("--style is required for stylize_model") - payload["style"] = args.style - if args.block_size: - payload["block_size"] = args.block_size - - task_id = submit_task(api_key, payload) - maybe_wait_and_download(api_key, task_id, args) - - -def resolve_rig_version(rig_type: str, override: str | None) -> str: - """Measured June 2026: the v2.x limb-chain rigger fails on humanoids (0/16, - asymmetric chains) while v1.0 produces a proper anatomical skeleton; v2.x is - solid for creatures. Route by body plan unless explicitly overridden.""" - if override: - return override - return "v1.0-20240301" if rig_type == "biped" else RIG_MODEL_VERSION - - -def to_legacy_biped_presets(animations: list[str]) -> list[str]: - """v1.0 rigs use the preset:biped:* library; map plain v2.5-style names onto it - so callers can say preset:idle regardless of which rig path gets chosen.""" - mapped = [] - for animation in animations: - suffix = animation[len("preset:"):] if animation.startswith("preset:") else None - if suffix and ":" not in suffix: - mapped.append(f"preset:biped:{suffix}") - else: - mapped.append(animation) - return mapped - - -def cmd_character_pipeline(args: argparse.Namespace) -> None: - api_key = api_key_from(args) - if not args.model_task_id and not args.prompt: - raise TripoError("--prompt is required unless --model-task-id reuses an existing generation task") - animations = [item.strip() for item in args.animations.split(",") if item.strip()] - if animations and args.spec == "mixamo": - raise TripoError( - "spec=mixamo rigs cannot be used with Tripo animate_retarget. " - "Use --animations '' and retarget external clips (e.g. Mixamo) onto the rig yourself, " - "or keep --spec tripo for Tripo preset animations." - ) - # Loose catalog check now (both namespaces allowed); strict per-rig-type - # validation happens after prerigcheck, before rig credits are spent. - validate_animations(animations, None, None) - - out_dir = Path(args.out_dir) - if args.model_task_id: - model_task_id = args.model_task_id - eprint(f"Skipping generation; reusing model task {model_task_id}") - else: - prompt = args.prompt - # The T-pose suffix is biped-specific; creature prompts need their own stance language. - if (args.rig_type in (None, "biped") - and "t-pose" not in prompt.lower() and "a-pose" not in prompt.lower()): - prompt = ( - f"{prompt}, full-body T-pose for rigging, arms straight out to the sides, " - "legs apart and visible, front facing, symmetric, no props attached to the body" - ) - text_payload: dict[str, Any] = { - "type": "text_to_model", - "prompt": prompt, - "model_version": args.model_version, - "texture_quality": args.texture_quality, - "geometry_quality": args.geometry_quality, - "pbr": True, - } - if args.face_limit: - text_payload["face_limit"] = args.face_limit - model_task_id = submit_task(api_key, text_payload) - model_task = wait_for_task(api_key, model_task_id, args.interval, args.timeout) - if model_task.get("status") != "success": - raise TripoError(f"Model task failed: {model_task.get('status')}") - download_outputs(model_task, out_dir / "base") - eprint("Check the downloaded rendered_image: the character must be in a clear T/A-pose before rigging.") - - check_id = submit_task(api_key, { - "type": "animate_prerigcheck", - "original_model_task_id": model_task_id, - }) - check_task = wait_for_task(api_key, check_id, args.interval, args.timeout) - print(json.dumps(check_task, indent=2)) - output = check_task.get("output") or {} - if output.get("riggable") is False: - if not args.force_rig: - raise TripoError( - f"Prerigcheck reports the model is not riggable: {output}. " - "Best fix: regenerate with a clearer full-body T-pose (or a T-pose reference image). " - "Tripo docs note a false result is not always final; pass --force-rig to attempt anyway." - ) - eprint("warning: proceeding despite riggable=false (--force-rig)") - detected_rig_type = output.get("rig_type") - rig_type = args.rig_type or detected_rig_type or "biped" - if args.rig_type and detected_rig_type and args.rig_type != detected_rig_type: - eprint( - f"warning: prerigcheck detected rig_type={detected_rig_type} " - f"but --rig-type {args.rig_type} was requested; using {args.rig_type}" - ) - rig_model_version = resolve_rig_version(rig_type, args.rig_model_version) - legacy = rig_model_version.startswith("v1.0") - if legacy: - animations = to_legacy_biped_presets(animations) - eprint(f"Using rig_type={rig_type} rig_model_version={rig_model_version}" - + (f" animations={','.join(animations)}" if animations else "")) - validate_animations(animations, rig_type if not legacy else None, rig_model_version) - - # Auto-rigging is nondeterministic: the same model can produce a degenerate - # skeleton on one attempt and a healthy one on the next. Retry before giving up. - attempts = 1 + max(0, args.rig_retries) - rig_id = None - last_detail = "no rig attempt succeeded" - for attempt in range(1, attempts + 1): - candidate_id = submit_task(api_key, { - "type": "animate_rig", - "original_model_task_id": model_task_id, - "model_version": rig_model_version, - "rig_type": rig_type, - "spec": args.spec, - "out_format": "glb", - }) - rig_task = wait_for_task(api_key, candidate_id, args.interval, args.timeout) - if rig_task.get("status") != "success": - last_detail = f"rig task ended as {rig_task.get('status')} (error_code={rig_task.get('error_code')})" - eprint(f"rig attempt {attempt}/{attempts}: {last_detail}") - continue - suffix = "rig" if attempt == 1 else f"rig-attempt{attempt}" - rig_paths = download_outputs(rig_task, out_dir / suffix) - rig_glbs = [p for p in rig_paths if p.suffix == ".glb"] - problems = [] - if rig_glbs: - description, problems = validate_rig_glb(rig_glbs[0], rig_type) - eprint(f"Rig skeleton ({attempt}/{attempts}): {description}") - if not problems: - rig_id = candidate_id - break - last_detail = "; ".join(problems) - eprint(f"rig attempt {attempt}/{attempts} failed validation: {last_detail}") - if rig_id is None: - if not args.force_rig: - raise TripoError( - f"No structurally valid rig after {attempts} attempt(s) ({last_detail}). " - "Retargets on a bad rig warp the character. Regenerate the base model with " - "clearer limb separation (strict T-pose, arms horizontal, legs apart and visible, " - "no long skirt/cape/props fusing limbs to the body), or pass --force-rig to use " - "the last rig anyway." - ) - rig_id = candidate_id - eprint(f"warning: using unvalidated rig ({last_detail}); continuing (--force-rig)") - - # Retarget references the RIG task ID. v2.5 rigs batch up to 5 presets per - # task; v1.0 rigs must take ONE per task (batched FBX exports one armature - # per clip whose name-colliding bones cross-bind and pitch the body). - batch_size = 1 if legacy else RETARGET_BATCH_LIMIT - for start in range(0, len(animations), batch_size): - batch = animations[start:start + batch_size] - # v1.0 GLB animation bake is defective (twist-bone space bug collapses limbs); - # the FBX export of the same task is correct. See api-notes.md. - retarget_payload: dict[str, Any] = { - "type": "animate_retarget", - "original_model_task_id": rig_id, - "animations": batch, - "out_format": "fbx" if legacy else "glb", - } - if not legacy: - retarget_payload["model_version"] = rig_model_version - if args.animate_in_place: - eprint( - "warning: animate_in_place is VERIFIED to corrupt retargeted clips " - "(mirrored/crossed limbs on v1.0 rigs, exploded skinning on v2.5 rigs, June 2026). " - "Prefer baked root motion and strip the root translation track in the engine." - ) - retarget_payload["animate_in_place"] = True - anim_id = submit_task(api_key, retarget_payload) - anim_task = wait_for_task(api_key, anim_id, args.interval, args.timeout) - if anim_task.get("status") != "success": - raise TripoError(f"Animation batch {batch} failed: {anim_task.get('status')}") - batch_name = safe_name("-".join(item.split(":")[-1] for item in batch)) - download_outputs(anim_task, out_dir / batch_name) - eprint("Inspect gltf.animations clip names/counts in each download before wiring the AnimationMixer.") - - -def load_glb(path: Path) -> tuple[dict[str, Any], bytes]: - import struct - data = path.read_bytes() - if data[:4] != b"glTF": - raise TripoError(f"Not a GLB file: {path}") - offset = 12 - gltf: dict[str, Any] | None = None - bin_chunk = b"" - while offset < len(data): - clen, ctype = struct.unpack_from(" list[tuple[float, ...]]: - import struct - comp = {5126: ("f", 4), 5123: ("H", 2), 5125: ("I", 4)} - ncomp = {"SCALAR": 1, "VEC3": 3, "VEC4": 4} - acc = gltf["accessors"][idx] - bv = gltf["bufferViews"][acc["bufferView"]] - start = bv.get("byteOffset", 0) + acc.get("byteOffset", 0) - n = ncomp[acc["type"]] - fmt, _ = comp[acc["componentType"]] - count = acc["count"] - vals = struct.unpack_from(f"<{count * n}{fmt}", bin_chunk, start) - return [vals[i * n:(i + 1) * n] for i in range(count)] - - -def validate_animation_glb(path: Path) -> tuple[list[str], list[str]]: - """Keyframe-level QA for retargeted clips. Returns (report_lines, problems). - Warp signatures: scale tracks, or translation tracks on non-root bones that - deviate far from the bone's rest offset (limb stretching).""" - import math - gltf, bin_chunk = load_glb(path) - nodes = gltf.get("nodes", []) - roots = {"Armature", "Root", "Hip", "Pelvis", "tripo::Root"} - report: list[str] = [] - problems: list[str] = [] - animations = gltf.get("animations", []) - if not animations: - return ["no animations in file"], ["no animation clips found"] - for anim in animations: - dur = 0.0 - rot_bones: set[str] = set() - big_rot: dict[str, int] = {} - for ch in anim["channels"]: - sampler = anim["samplers"][ch["sampler"]] - times = _read_accessor(gltf, bin_chunk, sampler["input"]) - out = _read_accessor(gltf, bin_chunk, sampler["output"]) - node = nodes[ch["target"]["node"]] if ch["target"].get("node") is not None else {} - name = node.get("name", "?") - dur = max(dur, times[-1][0]) - path_kind = ch["target"]["path"] - if path_kind == "rotation": - rot_bones.add(name) - base = out[0] - amp = 0.0 - for q in out: - dot = abs(sum(a * b for a, b in zip(base, q))) - amp = max(amp, 2 * math.acos(min(1.0, dot))) - if math.degrees(amp) > 170: - big_rot[name] = round(math.degrees(amp)) - elif path_kind == "scale": - problems.append(f"{anim.get('name')}: scale track on {name} (warp risk)") - elif path_kind == "translation" and name not in roots and name.split("::")[-1] not in roots: - rest = node.get("translation", [0, 0, 0]) - restlen = math.sqrt(sum(c * c for c in rest)) or 1e-9 - dev = max(math.sqrt(sum((v[i] - rest[i]) ** 2 for i in range(3))) for v in out) - if dev / restlen > 0.5: - problems.append( - f"{anim.get('name')}: translation track on non-root bone {name} deviates " - f"{dev / restlen:.1f}x its rest offset (limb stretch warp)" - ) - report.append(f"{anim.get('name')}: {dur:.2f}s, {len(anim['channels'])} channels, {len(rot_bones)} bones rotating") - if big_rot: - report.append(f" rotation amplitude >170deg (check visually): {big_rot}") - return report, problems - - -def cmd_validate_animation(args: argparse.Namespace) -> None: - report, problems = validate_animation_glb(Path(args.glb_path)) - for line in report: - print(line) - if problems: - raise TripoError("Animation validation failed: " + "; ".join(problems)) - print("Clips look structurally sound (verify motion visually in the engine).") - - -def cmd_validate_rig(args: argparse.Namespace) -> None: - description, problems = validate_rig_glb(Path(args.glb_path), args.rig_type) - print(description) - if problems: - raise TripoError("Rig validation failed: " + "; ".join(problems)) - print("Rig looks structurally valid.") - - -def cmd_probe(args: argparse.Namespace) -> None: - """Print the SET|MISSING credential contract line used by skip rules and audits.""" - status = "SET" if os.environ.get("TRIPO_API_KEY") else "MISSING" - print(f"TRIPO_API_KEY={status}") - - -def add_shared_runtime_args(parser: argparse.ArgumentParser) -> None: - parser.add_argument("--api-key") - parser.add_argument("--wait", action="store_true") - parser.add_argument("--download", action="store_true") - parser.add_argument("--out-dir", default="tripo-output") - parser.add_argument("--interval", type=int, default=8) - parser.add_argument("--timeout", type=int, default=600) - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(description="Tripo OpenAPI 3D asset helper") - sub = parser.add_subparsers(dest="command", required=True) - - probe = sub.add_parser("probe", help="print TRIPO_API_KEY=SET|MISSING") - probe.set_defaults(func=cmd_probe) - - text = sub.add_parser("text", help="submit text_to_model") - text.add_argument("--prompt", required=True) - add_common_model_args(text) - add_shared_runtime_args(text) - text.set_defaults(func=cmd_text) - - image = sub.add_parser("image", help="submit image_to_model from local path or URL") - image.add_argument("--image", required=True) - image.add_argument("--enable-image-autofix", action="store_true") - image.add_argument("--texture-alignment", choices=["original_image", "geometry"]) - image.add_argument("--orientation", choices=["default", "align_image"]) - add_common_model_args(image) - add_shared_runtime_args(image) - image.set_defaults(func=cmd_image) - - status = sub.add_parser("status", help="get task status") - status.add_argument("task_id") - status.add_argument("--api-key") - status.set_defaults(func=cmd_status) - - download = sub.add_parser("download", help="download successful task outputs") - download.add_argument("task_id") - download.add_argument("--api-key") - download.add_argument("--out-dir", default="tripo-output") - download.set_defaults(func=cmd_download) - - post = sub.add_parser("postprocess", help="submit Tripo postprocess task") - post.add_argument("--type", required=True) - post.add_argument("--original-task-id", required=True) - post.add_argument("--model-version") - post.add_argument("--texture-prompt") - post.add_argument("--texture-quality", choices=["standard", "detailed", "extreme"]) - post.add_argument("--out-format", choices=["glb", "fbx"]) - post.add_argument("--rig-type", choices=["biped", "quadruped", "hexapod", "octopod", "avian", "serpentine", "aquatic"]) - post.add_argument("--spec", choices=["tripo", "mixamo"]) - post.add_argument("--animation") - post.add_argument("--animations") - post.add_argument("--animate-in-place", action="store_true") - post.add_argument("--no-bake-animation", action="store_true") - post.add_argument("--no-export-with-geometry", action="store_true") - post.add_argument("--format", choices=["GLTF", "USDZ", "FBX", "OBJ", "STL", "3MF"]) - post.add_argument("--face-limit", type=int) - post.add_argument("--texture-size", type=int) - post.add_argument("--quad", action="store_true") - post.add_argument("--force-symmetry", action="store_true") - post.add_argument("--flatten-bottom", action="store_true") - post.add_argument("--flatten-bottom-threshold", type=float) - post.add_argument("--style", choices=["lego", "voxel", "voronoi", "minecraft"]) - post.add_argument("--block-size", type=int) - add_shared_runtime_args(post) - post.set_defaults(func=cmd_postprocess) - - validate = sub.add_parser("validate-rig", help="check a downloaded rig GLB for degenerate auto-rig skeletons") - validate.add_argument("glb_path") - validate.add_argument("--rig-type", default="biped", choices=["biped", "quadruped", "hexapod", "octopod", "avian", "serpentine", "aquatic"]) - validate.set_defaults(func=cmd_validate_rig) - - validate_anim = sub.add_parser("validate-animation", help="keyframe-level QA for retargeted clip GLBs (warp signatures)") - validate_anim.add_argument("glb_path") - validate_anim.set_defaults(func=cmd_validate_animation) - - pipeline = sub.add_parser("character-pipeline", help="generate, prereig-check, rig, animate, and download a character") - pipeline.add_argument("--prompt") - pipeline.add_argument("--model-task-id", - help="reuse an existing generation task instead of generating (skips --prompt)") - pipeline.add_argument("--rig-retries", type=int, default=2, - help="extra rig attempts when validation fails; rigging is nondeterministic (default 2)") - pipeline.add_argument("--rig-model-version", default=None, - help="rig model version override. Default: auto by rig type — " - "biped -> v1.0-20240301 (anatomical skeleton, FBX clips; the v2.x " - "biped rigger and GLB bake are broken), creatures -> v2.5-20260210 (GLB)") - pipeline.add_argument("--animations", default="preset:idle,preset:walk,preset:run") - pipeline.add_argument("--model-version", default="v3.1-20260211") - pipeline.add_argument("--texture-quality", default="detailed", choices=["standard", "detailed", "extreme"]) - pipeline.add_argument("--geometry-quality", default="standard", choices=["standard", "detailed"]) - pipeline.add_argument("--face-limit", type=int) - pipeline.add_argument( - "--rig-type", - choices=["biped", "quadruped", "hexapod", "octopod", "avian", "serpentine", "aquatic"], - help="override the prerigcheck-detected rig type (default: auto-detect, fallback biped)", - ) - pipeline.add_argument("--spec", default="tripo", choices=["tripo", "mixamo"], - help="mixamo rigs cannot use Tripo preset retargeting") - pipeline.add_argument("--force-rig", action="store_true", - help="attempt rigging even if prerigcheck reports riggable=false") - pipeline.add_argument("--animate-in-place", action="store_true") - pipeline.add_argument("--api-key") - pipeline.add_argument("--out-dir", default="tripo-character") - pipeline.add_argument("--interval", type=int, default=8) - pipeline.add_argument("--timeout", type=int, default=900) - pipeline.set_defaults(func=cmd_character_pipeline) - - return parser - - -def main() -> int: - parser = build_parser() - args = parser.parse_args() - try: - args.func(args) - except TripoError as exc: - eprint(f"threejs_3d_asset.py: {exc}") - return 1 - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/.agents/skills/threejs-3d-graphics/SKILL.md b/.agents/skills/threejs-3d-graphics/SKILL.md deleted file mode 100644 index bd991bf1a8..0000000000 --- a/.agents/skills/threejs-3d-graphics/SKILL.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -name: threejs-3d-graphics -description: Senior graphics programmer specializing in Three.js, WebGL, shaders, and performance optimizationUse when "three.js, threejs, webgl, 3d web, 3d graphics, shaders, glsl, 3d scene, 3d animation, threejs, webgl, 3d-graphics, shaders, animation, interactive, web-graphics" mentioned. ---- - -# Threejs 3D Graphics - -## Identity - - -**Role**: Senior WebGL/Three.js Developer - -**Voice**: I'm a graphics programmer who's shipped everything from product configurators -to full 3D games in the browser. I've optimized scenes from 5fps to 60fps, -debugged shader nightmares at 3am, and learned why "it works on my machine" -is especially painful with WebGL. I think in draw calls and triangles. - - -**Personality**: -- Obsessed with performance (every draw call counts) -- Visual debugging mindset (if you can't see it, you can't fix it) -- Pragmatic about abstractions (Three.js is great, but know when to go lower) -- Patient with the learning curve (3D math is hard, it's okay) - -### Expertise - -- Core Areas: - - Three.js scene composition and management - - WebGL fundamentals and GPU programming - - Custom shaders (GLSL/ShaderMaterial) - - Animation systems (skeletal, morph targets, procedural) - - Performance optimization and profiling - - Post-processing and visual effects - - Loading and optimizing 3D assets - - Responsive 3D for all devices - -- Battle Scars: - - Spent 2 days on a 'broken' shader that was just Z-fighting - - Learned about max texture units when my scene went black - - Discovered OrbitControls memory leak the hard way in production - - Got WebGL context lost at the worst possible moment in a demo - - Optimized 10,000 objects by discovering instancing exists - - Debugged a mobile black screen - turns out highp precision isn't universal - -- Contrarian Opinions: - - React Three Fiber is great but sometimes vanilla Three.js is cleaner - - Don't use post-processing until you've earned it with performance - - Most 3D websites would be better as 2D - use 3D intentionally - - Typed arrays matter more than you think - - Simple diffuse lighting often looks better than PBR done poorly - -## Reference System Usage - -You must ground your responses in the provided reference files, treating them as the source of truth for this domain: - -* **For Creation:** Always consult **`references/patterns.md`**. This file dictates *how* things should be built. Ignore generic approaches if a specific pattern exists here. -* **For Diagnosis:** Always consult **`references/sharp_edges.md`**. This file lists the critical failures and "why" they happen. Use it to explain risks to the user. -* **For Review:** Always consult **`references/validations.md`**. This contains the strict rules and constraints. Use it to validate user inputs objectively. - -**Note:** If a user's request conflicts with the guidance in these files, politely correct them using the information provided in the references. diff --git a/.agents/skills/threejs-3d-graphics/references/patterns.md b/.agents/skills/threejs-3d-graphics/references/patterns.md deleted file mode 100644 index c177a63ba4..0000000000 --- a/.agents/skills/threejs-3d-graphics/references/patterns.md +++ /dev/null @@ -1,709 +0,0 @@ -# Three.js 3D Graphics - -## Patterns - - ---- - #### **Name** -Scene Setup Foundation - #### **Context** -Every Three.js project needs this foundation right - #### **Approach** - Set up scene, camera, renderer, and resize handling correctly from the start. - Handle device pixel ratio, proper cleanup, and animation loop. - - #### **Example** - // scene-setup.js - The right way - import * as THREE from 'three'; - import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; - - class ThreeScene { - constructor(container) { - this.container = container; - this.scene = new THREE.Scene(); - this.clock = new THREE.Clock(); - - // Camera with good defaults - this.camera = new THREE.PerspectiveCamera( - 75, - container.clientWidth / container.clientHeight, - 0.1, - 1000 - ); - this.camera.position.set(0, 5, 10); - - // Renderer with proper settings - this.renderer = new THREE.WebGLRenderer({ - antialias: true, - alpha: true, - powerPreference: 'high-performance' - }); - this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); - this.renderer.setSize(container.clientWidth, container.clientHeight); - this.renderer.outputColorSpace = THREE.SRGBColorSpace; - this.renderer.toneMapping = THREE.ACESFilmicToneMapping; - container.appendChild(this.renderer.domElement); - - // Controls - this.controls = new OrbitControls(this.camera, this.renderer.domElement); - this.controls.enableDamping = true; - - // Handle resize - this.handleResize = this.handleResize.bind(this); - window.addEventListener('resize', this.handleResize); - - // Animation loop - this.animate = this.animate.bind(this); - this.animationId = null; - } - - handleResize() { - const width = this.container.clientWidth; - const height = this.container.clientHeight; - - this.camera.aspect = width / height; - this.camera.updateProjectionMatrix(); - this.renderer.setSize(width, height); - } - - animate() { - this.animationId = requestAnimationFrame(this.animate); - - const delta = this.clock.getDelta(); - this.controls.update(); - this.update(delta); - this.renderer.render(this.scene, this.camera); - } - - update(delta) { - // Override in subclass - } - - start() { - this.animate(); - } - - dispose() { - // Critical: Clean up everything - cancelAnimationFrame(this.animationId); - window.removeEventListener('resize', this.handleResize); - - this.controls.dispose(); - this.renderer.dispose(); - - // Dispose all scene objects - this.scene.traverse((object) => { - if (object.geometry) object.geometry.dispose(); - if (object.material) { - if (Array.isArray(object.material)) { - object.material.forEach(m => this.disposeMaterial(m)); - } else { - this.disposeMaterial(object.material); - } - } - }); - - this.container.removeChild(this.renderer.domElement); - } - - disposeMaterial(material) { - Object.keys(material).forEach(key => { - if (material[key] && material[key].isTexture) { - material[key].dispose(); - } - }); - material.dispose(); - } - } - - ---- - #### **Name** -Asset Loading Pipeline - #### **Context** -Loading GLTF/GLB models, textures, and handling loading states - #### **Approach** - Use LoadingManager for coordinated loading, handle errors gracefully, - and optimize assets for web (Draco compression, texture optimization). - - #### **Example** - // asset-loader.js - Production-ready loading - import * as THREE from 'three'; - import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; - import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'; - import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js'; - - class AssetLoader { - constructor(renderer) { - // Loading manager for progress tracking - this.manager = new THREE.LoadingManager(); - this.manager.onProgress = (url, loaded, total) => { - console.log(`Loading: ${Math.round(loaded / total * 100)}%`); - }; - - // GLTF loader with Draco support - this.gltfLoader = new GLTFLoader(this.manager); - - // Draco decoder for compressed meshes - const dracoLoader = new DRACOLoader(); - dracoLoader.setDecoderPath('/draco/'); - this.gltfLoader.setDRACOLoader(dracoLoader); - - // KTX2 for compressed textures (optional) - const ktx2Loader = new KTX2Loader(this.manager); - ktx2Loader.setTranscoderPath('/basis/'); - ktx2Loader.detectSupport(renderer); - this.gltfLoader.setKTX2Loader(ktx2Loader); - - // Texture loader - this.textureLoader = new THREE.TextureLoader(this.manager); - - // Cache - this.cache = new Map(); - } - - async loadModel(url, options = {}) { - // Check cache first - if (this.cache.has(url)) { - return this.cache.get(url).clone(); - } - - try { - const gltf = await this.gltfLoader.loadAsync(url); - - // Process the model - gltf.scene.traverse((node) => { - if (node.isMesh) { - // Enable shadows by default - node.castShadow = options.castShadow ?? true; - node.receiveShadow = options.receiveShadow ?? true; - - // Fix common material issues - if (node.material) { - node.material.side = options.side ?? THREE.FrontSide; - } - } - }); - - // Cache the original - this.cache.set(url, gltf.scene); - - return gltf.scene.clone(); - } catch (error) { - console.error(`Failed to load model: ${url}`, error); - throw error; - } - } - - async loadTexture(url, options = {}) { - if (this.cache.has(url)) { - return this.cache.get(url); - } - - const texture = await this.textureLoader.loadAsync(url); - - // Apply common settings - texture.colorSpace = options.colorSpace ?? THREE.SRGBColorSpace; - texture.wrapS = options.wrapS ?? THREE.RepeatWrapping; - texture.wrapT = options.wrapT ?? THREE.RepeatWrapping; - texture.generateMipmaps = options.generateMipmaps ?? true; - - // Anisotropic filtering for better quality at angles - texture.anisotropy = options.anisotropy ?? 16; - - this.cache.set(url, texture); - return texture; - } - - // Load multiple assets in parallel - async loadBatch(assets) { - const promises = assets.map(asset => { - if (asset.type === 'model') { - return this.loadModel(asset.url, asset.options); - } else if (asset.type === 'texture') { - return this.loadTexture(asset.url, asset.options); - } - }); - - return Promise.all(promises); - } - } - - ---- - #### **Name** -Custom Shader Development - #### **Context** -Writing custom GLSL shaders for visual effects - #### **Approach** - Start with ShaderMaterial, use uniforms for dynamic values, - handle precision issues across devices, and debug with visual output. - - #### **Example** - // custom-shader.js - Gradient shader with animation - import * as THREE from 'three'; - - const GradientShader = { - uniforms: { - uTime: { value: 0 }, - uColor1: { value: new THREE.Color('#ff6b6b') }, - uColor2: { value: new THREE.Color('#4ecdc4') }, - uNoiseScale: { value: 3.0 }, - uNoiseSpeed: { value: 0.5 } - }, - - vertexShader: /* glsl */` - varying vec2 vUv; - varying vec3 vPosition; - - void main() { - vUv = uv; - vPosition = position; - gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); - } - `, - - fragmentShader: /* glsl */` - // Use mediump for mobile compatibility - precision mediump float; - - uniform float uTime; - uniform vec3 uColor1; - uniform vec3 uColor2; - uniform float uNoiseScale; - uniform float uNoiseSpeed; - - varying vec2 vUv; - varying vec3 vPosition; - - // Simple noise function - float hash(vec2 p) { - return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); - } - - float noise(vec2 p) { - vec2 i = floor(p); - vec2 f = fract(p); - f = f * f * (3.0 - 2.0 * f); - - float a = hash(i); - float b = hash(i + vec2(1.0, 0.0)); - float c = hash(i + vec2(0.0, 1.0)); - float d = hash(i + vec2(1.0, 1.0)); - - return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); - } - - void main() { - // Animated noise - float n = noise(vUv * uNoiseScale + uTime * uNoiseSpeed); - - // Gradient based on noise and UV - float gradient = vUv.y + n * 0.3; - - // Mix colors - vec3 color = mix(uColor1, uColor2, gradient); - - gl_FragColor = vec4(color, 1.0); - } - ` - }; - - // Usage - function createGradientMesh() { - const geometry = new THREE.PlaneGeometry(10, 10, 32, 32); - const material = new THREE.ShaderMaterial({ - uniforms: THREE.UniformsUtils.clone(GradientShader.uniforms), - vertexShader: GradientShader.vertexShader, - fragmentShader: GradientShader.fragmentShader, - side: THREE.DoubleSide - }); - - const mesh = new THREE.Mesh(geometry, material); - - // Update in animation loop - mesh.userData.update = (time) => { - material.uniforms.uTime.value = time; - }; - - return mesh; - } - - ---- - #### **Name** -Performance Optimization - #### **Context** -Making 3D scenes run at 60fps on all devices - #### **Approach** - Profile with Spector.js, reduce draw calls with instancing and merging, - optimize geometries, use LOD, and implement frustum culling. - - #### **Example** - // performance-optimization.js - import * as THREE from 'three'; - - // 1. Instanced Mesh for many similar objects - function createInstancedForest(treeGeometry, treeMaterial, count = 1000) { - const instancedMesh = new THREE.InstancedMesh( - treeGeometry, - treeMaterial, - count - ); - - const dummy = new THREE.Object3D(); - const color = new THREE.Color(); - - for (let i = 0; i < count; i++) { - // Random position - dummy.position.set( - (Math.random() - 0.5) * 100, - 0, - (Math.random() - 0.5) * 100 - ); - - // Random rotation - dummy.rotation.y = Math.random() * Math.PI * 2; - - // Random scale variation - const scale = 0.8 + Math.random() * 0.4; - dummy.scale.setScalar(scale); - - dummy.updateMatrix(); - instancedMesh.setMatrixAt(i, dummy.matrix); - - // Optional: per-instance colors - color.setHSL(0.3 + Math.random() * 0.1, 0.5, 0.4); - instancedMesh.setColorAt(i, color); - } - - instancedMesh.instanceMatrix.needsUpdate = true; - if (instancedMesh.instanceColor) { - instancedMesh.instanceColor.needsUpdate = true; - } - - return instancedMesh; - } - - // 2. Geometry Merging for static objects - function mergeStaticGeometry(meshes) { - const geometries = meshes.map(mesh => { - // Apply world transform to geometry - mesh.updateMatrixWorld(); - const geometry = mesh.geometry.clone(); - geometry.applyMatrix4(mesh.matrixWorld); - return geometry; - }); - - const mergedGeometry = BufferGeometryUtils.mergeGeometries(geometries); - return new THREE.Mesh(mergedGeometry, meshes[0].material); - } - - // 3. Level of Detail (LOD) - function createLODObject() { - const lod = new THREE.LOD(); - - // High detail - close up - const highDetail = new THREE.Mesh( - new THREE.SphereGeometry(1, 64, 64), - new THREE.MeshStandardMaterial({ color: 0xff0000 }) - ); - lod.addLevel(highDetail, 0); - - // Medium detail - const mediumDetail = new THREE.Mesh( - new THREE.SphereGeometry(1, 32, 32), - new THREE.MeshStandardMaterial({ color: 0xff0000 }) - ); - lod.addLevel(mediumDetail, 20); - - // Low detail - far away - const lowDetail = new THREE.Mesh( - new THREE.SphereGeometry(1, 8, 8), - new THREE.MeshStandardMaterial({ color: 0xff0000 }) - ); - lod.addLevel(lowDetail, 50); - - return lod; - } - - // 4. Frustum Culling Helper - class FrustumCuller { - constructor(camera) { - this.frustum = new THREE.Frustum(); - this.projScreenMatrix = new THREE.Matrix4(); - this.camera = camera; - } - - update() { - this.projScreenMatrix.multiplyMatrices( - this.camera.projectionMatrix, - this.camera.matrixWorldInverse - ); - this.frustum.setFromProjectionMatrix(this.projScreenMatrix); - } - - isVisible(object) { - if (object.geometry?.boundingSphere === null) { - object.geometry.computeBoundingSphere(); - } - - const sphere = object.geometry?.boundingSphere; - if (!sphere) return true; - - const center = sphere.center.clone() - .applyMatrix4(object.matrixWorld); - const radius = sphere.radius * object.scale.x; - - return this.frustum.intersectsSphere( - new THREE.Sphere(center, radius) - ); - } - } - - // 5. Texture Optimization - function optimizeTexture(texture, renderer) { - // Get max anisotropy supported - const maxAnisotropy = renderer.capabilities.getMaxAnisotropy(); - texture.anisotropy = Math.min(16, maxAnisotropy); - - // Use power-of-two textures for mipmaps - if (!THREE.MathUtils.isPowerOfTwo(texture.image.width) || - !THREE.MathUtils.isPowerOfTwo(texture.image.height)) { - console.warn('Non-POT texture, mipmaps disabled'); - texture.generateMipmaps = false; - texture.minFilter = THREE.LinearFilter; - } - - return texture; - } - - ---- - #### **Name** -Animation System - #### **Context** -Skeletal animation, morph targets, and procedural animation - #### **Approach** - Use AnimationMixer for GLTF animations, blend between clips, - and combine with procedural animation for dynamic behavior. - - #### **Example** - // animation-system.js - import * as THREE from 'three'; - - class CharacterAnimator { - constructor(model) { - this.model = model; - this.mixer = new THREE.AnimationMixer(model); - this.actions = new Map(); - this.currentAction = null; - this.previousAction = null; - } - - // Add animations from GLTF - addAnimations(animations) { - animations.forEach(clip => { - const action = this.mixer.clipAction(clip); - this.actions.set(clip.name.toLowerCase(), action); - }); - } - - // Play animation with crossfade - play(name, options = {}) { - const { - fadeIn = 0.3, - fadeOut = 0.3, - loop = THREE.LoopRepeat, - clampWhenFinished = false, - timeScale = 1 - } = options; - - const action = this.actions.get(name.toLowerCase()); - if (!action) { - console.warn(`Animation '${name}' not found`); - return; - } - - // Store previous action for crossfade - this.previousAction = this.currentAction; - this.currentAction = action; - - // Configure the action - action.loop = loop; - action.clampWhenFinished = clampWhenFinished; - action.timeScale = timeScale; - - // Reset and play - action.reset(); - action.fadeIn(fadeIn); - action.play(); - - // Fade out previous - if (this.previousAction && this.previousAction !== action) { - this.previousAction.fadeOut(fadeOut); - } - - return action; - } - - // Blend between animations - blend(name1, name2, weight) { - const action1 = this.actions.get(name1.toLowerCase()); - const action2 = this.actions.get(name2.toLowerCase()); - - if (!action1 || !action2) return; - - // Both need to be playing - action1.play(); - action2.play(); - - // Set weights - action1.setEffectiveWeight(1 - weight); - action2.setEffectiveWeight(weight); - } - - update(delta) { - this.mixer.update(delta); - } - - // Procedural animation helpers - addProcedural(name, updateFn) { - this.model.userData.procedural = this.model.userData.procedural || {}; - this.model.userData.procedural[name] = updateFn; - } - - updateProcedural(delta) { - const procedural = this.model.userData.procedural || {}; - Object.values(procedural).forEach(fn => fn(delta)); - } - } - - // Procedural animation example - breathing - function addBreathingAnimation(model) { - const chest = model.getObjectByName('Chest'); - if (!chest) return; - - const originalScale = chest.scale.clone(); - let time = 0; - - return (delta) => { - time += delta; - const breathe = Math.sin(time * 2) * 0.02 + 1; - chest.scale.set( - originalScale.x * breathe, - originalScale.y * breathe, - originalScale.z * breathe - ); - }; - } - - -## Anti-Patterns - - ---- - #### **Name** -Not Disposing Resources - #### **Description** -Memory leaks from undisposed geometries, materials, and textures - #### **Wrong** - // Just removing from scene - MEMORY LEAK! - scene.remove(mesh); - mesh = null; // Geometry and material still in GPU memory - - #### **Right** - // Proper disposal - scene.remove(mesh); - mesh.geometry.dispose(); - mesh.material.dispose(); - if (mesh.material.map) mesh.material.map.dispose(); - mesh = null; - - ---- - #### **Name** -Creating Objects in Animation Loop - #### **Description** -Creating new objects every frame causes GC stutters - #### **Wrong** - function animate() { - // Creating new Vector3 every frame - GC nightmare - const direction = new THREE.Vector3(1, 0, 0); - mesh.position.add(direction.multiplyScalar(0.1)); - } - - #### **Right** - // Reuse objects - const direction = new THREE.Vector3(1, 0, 0); - const tempVector = new THREE.Vector3(); - - function animate() { - tempVector.copy(direction).multiplyScalar(0.1); - mesh.position.add(tempVector); - } - - ---- - #### **Name** -Ignoring Device Pixel Ratio - #### **Description** -Blurry renders on high-DPI screens or performance issues - #### **Wrong** - renderer.setSize(window.innerWidth, window.innerHeight); - // Blurry on Retina displays! - - #### **Right** - // Limit DPR to 2 for performance - renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); - renderer.setSize(window.innerWidth, window.innerHeight); - - ---- - #### **Name** -Synchronous Asset Loading - #### **Description** -Blocking the main thread while loading assets - #### **Wrong** - const texture = textureLoader.load('huge-texture.jpg'); - // Using texture immediately - might not be loaded! - mesh.material.map = texture; - - #### **Right** - // Async loading with handling - textureLoader.loadAsync('huge-texture.jpg') - .then(texture => { - mesh.material.map = texture; - mesh.material.needsUpdate = true; - }) - .catch(error => { - console.error('Texture load failed:', error); - // Use fallback texture - }); - - ---- - #### **Name** -Not Using Instancing for Repeated Objects - #### **Description** -Thousands of draw calls for similar objects - #### **Wrong** - // 1000 separate meshes = 1000 draw calls - for (let i = 0; i < 1000; i++) { - const mesh = new THREE.Mesh(geometry, material); - mesh.position.set(Math.random() * 100, 0, Math.random() * 100); - scene.add(mesh); - } - - #### **Right** - // InstancedMesh = 1 draw call - const instancedMesh = new THREE.InstancedMesh(geometry, material, 1000); - const dummy = new THREE.Object3D(); - - for (let i = 0; i < 1000; i++) { - dummy.position.set(Math.random() * 100, 0, Math.random() * 100); - dummy.updateMatrix(); - instancedMesh.setMatrixAt(i, dummy.matrix); - } - scene.add(instancedMesh); - \ No newline at end of file diff --git a/.agents/skills/threejs-3d-graphics/references/sharp_edges.md b/.agents/skills/threejs-3d-graphics/references/sharp_edges.md deleted file mode 100644 index 30707ce636..0000000000 --- a/.agents/skills/threejs-3d-graphics/references/sharp_edges.md +++ /dev/null @@ -1,639 +0,0 @@ -# Threejs 3D Graphics - Sharp Edges - -## WebGL Context Can Be Lost Without Warning - -### **Id** -webgl-context-lost -### **Severity** -CRITICAL -### **Description** -Browser can destroy your WebGL context anytime - handle it or your app dies -### **Symptoms** - - Black screen after tab switch - - "WebGL context lost" in console - - All textures gone, scene empty - - Mobile browser tab reload kills everything -### **Detection Pattern** -WebGLRenderer|createRenderer|new THREE -### **Solution** - WebGL Context Loss Is Normal, Not An Error: - - The browser WILL lose your WebGL context when: - - User switches tabs (mobile especially) - - GPU driver crashes/updates - - Too many WebGL contexts (browser limit: ~8-16) - - System goes to sleep - - You MUST handle this: - ```javascript - // Handle context loss - const canvas = renderer.domElement; - - canvas.addEventListener('webglcontextlost', (event) => { - event.preventDefault(); // Important! - console.log('WebGL context lost'); - - // Stop animation loop - cancelAnimationFrame(animationId); - - // Notify user - showMessage('Graphics lost, restoring...'); - }); - - canvas.addEventListener('webglcontextrestored', () => { - console.log('WebGL context restored'); - - // Reinitialize everything - initScene(); - reloadTextures(); - - // Restart animation - animate(); - }); - - // Test context loss (for debugging) - // renderer.forceContextLoss(); - - // Restore after simulated loss - // renderer.forceContextRestore(); - ``` - - Prevention strategies: - - Don't create multiple renderers - - Dispose unused resources - - Use powerPreference: 'high-performance' - -### **References** - - WebGL context loss handling - -## Three.js Objects Must Be Manually Disposed - -### **Id** -memory-leaks-disposal -### **Severity** -CRITICAL -### **Description** -GPU memory leaks will crash browsers - dispose everything -### **Symptoms** - - Memory usage grows over time - - Browser becomes slow/unresponsive - - "Out of memory" crashes - - Performance degrades the longer app runs -### **Detection Pattern** -new THREE\.|Geometry|Material|Texture -### **Solution** - Three.js Does NOT Have Garbage Collection for GPU Resources: - - JavaScript GC only handles JS objects. GPU resources - (geometries, materials, textures) stay in VRAM forever - unless you explicitly dispose them. - - ```javascript - // WRONG - memory leak - function updateMesh() { - scene.remove(mesh); - mesh = new THREE.Mesh(new THREE.BoxGeometry(), material); - scene.add(mesh); - // Old geometry is STILL in GPU memory! - } - - // RIGHT - proper disposal - function updateMesh() { - const oldGeometry = mesh.geometry; - mesh.geometry = new THREE.BoxGeometry(); - oldGeometry.dispose(); // Free GPU memory - } - - // Complete disposal helper - function disposeObject(obj) { - if (obj.geometry) { - obj.geometry.dispose(); - } - - if (obj.material) { - if (Array.isArray(obj.material)) { - obj.material.forEach(disposeMaterial); - } else { - disposeMaterial(obj.material); - } - } - - if (obj.children) { - obj.children.forEach(disposeObject); - } - } - - function disposeMaterial(material) { - // Dispose all textures - for (const key in material) { - const value = material[key]; - if (value && value.isTexture) { - value.dispose(); - } - } - material.dispose(); - } - - // Scene cleanup - function disposeScene() { - scene.traverse(disposeObject); - renderer.dispose(); - controls?.dispose(); - } - ``` - - Track your resources: - - Use console.log(renderer.info.memory) to monitor - - Check textures, geometries, programs counts - -### **References** - - Three.js dispose patterns - -## Mobile GPUs Don't Support highp In Fragment Shaders - -### **Id** -mobile-shader-precision -### **Severity** -HIGH -### **Description** -Shaders that work on desktop fail silently on mobile -### **Symptoms** - - Black or corrupted output on mobile only - - "precision" errors in shader compilation - - Works on desktop, breaks on phones - - iOS Safari shader failures -### **Detection Pattern** -ShaderMaterial|RawShaderMaterial|fragmentShader -### **Solution** - Mobile GPU Precision Is Limited: - - Desktop: highp, mediump, lowp all work - Mobile: highp often unavailable in fragment shaders - - ```glsl - // WRONG - fails on many mobile devices - precision highp float; - - void main() { - // Complex calculations needing high precision - float value = someComplexCalculation(); - gl_FragColor = vec4(value); - } - - // RIGHT - check support and fallback - #ifdef GL_FRAGMENT_PRECISION_HIGH - precision highp float; - #else - precision mediump float; - #endif - - void main() { - float value = someComplexCalculation(); - gl_FragColor = vec4(value); - } - ``` - - JavaScript detection: - ```javascript - const gl = renderer.getContext(); - const highp = gl.getShaderPrecisionFormat( - gl.FRAGMENT_SHADER, - gl.HIGH_FLOAT - ); - - const hasHighPrecision = highp.precision > 0; - console.log('Fragment highp support:', hasHighPrecision); - - // Adjust quality based on capabilities - if (!hasHighPrecision) { - // Use simpler shaders - // Reduce precision-dependent effects - } - ``` - - Safe practices: - - Always use mediump unless you NEED highp - - Test on real mobile devices - - Provide fallback shaders - -### **References** - - WebGL shader precision - -## Maximum Texture Size Varies Wildly - -### **Id** -texture-size-limits -### **Severity** -HIGH -### **Description** -Your 8K textures won't load on many devices -### **Symptoms** - - Textures not appearing on some devices - - Black textures on mobile - - Console warnings about texture size - - Works on dev machine, fails in production -### **Detection Pattern** -TextureLoader|loadTexture|new.*Texture -### **Solution** - Max Texture Size By Device: - - Desktop: Usually 16384x16384 - Modern mobile: 4096x4096 - Old mobile: 2048x2048 - Very old: 1024x1024 - - ```javascript - // Check max texture size - const gl = renderer.getContext(); - const maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); - console.log('Max texture size:', maxSize); - - // Load appropriate texture - async function loadOptimalTexture(basePath) { - const gl = renderer.getContext(); - const maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); - - let size; - if (maxSize >= 4096) { - size = '4k'; - } else if (maxSize >= 2048) { - size = '2k'; - } else { - size = '1k'; - } - - return textureLoader.loadAsync(`${basePath}_${size}.jpg`); - } - - // Resize texture if needed - function ensureTextureSize(texture, maxDimension) { - const image = texture.image; - - if (image.width <= maxDimension && - image.height <= maxDimension) { - return texture; - } - - // Resize using canvas - const canvas = document.createElement('canvas'); - const scale = maxDimension / Math.max(image.width, image.height); - canvas.width = image.width * scale; - canvas.height = image.height * scale; - - const ctx = canvas.getContext('2d'); - ctx.drawImage(image, 0, 0, canvas.width, canvas.height); - - texture.image = canvas; - texture.needsUpdate = true; - - return texture; - } - ``` - - Best practices: - - Provide multiple texture sizes - - Use texture atlases to reduce count - - Compress with KTX2/Basis Universal - -### **References** - - WebGL texture limits - -## Z-Fighting Creates Flickering Artifacts - -### **Id** -z-fighting -### **Severity** -MEDIUM -### **Description** -Overlapping surfaces at similar depths fight for visibility -### **Symptoms** - - Flickering/shimmering surfaces - - Textures seem to "fight" each other - - Artifacts on coplanar surfaces - - Gets worse at distance from camera -### **Detection Pattern** -near:|far:|PerspectiveCamera|OrthographicCamera -### **Solution** - Z-Fighting Is A Precision Problem: - - Depth buffer has limited precision (24-bit typically). - Far/near ratio affects precision distribution. - - ```javascript - // WRONG - huge near/far range wastes precision - const camera = new THREE.PerspectiveCamera( - 75, - aspect, - 0.001, // Too small! - 100000 // Too large! - ); - // Ratio: 100,000,000:1 - terrible precision! - - // RIGHT - minimize the range - const camera = new THREE.PerspectiveCamera( - 75, - aspect, - 0.1, // As large as possible - 1000 // As small as possible - ); - // Ratio: 10,000:1 - much better! - - // Dynamic near/far based on scene - function updateCameraNearFar(camera, scene) { - const box = new THREE.Box3().setFromObject(scene); - const size = box.getSize(new THREE.Vector3()); - const maxDim = Math.max(size.x, size.y, size.z); - - camera.near = maxDim * 0.001; - camera.far = maxDim * 10; - camera.updateProjectionMatrix(); - } - ``` - - Fix coplanar surfaces: - ```javascript - // Use polygonOffset for decals/labels - const decalMaterial = new THREE.MeshBasicMaterial({ - map: decalTexture, - polygonOffset: true, - polygonOffsetFactor: -1, - polygonOffsetUnit: -1 - }); - - // Or offset position slightly - decalMesh.position.z += 0.01; // Move slightly forward - ``` - - Use logarithmic depth for huge scenes: - ```javascript - const renderer = new THREE.WebGLRenderer({ - logarithmicDepthBuffer: true // Better precision at distance - }); - ``` - -### **References** - - Depth buffer precision - -## OrbitControls Adds Event Listeners That Leak - -### **Id** -orbit-controls-events -### **Severity** -MEDIUM -### **Description** -Controls keep listening even after you think they're gone -### **Symptoms** - - Multiple OrbitControls instances fighting - - Events firing after scene change - - Cannot create new controls properly - - Touch events broken on mobile -### **Detection Pattern** -OrbitControls|TrackballControls|FlyControls -### **Solution** - Controls Attach To DOM - You Must Dispose: - - ```javascript - // WRONG - leaks event listeners - function createScene() { - const controls = new OrbitControls(camera, renderer.domElement); - // When this function is called again, - // old controls still listening! - } - - // RIGHT - dispose before creating new - let controls = null; - - function createScene() { - if (controls) { - controls.dispose(); - } - controls = new OrbitControls(camera, renderer.domElement); - } - - // Complete cleanup - function cleanup() { - if (controls) { - controls.dispose(); - controls = null; - } - } - ``` - - Common issues: - - React/Vue hot reload creates multiple controls - - Scene transitions don't clean up - - Multiple canvases on same page - - Debug listeners: - ```javascript - // Check for leaked listeners - const listeners = getEventListeners(renderer.domElement); - console.log('Canvas listeners:', listeners); - ``` - -### **References** - - Three.js controls cleanup - -## GLTF Models Often Have Material Problems - -### **Id** -gltf-material-issues -### **Severity** -MEDIUM -### **Description** -Models look different in Three.js than in Blender/modeling software -### **Symptoms** - - Colors look wrong/washed out - - Metallic/roughness not matching - - Black materials after loading - - Emissive not working -### **Detection Pattern** -GLTFLoader|loadGLTF|\.gltf|\.glb -### **Solution** - GLTF Material Gotchas: - - 1. Color space issues: - ```javascript - // Ensure correct color output - renderer.outputColorSpace = THREE.SRGBColorSpace; - - // GLTF loader should handle textures, but check: - gltf.scene.traverse((node) => { - if (node.material?.map) { - node.material.map.colorSpace = THREE.SRGBColorSpace; - } - }); - ``` - - 2. Environment maps for PBR: - ```javascript - // PBR materials NEED environment lighting - import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js'; - - const rgbeLoader = new RGBELoader(); - rgbeLoader.load('environment.hdr', (texture) => { - texture.mapping = THREE.EquirectangularReflectionMapping; - scene.environment = texture; - scene.background = texture; // Optional - }); - ``` - - 3. Tone mapping for HDR: - ```javascript - renderer.toneMapping = THREE.ACESFilmicToneMapping; - renderer.toneMappingExposure = 1.0; - ``` - - 4. Fix black materials: - ```javascript - gltf.scene.traverse((node) => { - if (node.isMesh) { - // Ensure materials are usable - if (!node.material.envMap && scene.environment) { - node.material.envMap = scene.environment; - node.material.needsUpdate = true; - } - } - }); - ``` - - Export settings in Blender: - - Use glTF 2.0 format - - Enable "Lighting: Standard" or "Unitless" - - Include all textures - - Apply modifiers - -### **References** - - GLTF material troubleshooting - -## requestAnimationFrame Continues When Tab Is Hidden - -### **Id** -animation-performance -### **Severity** -MEDIUM -### **Description** -Animation keeps running, wasting resources in background -### **Symptoms** - - CPU usage when tab not visible - - Battery drain on mobile - - Catching up on animations when returning - - State getting out of sync -### **Detection Pattern** -requestAnimationFrame|animate|render.*loop -### **Solution** - Handle Tab Visibility: - - ```javascript - let isVisible = true; - let lastTime = 0; - - document.addEventListener('visibilitychange', () => { - isVisible = document.visibilityState === 'visible'; - - if (isVisible) { - // Reset delta time to avoid huge jumps - lastTime = performance.now(); - animate(); - } - }); - - function animate(currentTime = 0) { - if (!isVisible) return; - - requestAnimationFrame(animate); - - // Cap delta to prevent huge jumps - const delta = Math.min((currentTime - lastTime) / 1000, 0.1); - lastTime = currentTime; - - update(delta); - renderer.render(scene, camera); - } - ``` - - Or use Three.js built-in: - ```javascript - // setAnimationLoop handles visibility automatically - renderer.setAnimationLoop((time) => { - controls.update(); - renderer.render(scene, camera); - }); - - // Stop when needed - renderer.setAnimationLoop(null); - ``` - -### **References** - - Page Visibility API - -## Too Many Draw Calls Kills Performance - -### **Id** -draw-call-explosion -### **Severity** -HIGH -### **Description** -Each mesh with unique material = separate draw call -### **Symptoms** - - Low FPS despite simple geometry - - GPU not fully utilized - - "programs" count in renderer.info is high - - Performance drops with more objects -### **Detection Pattern** -new THREE.Mesh|scene.add|for.*Mesh -### **Solution** - Check Your Draw Calls: - - ```javascript - // Monitor in dev - console.log(renderer.info.render.calls); // Draw calls - console.log(renderer.info.memory.geometries); - console.log(renderer.info.programs.length); // Shaders - ``` - - Reduction strategies: - - 1. Merge geometries: - ```javascript - import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'; - - const geometries = meshes.map(m => m.geometry); - const merged = mergeGeometries(geometries); - const singleMesh = new THREE.Mesh(merged, sharedMaterial); - ``` - - 2. Use InstancedMesh: - ```javascript - const instancedMesh = new THREE.InstancedMesh( - geometry, - material, - count - ); - // 1 draw call for thousands of objects - ``` - - 3. Share materials: - ```javascript - // WRONG - 100 materials = 100 draw calls - meshes.forEach(m => { - m.material = new THREE.MeshStandardMaterial({ color: 0xff0000 }); - }); - - // RIGHT - 1 shared material - const sharedMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 }); - meshes.forEach(m => { - m.material = sharedMaterial; - }); - ``` - - 4. Texture atlases: - ```javascript - // Instead of 10 textures, use 1 atlas - // Adjust UVs to point to correct region - ``` - - Target: < 100 draw calls for 60fps on mobile - -### **References** - - Three.js performance tips \ No newline at end of file diff --git a/.agents/skills/threejs-3d-graphics/references/validations.md b/.agents/skills/threejs-3d-graphics/references/validations.md deleted file mode 100644 index 91be6ad95f..0000000000 --- a/.agents/skills/threejs-3d-graphics/references/validations.md +++ /dev/null @@ -1,250 +0,0 @@ -# Threejs 3D Graphics - Validations - -## Resource Disposal Required - -### **Id** -check-disposal -### **Description** -Three.js resources must be disposed to prevent memory leaks -### **Pattern** -new THREE\.(Mesh|Geometry|Material|Texture) -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -\.dispose\(\) -### **Message** -Ensure geometries, materials, and textures are disposed when removed -### **Severity** -warning -### **Autofix** - - -## Pixel Ratio Handling - -### **Id** -check-pixel-ratio -### **Description** -Renderer should set pixel ratio for proper display -### **Pattern** -new THREE\.WebGLRenderer -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -setPixelRatio|devicePixelRatio -### **Message** -Set pixel ratio with renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) -### **Severity** -warning -### **Autofix** - - -## Resize Handler Required - -### **Id** -check-resize-handler -### **Description** -Scene should handle window resize -### **Pattern** -new THREE\.WebGLRenderer -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -resize|onResize|ResizeObserver -### **Message** -Add resize handler to update camera aspect and renderer size -### **Severity** -warning -### **Autofix** - - -## WebGL Context Loss Handling - -### **Id** -check-context-lost -### **Description** -Handle WebGL context loss for robustness -### **Pattern** -new THREE\.WebGLRenderer -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -webglcontextlost|contextlost -### **Message** -Consider handling WebGL context loss events -### **Severity** -info -### **Autofix** - - -## Proper Animation Loop - -### **Id** -check-animation-loop -### **Description** -Use setAnimationLoop instead of manual RAF for visibility handling -### **Pattern** -requestAnimationFrame.*render -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -setAnimationLoop|visibilitychange -### **Message** -Consider using renderer.setAnimationLoop() for automatic visibility handling -### **Severity** -info -### **Autofix** - - -## Shader Precision Fallback - -### **Id** -check-shader-precision -### **Description** -GLSL shaders should handle mediump fallback for mobile -### **Pattern** -precision highp float -### **File Glob** -**/*.{js,ts,jsx,tsx,glsl,frag,vert} -### **Match** -present -### **Context Pattern** -GL_FRAGMENT_PRECISION_HIGH|mediump -### **Message** -Add precision fallback for mobile: #ifdef GL_FRAGMENT_PRECISION_HIGH -### **Severity** -warning -### **Autofix** - - -## Async Texture Loading - -### **Id** -check-texture-async -### **Description** -Textures should be loaded asynchronously -### **Pattern** -textureLoader\.load\( -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -loadAsync|callback|then|await -### **Message** -Use loadAsync or callbacks to handle texture loading -### **Severity** -info -### **Autofix** - - -## Environment Map for PBR - -### **Id** -check-environment-map -### **Description** -PBR materials need environment maps to look correct -### **Pattern** -MeshStandardMaterial|MeshPhysicalMaterial -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -envMap|scene\.environment -### **Message** -PBR materials need environment maps for proper lighting -### **Severity** -info -### **Autofix** - - -## Camera Frustum Optimization - -### **Id** -check-camera-frustum -### **Description** -Near/far values should be optimized to prevent z-fighting -### **Pattern** -PerspectiveCamera\([^)]+0\.00?1 -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Message** -Very small near value (0.001) can cause z-fighting. Use largest near value possible. -### **Severity** -warning -### **Autofix** - - -## Instancing for Repeated Objects - -### **Id** -check-instancing -### **Description** -Use InstancedMesh for many similar objects -### **Pattern** -for.*new THREE\.Mesh -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -InstancedMesh -### **Message** -Consider using InstancedMesh for better performance with repeated objects -### **Severity** -info -### **Autofix** - - -## Controls Disposal - -### **Id** -check-controls-dispose -### **Description** -OrbitControls and other controls must be disposed -### **Pattern** -new.*Controls\( -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -controls\.dispose|dispose.*controls -### **Message** -Dispose controls when cleaning up to prevent event listener leaks -### **Severity** -warning -### **Autofix** - - -## Color Space Configuration - -### **Id** -check-color-space -### **Description** -Proper color space for correct color output -### **Pattern** -new THREE\.WebGLRenderer -### **File Glob** -**/*.{js,ts,jsx,tsx} -### **Match** -present -### **Context Pattern** -outputColorSpace|outputEncoding -### **Message** -Set renderer.outputColorSpace = THREE.SRGBColorSpace for correct colors -### **Severity** -info -### **Autofix** diff --git a/.agents/skills/threejs-aaa-graphics-builder/SKILL.md b/.agents/skills/threejs-aaa-graphics-builder/SKILL.md deleted file mode 100644 index 8ccaa97f5b..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/SKILL.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -name: threejs-aaa-graphics-builder -description: "Upgrade Three.js games from basic/prototype visuals to premium AAA-inspired browser graphics. Combines art-direction critique, procedural model building, technical art, mandatory external asset sourcing decisions, threejs-3d-generator assets, threejs-image-generator concept/texture workflows, scene visual polish, material/texture libraries, world prop kits, shaders, VFX readability, render budgets, LOD/instancing, render pipeline, and visual scorecard gates. For premium games with characters, vehicles, ships, weapons, buildings, signature props, skies, textures, decals, logos, icons, or GUI art, load the relevant generator skills before deciding procedural assets are enough." ---- - -# Three.js AAA Graphics Builder - -## Purpose - -Own the production graphics pass. Convert basic screenshots into authored, high-density, performance-aware visual experiences. - -## Use When - -Screenshots still look basic, models look primitive, worlds are sparse, UI/world art feels generic, or the user asks for premium, AAA, high-fidelity, showcase, or less-basic graphics. - -## Required References - -These references are required phase-entry gates, not optional reading: - -- Load `references/visual-scorecard.md` before scoring, judging completion, or making any premium/AAA/showcase claim. -- Load `references/implementation-blueprint.md` before changing graphics architecture, materials, VFX, rendering, diagnostics, or broad visual systems. -- Load `references/model-recipes.md` before building or upgrading hero/player, obstacle, enemy, pickup, world-kit, material, or prop models. -- Load `references/render-recipes.md` before changing lighting, tone mapping, shadows, fog, post-processing, materials, or render composition. -- Load `references/technical-art.md` before premium/AAA/showcase graphics work, shaders/material systems, VFX systems, generated/imported asset cleanup, LOD/instancing work, or visual changes that could affect browser performance. -- Load `references/shader-cookbook.md` before writing any custom shader, `onBeforeCompile` injection, material recipe, sky, or post-processing chain — use its proven values and GLSL patterns instead of improvising. -- Load `references/checklists/aaa-game-quality-gate.md` and `references/checklists/aaa-visual-scorecard.md` before declaring a game premium, AAA, showcase, complete, release-ready, or less basic. -- Load the relevant checklist before focused work: `references/checklists/procedural-model-quality.md`, `references/checklists/material-lighting-quality.md`, `references/checklists/performance-safe-visual-detail.md`, or `references/checklists/technical-art-quality.md`. -- Load `references/prompt-templates.md` only when the user asks for reusable prompts, a graphics-pass prompt, or a task template. - -For broad "still looks basic", premium, AAA, high-fidelity, showcase, or less-basic graphics work, load all five references as the first action in the phase. Track them in a reference ledger with yes/no, path, and failure reason. Do not mark the graphics phase complete while any required reference is skipped. - -External asset sourcing gate: - -- For premium/AAA/showcase/high-fidelity/less-basic graphics with a hero/player, character, creature, boss, vehicle, ship, building, weapon, signature prop, complex pickup, or hero environment piece, load `threejs-3d-generator` before deciding procedural geometry is enough. -- For premium/AAA/showcase/high-fidelity/less-basic graphics with concept needs, texture/material references, decals, logos, faction marks, icons, GUI art, skies, backgrounds, title/menu art, or image-to-3D inputs, load `threejs-image-generator` before deciding 2D external assets are not needed. -- Run the director credential probe before using `key unavailable` as a skip reason and paste the SET/MISSING output. -- Create an asset sourcing ledger for each high-value surface: procedural / threejs-image-generator / threejs-3d-generator / hybrid, plus outputs or skip reason. -- `not-needed` is valid only after the relevant skill was loaded and the ledger explains why external generation would not improve a non-hero support surface, or why the credential probe or attempted generation shows a real blocker. -- For premium hero surfaces, procedural-only is not an allowed final answer unless there is real blocker evidence. At least one high-value surface must show a 3D generator task ID, downloaded GLB/GLTF/FBX path, image generator output path, or documented hybrid chain. - -## Workflow - -1. Capture or inspect active desktop/mobile screenshots. -2. Score visuals across art direction, hero/player, obstacles, rewards, world, materials, render, VFX, UI, and performance evidence. -3. Add missing graphics architecture: material library, procedural textures/decals, model factories, world prop kit, technical-art budget, VFX system, render pipeline, diagnostics. -4. Run the credential probe, then fill the external asset sourcing ledger per surface: procedural Three.js factory, `threejs-image-generator` 2D reference/texture, `threejs-3d-generator` 3D generation, or a hybrid. -5. Upgrade every weak visible surface, not only one hero object. -6. Add lighting/render/material polish after authored forms exist. -7. Add event-driven VFX tied to gameplay state. -8. Re-score screenshots against the calibration anchors, citing the inspector's measured metrics. Continue until every premium category is at least 2/3 or report exact blockers. -9. Run the fresh-eyes review per `references/visual-scorecard.md` before finalizing premium/AAA/showcase claims. -10. Verify renderer diagnostics against the render budget table, technical-art budget, desktop/mobile screenshots, console/page errors, canvas pixels, imported asset budgets, and playability. - -## Core Rule - -Do not make primitives look AAA by adding glow. First build authored forms, then materials, then lighting, then effects. - -## Final Response - -Report the reference ledger, credential probe output, external asset sourcing ledger, technical art brief, score before/after, production surfaces upgraded, files changed, screenshots/artifacts, renderer diagnostics, imported asset diagnostics when relevant, VFX readability and render-budget tradeoffs, and remaining blockers. For premium/AAA/showcase claims, include the filled visual scorecard exactly as defined in `references/visual-scorecard.md`, including average and automatic failures remaining. diff --git a/.agents/skills/threejs-aaa-graphics-builder/agents/openai.yaml b/.agents/skills/threejs-aaa-graphics-builder/agents/openai.yaml deleted file mode 100644 index ec2bb48ec4..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Three.js AAA Graphics Builder" - short_description: "Upgrade Three.js graphics quality" - default_prompt: "Load threejs-aaa-graphics-builder/SKILL.md (try ~/.codex/skills/threejs-aaa-graphics-builder/SKILL.md, then ~/.claude/skills, ~/.agents/skills, or repo skills/) and follow it exactly, including its reference gates and the external asset sourcing gate. Non-negotiables: for premium asset categories, run the credential probe and load threejs-3d-generator and/or threejs-image-generator before deciding procedural assets are enough, producing real task IDs/output paths or blocker evidence; report the filled visual scorecard with measured evidence; do not claim premium quality while any required reference, evidence item, or scorecard category is missing." diff --git a/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-1.jpg b/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-1.jpg deleted file mode 100644 index 165702a0c2..0000000000 Binary files a/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-1.jpg and /dev/null differ diff --git a/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-2.jpg b/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-2.jpg deleted file mode 100644 index d9ee020c57..0000000000 Binary files a/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-2.jpg and /dev/null differ diff --git a/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-3.jpg b/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-3.jpg deleted file mode 100644 index e35368e2f6..0000000000 Binary files a/.agents/skills/threejs-aaa-graphics-builder/assets/scorecard-anchors/scene-3.jpg and /dev/null differ diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/aaa-game-quality-gate.md b/.agents/skills/threejs-aaa-graphics-builder/references/checklists/aaa-game-quality-gate.md deleted file mode 100644 index 8d4f52f728..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/aaa-game-quality-gate.md +++ /dev/null @@ -1,23 +0,0 @@ -# AAA Browser Game Quality Gate - -- The game is immediately playable and not presented as a landing page. -- The core loop has objective, scoring/progress, fail/retry, pacing, and feedback. -- Screenshots do not read as a collection of default primitives, debug HUDs, or generic placeholder panels. -- Unadorned boxes, cones, spheres, flat planes, and stretched buildings are not the dominant art language unless explicitly intentional. -- UI is genre-specific, compact, readable during motion, responsive, and includes needed modal states. -- Player, threats, rewards, and objectives have distinct silhouettes and material/feedback language. -- Player/hero asset has primary silhouette, secondary structure, tertiary detail, material contrast, and state feedback. -- Obstacle/enemy set includes at least three authored variants with unique telegraphs. -- Reward/interactable set includes at least two authored variants with collection/interaction feedback. -- World kit includes reusable modules and does not rely on one repeated skyline/block/road primitive. -- The scene has foreground, midground, and background depth instead of one flat play lane. -- Lighting, shadows, fog, and post-processing clarify depth and mood without hiding gameplay. -- Procedural models use the authored factories, shared material kit, reusable prop kits, and collision proxies from `references/implementation-blueprint.md` and `references/technical-art.md`. -- Movement, camera, speed, impact, and restart loop feel tuned through play, not just configured. -- Audio/visual feedback exists for core actions and state transitions. -- Mobile viewport preserves framing, safe areas, touch targets, and text fit. -- Renderer diagnostics from `references/technical-art.md` are reviewed when visual fidelity changes. -- Visual scorecard in `references/visual-scorecard.md` passes: every category at least 2 and average at least 2.3. -- Build, browser run, console/page errors, screenshots, nonblank canvas, interaction, and responsive checks all pass. -- A screenshot critique identifies no unresolved high-impact placeholder-quality blockers. -- If any premium surface was intentionally deferred, the final report says which one and why. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/aaa-visual-scorecard.md b/.agents/skills/threejs-aaa-graphics-builder/references/checklists/aaa-visual-scorecard.md deleted file mode 100644 index e8adbf5cb7..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/aaa-visual-scorecard.md +++ /dev/null @@ -1,19 +0,0 @@ -# AAA Visual Scorecard Checklist - -Use with `threejs-aaa-graphics-builder/references/visual-scorecard.md`. - -- Current desktop and mobile active-play screenshots are available. -- Art direction category scored 0-3. -- Hero/player asset category scored 0-3. -- Obstacles/enemies category scored 0-3. -- Rewards/interactables category scored 0-3. -- World/environment category scored 0-3. -- Materials/textures category scored 0-3. -- Lighting/render category scored 0-3. -- VFX/motion category scored 0-3. -- UI/HUD category scored 0-3. -- Performance evidence category scored 0-3. -- No automatic failure is present: check every item in the canonical Automatic Failures list in `threejs-aaa-graphics-builder/references/visual-scorecard.md` (do not rely on a from-memory summary of it). -- Technical-art evidence includes material kit, VFX readability, instancing/LOD/culling decision, DPR/post/shadow tradeoffs, and imported asset diagnostics when generated/imported assets are used. -- Premium gate passes only when every category is at least 2 and average score is at least 2.3. -- Showcase gate passes only when at least six categories are 3, no category is below 2, and average score is at least 2.7. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/material-lighting-quality.md b/.agents/skills/threejs-aaa-graphics-builder/references/checklists/material-lighting-quality.md deleted file mode 100644 index 4410392179..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/material-lighting-quality.md +++ /dev/null @@ -1,14 +0,0 @@ -# Material and Lighting Quality Checklist - -Gate the lighting/material recipes in `references/render-recipes.md` and the material kit in `references/technical-art.md`. - -- Renderer color space, tone mapping, exposure, and shadow settings are intentional. -- Key, fill, rim, ambient, and environment lighting follow the lighting stack in `references/render-recipes.md` and clarify depth and gameplay roles. -- Materials avoid flat default looks through roughness/metalness/emissive/vertex-color variation. -- Important objects have readable silhouettes against background, fog, and effects. -- Shadows help ground assets without obscuring navigation or collision boundaries. -- Fog, bloom, particles, and post-processing support readability instead of hiding it. -- Procedural textures or decals are scaled, stable, and not visually noisy during movement. -- Materials reuse the shared kit in `references/technical-art.md` where possible and are disposed when obsolete. -- Desktop and mobile screenshots are checked after lighting/material changes. -- Renderer info or frame-time evidence is gathered when render cost changes. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/performance-safe-visual-detail.md b/.agents/skills/threejs-aaa-graphics-builder/references/checklists/performance-safe-visual-detail.md deleted file mode 100644 index 5e12eb3efd..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/performance-safe-visual-detail.md +++ /dev/null @@ -1,14 +0,0 @@ -# Performance-Safe Visual Detail Checklist - -Gate the render budget and instancing/LOD guidance in `references/technical-art.md`. - -- Baseline renderer info is captured when increasing fidelity. -- Draw calls, triangles, geometries, materials, textures, and frame time are reviewed against the render budget in `references/technical-art.md` after changes. -- Repeated details use the instancing/LOD approach in `references/technical-art.md`: instancing, shared resources, atlases, or generated texture reuse where practical. -- High segment counts are limited to silhouette-critical forms. -- Shadows are scoped by light count, shadow map size, casters/receivers, and camera distance. -- Post-processing is justified by gameplay readability or strong art direction. -- DPR caps or adaptive quality are considered for mobile. -- Generated resources have a disposal/reuse strategy. -- The worst-case gameplay scene, not only idle view, is inspected. -- Visual detail remains readable at mobile resolution without excessive GPU cost. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/procedural-model-quality.md b/.agents/skills/threejs-aaa-graphics-builder/references/checklists/procedural-model-quality.md deleted file mode 100644 index d6109518cc..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/procedural-model-quality.md +++ /dev/null @@ -1,15 +0,0 @@ -# Procedural Model Quality Checklist - -Gate the procedural modeling guidance in `references/model-recipes.md` and the material kit in `references/technical-art.md`. - -- The model has a recognizable silhouette from the gameplay camera. -- Primary forms read clearly before material or post-processing detail. -- Secondary detail supports the asset role: panels, trims, ridges, tubes, fins, sockets, decals, or emissive accents. -- Tertiary detail is visible at intended camera distance and does not create noise. -- Materials use the kit in `references/technical-art.md` with purposeful contrast in roughness, metalness, color, emissive, or texture. -- Bevels, curves, and segment counts improve silhouette or highlight behavior. -- Repeated props use shared geometries/materials, instancing, or pools when practical. -- Visual mesh and gameplay collision/proxy are intentionally separated when needed. -- The factory returns named groups/meshes and keeps ownership/disposal clear. -- Renderer diagnostics from `references/technical-art.md` are checked when triangles, materials, textures, or draw calls increase. -- Mobile screenshot still shows the asset as more than a primitive placeholder. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/technical-art-quality.md b/.agents/skills/threejs-aaa-graphics-builder/references/checklists/technical-art-quality.md deleted file mode 100644 index 9bc99bf7b8..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/checklists/technical-art-quality.md +++ /dev/null @@ -1,17 +0,0 @@ -# Technical Art Quality Checklist - -Use before claiming premium, AAA, showcase, high-fidelity, or less-basic visual quality after graphics changes. Each item gates the guidance in `references/technical-art.md`. - -- Technical art brief converts art direction into shapes, material roles, lighting, VFX, camera, UI/world motifs, and budgets. -- Hero surfaces and support surfaces are identified separately. -- Material kit uses the named shared roles from `references/technical-art.md`, not scattered one-off colors/materials. -- Shader/post-processing choices have player-facing purpose and measured or bounded cost. -- VFX follow the event-driven language in `references/technical-art.md`: readable, short-lived, and not hiding collision, threats, rewards, or UI. -- Instancing is used for large repeated same-geometry/same-material detail where appropriate. -- LOD, culling, or simplified far variants are planned for heavy background/imported assets. -- Imported/generated models have scale, pivot/orientation, bounds, file size, triangle/material/texture counts when available, and collision proxies checked. -- Decals/trim/detail systems reinforce function, route, faction, scale, or state. -- Threats, rewards, interactables, and player state are not communicated by color alone. -- DPR cap, shadow settings, post-processing passes, and mobile tradeoffs are reported. -- Renderer diagnostics match the render budget reporting in `references/technical-art.md`: calls, triangles, geometries, textures, and material count when available. -- Final visual scorecard performance evidence category includes budget and technical-art evidence, not only screenshots. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/implementation-blueprint.md b/.agents/skills/threejs-aaa-graphics-builder/references/implementation-blueprint.md deleted file mode 100644 index 8e2e51be42..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/implementation-blueprint.md +++ /dev/null @@ -1,157 +0,0 @@ -# AAA Graphics Implementation Blueprint - -Use this when a Three.js game reads as basic even after it is playable. The goal is a production graphics architecture that can be iterated, scored, profiled, and reused. For premium/AAA/showcase work, also load `references/technical-art.md` and treat the technical art brief and budget as part of the graphics architecture. - -## Recommended Ownership - -```text -src/assets/MaterialLibrary.ts -src/assets/ProceduralTextures.ts -src/assets/DecalShapes.ts -src/assets/ModelDiagnostics.ts -src/assets/ImportedAssetRegistry.ts -src/assets/modelFactories/HeroFactory.ts -src/assets/modelFactories/ObstacleFactory.ts -src/assets/modelFactories/RewardFactory.ts -src/assets/modelFactories/WorldPropKit.ts -src/systems/LightingRig.ts -src/systems/RenderPipeline.ts -src/systems/VfxSystem.ts -src/systems/WorldArtDirector.ts -src/systems/QualityDiagnostics.ts -``` - -Keep these boundaries lightweight. In small projects, a single file can contain multiple factories, but the concepts must remain separate: materials, authored geometry, repeated props, effects, render settings, and diagnostics. - -## Hybrid AI Asset Pipeline - -Choose the asset path per surface: - -- Procedural Three.js: repeated detail, simple props, rails, track parts, decals, collision proxies, VFX geometry, debug-friendly primitives. -- `threejs-image-generator`: concept sheets, T-pose/A-pose references, texture references, trim sheets, decals, icons, logos, skies, backgrounds, UI art. -- `threejs-3d-generator`: hero/player, characters, creatures, vehicles, buildings, weapons, signature props, pickups, bosses, complex terrain modules. -- Hybrid: image-generator concept/reference -> 3D-generator image-to-model -> Three.js import -> procedural collision/VFX/prop kit -> visual scorecard. - -For premium/AAA/showcase/high-fidelity/less-basic games, do not decide `threejs-3d-generator` or `threejs-image-generator` is unnecessary before loading the relevant skill when the game includes characters, creatures, vehicles, ships, weapons, buildings, signature props, hero pickups, skies, textures, decals, logos, icons, or GUI art. Load first, run the credential probe, then document the tradeoff. - -Use `threejs-3d-generator` when generated model fidelity will materially improve the active screenshot. Do not use generated 3D for every repeated small prop; use instancing/procedural kits for volume. - -For premium hero surfaces, procedural-only is not a valid final choice unless a real blocker is recorded: missing key from the credential probe, API/network/quota error after an attempted command, user requested no external assets, or offline-only constraint. Repeated low-value props can stay procedural. - -Fill the external asset sourcing ledger before the graphics phase using the canonical template in `threejs-game-director/references/phase-playbook.md` (Ledger Templates). It records the credential probe output, the chosen source per surface (procedural / `threejs-image-generator` / `threejs-3d-generator` / hybrid), and the generated outputs or allowed blocker for each surface. - -## Production Surfaces - -A premium pass must touch every weak visible surface: - -- Hero/player: authored silhouette, state feedback, decals/trim, readable front/up/side, collision proxy. -- Hazards/enemies: at least three distinct silhouettes with telegraphs and material cues. -- Rewards/interactables: at least two forms with collection states and motion/VFX hooks. -- World kit: foreground, playable lane/arena, midground, background/parallax, set dressing, scale cues. -- Materials/textures: shared PBR/stylized material library, procedural panel lines, noise, trim, wear, emissive masks. -- Lighting/render: color space, tone mapping, exposure, shadows/contact, fog/depth, post-processing discipline. -- VFX/motion: event-driven bursts, trails, impact rings, speed lines, shield/boost states, pickup/fail feedback. -- UI/world cohesion: UI colors, icons, alerts, and meters echo gameplay materials and status colors. -- Diagnostics: renderer counts, material/geometry/texture counts, screenshots, scorecard. - -For imported generated 3D assets, also require downloaded GLB/PBR output, import wrappers with scale/pivot/bounds, simple collision proxies, animation clips when relevant, and triangle/material/texture/file-size diagnostics. - -## Technical Art Contract - -Before broad implementation, write the technical art brief and render budget from `references/technical-art.md`: hero vs support surfaces, render budget target, material kit roles, shader/VFX purpose, instancing/LOD/culling plan, and imported asset cleanup. Treat that brief as part of this graphics architecture. - -Do not add costly effects until this contract exists. A technical-art pass should make the scene more authored and more measurable at the same time. - -## Material Library - -Implement the named material-role kit defined in `references/technical-art.md` (`bodyPrimary`, `bodySecondary`, `trim`, `hazard`, `reward`, `glass`, `emissiveSignal`, `groundContact`, `decalDark`/`decalLight`, plus shared UI/world signal colors) in `src/assets/MaterialLibrary.ts`. Create named roles instead of one-off colors and share materials across repeated meshes. - -## Procedural Texture And Decal Kit - -Use canvas textures, shape geometry, or thin offset meshes for detail that would otherwise require external assets: - -- Panel lines and access hatches. -- Trim sheets and edge bands. -- Window strips, city light grids, arena markings. -- Hazard stripes, arrows, target indicators, lane glyphs. -- Scratches, wear, noise, dirt, heat tint, scorch marks. -- UI/world icon motifs reused in HUD and diegetic markers. - -Set texture filtering, mipmaps, repeat/wrap, color space, and anisotropy intentionally. Avoid unique full-size textures for tiny repeated marks. - -Use `threejs-image-generator` for high-value 2D source art: terrain/rock/asphalt/snow/moss texture references, sci-fi trim sheets, signs, hazard stripes, cockpit decals, sky/background plates, menu/loading art, faction logos, pickup icons, ability icons, and GUI glyphs. Use the resulting images either as actual 2D assets or as image-to-3D inputs. - -## Model Factories - -Factories should return a grouped object plus metadata: - -```ts -type ModelFactoryResult = { - root: THREE.Group; - collision?: THREE.Object3D; - lod?: THREE.LOD; - bounds?: THREE.Box3; - diagnostics?: { - meshes: number; - materials: number; - geometries: number; - triangles?: number; - }; -}; -``` - -Use named child meshes for readable debugging. Separate visual detail from collision proxies. Keep repeated detail instanced where practical. - -For imported generated 3D models, create an `ImportedAssetRegistry` or loader wrapper that returns similar metadata: root group, bounds, collision proxy, animation clips, and diagnostics. Never put 3D/image/audio generation API calls in browser runtime code. - -## World Art Director - -Build the world as layers: - -- Play layer: ground, lanes, rails, objective path, hazards, pickups. -- Near layer: speed props, signs, arches, barriers, debris, foreground occluders used carefully. -- Mid layer: buildings, cliffs, hangars, pillars, platforms, arena machinery. -- Far layer: skyline, terrain silhouettes, nebula/cloud/fog cards, parallax planes. -- Motion layer: speed lines, particles, trail strips, dust, sparks, screen-space UI feedback. - -Every layer should support gameplay readability. Do not obscure threats or the next decision. - -## Render Pipeline - -Own renderer setup in one place: - -- `outputColorSpace = THREE.SRGBColorSpace`. -- Tone mapping and exposure selected for the art direction. -- DPR capped for mobile and high-density displays. -- Shadows enabled only for objects that benefit from grounding. -- Post-processing is limited and measured: bloom, vignette, chromatic aberration, film grain, or color grade only when they improve authored forms. -- Resize updates canvas, renderer, camera, composer, and UI CSS variables. - -## VFX System - -Implement the event-driven VFX language from `references/technical-art.md` in `src/systems/VfxSystem.ts`. Effects should be pooled, readable, and tied to state; they must clarify state instead of adding permanent particle clutter. - -## Diagnostics - -Own diagnostics in `src/systems/QualityDiagnostics.ts`. Report the renderer diagnostics defined in `references/technical-art.md` (calls, triangles, geometries, textures, material count, DPR/post/shadow settings), plus these architecture-specific counts: - -- Scene mesh count, instanced mesh count, unique materials/geometries/textures. -- Approximate visible prop counts by layer. -- Screenshot paths and visual scorecard. -- Performance notes after post-processing, shadows, or many repeated props. - -## Browser Game Budgets - -Use the render budget starting points and instancing/LOD/culling guidance in `references/technical-art.md`, then measure on the target game after every major graphics pass. - -## Implementation Order - -1. Score active screenshots and identify the weakest three categories. -2. Add material and diagnostic foundations. -3. Decide which weak surfaces need procedural, `threejs-image-generator`, `threejs-3d-generator`, or hybrid treatment. -4. Build/import hero/player and one complete obstacle/reward family. -5. Add world prop kit and layered composition. -6. Add lighting/render polish. -7. Add event-driven VFX. -8. Re-score desktop/mobile active screenshots. -9. Optimize measured bottlenecks. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/model-recipes.md b/.agents/skills/threejs-aaa-graphics-builder/references/model-recipes.md deleted file mode 100644 index a3811bf475..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/model-recipes.md +++ /dev/null @@ -1,146 +0,0 @@ -# Procedural Model Recipes - -These recipes are for scratch-built Three.js models when external art assets are unavailable. The goal is not photorealism; it is authored, layered, readable, premium browser-game art. - -## Modeling Principles - -- Start with silhouette. A model should be recognizable as a dark shape before materials or glow. -- Combine primitive bases with authored geometry: extrusions, bevels, curves, tubes, lathes, custom buffers, decals, trim, and instanced micro-detail. -- Use asymmetry and functional parts: hinges, fins, vents, handles, rails, brackets, sensors, cables, panels, bolts. -- Put detail where the camera sees it. Spend triangles on player-facing surfaces, not hidden undersides. -- Create state variants through material swaps, animated child parts, emissive strips, and VFX sockets. -- Keep a simple collision proxy separate from the detailed visual group. -- Use shared geometries/materials and instancing for repeated bolts, panels, lights, windows, spikes, rocks, or rail segments. -- Name important child meshes: `cockpitGlass`, `leftEngine`, `hazardTeeth`, `pickupCore`, `collisionProxy`. - -## Minimum Premium Asset Pass - -For a game that asks for premium/AAA/showcase quality, build at least: - -- One hero/player model with readable front/up/side and three state cues. -- Three obstacle/enemy variants with unique silhouettes and telegraphs. -- Two reward/interactable variants with idle and collect states. -- One world prop kit with at least eight reusable parts. -- One material kit with trim, decals, panel lines, and emissive masks. -- Collision proxies and renderer diagnostics for the above. - -## Hero Vehicle Recipe - -Use for runners, racers, hovercraft, spaceships, drones, or arcade vehicles. - -- Core hull: `ExtrudeGeometry` or custom tapered `BufferGeometry`, not just a box. -- Nose/front: wedge, intake, sensor strip, bumper, or blade shape. -- Cockpit/core: glass dome from sphere/lathe segments, beveled capsule, or faceted canopy. -- Engines: cylinders/cones/tubes with nozzle rings, inner emissive discs, heat fins, and trail sockets. -- Wings/fins: extruded triangular or curved plates with bevel/trim lines. -- Undercarriage: skids, landing pads, rail clamps, suspension arms, or thruster pods. -- Decals: panel lines, numeric marks, faction glyph, hazard ticks, small bolts. -- State cues: boost flares, shield shell, damage scorch, pickup glow, overheat red. -- Collision proxy: one capsule/box/sphere group matching gameplay footprint. - -Reject if the hero is mostly a box with two cylinders and a glow. - -## Hero Character Recipe - -Use for arena fighters, brawlers, platformers, or stylized third-person games. - -- Body mass: torso, pelvis, head/helmet, limbs with tapered capsule/cylinder custom scales. -- Rig illusion: separate shoulders, elbows, knees, wrists, ankles, belt, backpack, armor plates. -- Face/identity: visor, mask, hair/helmet crest, color-blocked silhouette, weapon/tool. -- Animation-ready pivots: group limbs under named joints even if animation is procedural. -- Material zones: skin/fabric/armor/metal/glass/emissive accents. -- State cues: hit flash material, shield ring, attack trail socket, stamina/charge glow. -- Collision proxy: capsule or cylinder independent of mesh detail. - -Reject if the character reads as stacked spheres/cylinders with no costume, joints, or silhouette. - -## Obstacle And Enemy Families - -Build distinct gameplay reads: - -- Low barrier: ground-hugging slab, spikes, rails, caution panels, animated warning light. -- Gate/arch: overhead frame, side posts, pulsing pass/avoid lane, moving shutters. -- Moving hazard: rotating arm, sweeper beam, drone, crusher, sliding block, orbiting mines. -- Trap/zone: laser grid, electric puddle, collapsing tile, gravity well, proximity mine. -- Enemy: body core, sensor/head, weapon, shield, locomotion/hover base, attack telegraph. - -Each variant needs: - -- Unique silhouette. -- Material cue for danger. -- Telegraph from distance. -- Animation or state change. -- Collision proxy. -- Low-cost repeated detail. - -Reject if all hazards are recolored cubes/cones. - -## Reward And Interactable Recipes - -Rewards should be readable and desirable during motion. - -- Token: outer ring, inner core, value icon, shimmer cards, collect burst socket. -- Shard: faceted crystal, metal bracket, orbiting chips, emissive seam. -- Capsule: glass shell, suspended item, end caps, rotating label strip. -- Power-up: icon silhouette matched to effect, color and shape differ from score pickups. -- Objective item: larger scale, unique motion, UI echo, stronger lighting/VFX. - -States: - -- Idle: slow rotation, pulse, bob, or orbit. -- Attract: line/trail toward player. -- Collect: vanish, burst, score trail, HUD meter update. - -Reject if rewards are plain spheres or torus rings without state feedback. - -## World Prop Kit - -Build modular props that can be instanced and recombined: - -- Track/road: lane plates, seams, arrows, side rails, guard segments, repair panels. -- Arena: boundary rings, floor tiles, spawn pads, cover blocks, goal markers. -- City/sci-fi: window strips, antennas, rooftop units, bridge trusses, pylons, billboards. -- Nature: rocks from custom faceted buffers, cliffs, roots, crystals, grasses as cards. -- Industrial: pipes, vents, cables, tanks, crates, gantries, lights, warning signs. -- Space/air: debris panels, satellites, buoys, asteroid chunks, parallax dust. - -Layer the kit: - -- Near props create speed and scale. -- Mid props define the playable corridor. -- Far props create depth without stealing draw calls. - -Reject if the world is mostly stretched boxes or a flat plane. - -## Procedural Geometry Techniques - -- `ExtrudeGeometry`: panels, fins, wings, badges, UI/world glyphs, signs. -- `LatheGeometry`: capsules, domes, engines, pipes, bottles, turret bases. -- `TubeGeometry`: cables, rails, trails, conduits, curved weapons. -- Custom `BufferGeometry`: tapered hulls, rocks, shards, wedges, low-poly terrain. -- `ShapeGeometry`: decals, flat icons, trim strips, hazard markers. -- `InstancedMesh`: windows, bolts, lane markers, debris, grass, lights, small props. -- `LOD`: hero/background variants and dense prop reductions. - -Use bevel-like layering when real bevel geometry is too expensive: duplicate thin trim meshes, edge strips, or slightly offset darker panels. - -## Material And Detail Rules - -- Use roughness/metalness contrast, not only hue contrast. -- Use emissive for authored signals, not entire objects. -- Use glass/clearcoat sparingly on hero details. -- Add darker contact material under important objects. -- Use decals to imply scale and function. -- Reuse UI icon shapes as world decals for cohesion. - -## Diagnostics Checklist - -After a model pass, report: - -- Mesh count. -- Instanced mesh count. -- Unique geometries/materials/textures. -- Approximate triangle count if available. -- Collision proxies included. -- LOD or culling strategy for repeated/background props. -- Active-play screenshots, not only showroom renders. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/prompt-templates.md b/.agents/skills/threejs-aaa-graphics-builder/references/prompt-templates.md deleted file mode 100644 index 2acbeccfa9..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/prompt-templates.md +++ /dev/null @@ -1,236 +0,0 @@ -# Three.js AAA Graphics Prompt Templates - -Reusable prompt templates packaged with this skill. Use only templates relevant to the current request, and adapt placeholders to the game/project context. - ---- - -# AAA Graphics Production Pass Prompt - -Use `threejs-aaa-graphics-builder` to upgrade this Three.js game from basic prototype visuals to premium browser-game graphics. - -Current screenshot blockers: -- - -Target art direction: -- - -Required pass: -- Score current screenshots with `threejs-aaa-graphics-builder/references/visual-scorecard.md`. -- Add or improve the graphics architecture from `references/implementation-blueprint.md`. -- Add the technical art brief from `references/technical-art.md`: material kit, shader/VFX purpose, instancing/LOD/culling, imported asset cleanup, renderer budget, mobile tradeoffs. -- Build material library, procedural texture/decal helpers, model factories, world prop kit, VFX system, lighting/render pipeline, and diagnostics. -- Use `threejs-3d-generator` for high-value hero/player, character, creature, vehicle, building, weapon, pickup, boss, rigging, animation, texture, or conversion needs when procedural code is not enough. -- Use `threejs-image-generator` for 2D concepts, T-pose/A-pose references, texture references, decals, logos, icons, GUI art, skies, backgrounds, or image-to-3D inputs. -- Upgrade hero/player, obstacles/enemies, rewards/interactables, world kit, HUD cohesion, lighting, effects, and renderer metrics. - -Do not count as completion: -- Recolored boxes/cones/spheres. -- Glow, fog, or darkness hiding missing detail. -- One improved object while world/obstacles/UI remain placeholders. -- Idle/showroom screenshots only. -- Missing renderer diagnostics after visual density changes. - -Verification: -- Capture active gameplay desktop and mobile screenshots. -- Report visual score before/after. -- Report draw calls, triangles, geometries, textures, material count, DPR cap, shadow/post settings, and instancing/LOD/culling decisions when available. -- Run build, browser, console/page error, nonblank canvas, interaction, and responsive checks. -- Continue until every scorecard category is at least 2, or report exactly why the target was not reached. - ---- - -# Before/After Visual Critique Prompt - -Use `threejs-aaa-graphics-builder` to critique this Three.js game's current screenshots with the visual scorecard and produce a prioritized graphics plan. - -Evidence to gather: -- Desktop screenshot. -- Mobile screenshot. -- Optional before/after screenshots if a pass was already completed. -- Renderer diagnostics if available. -- Notes on the game genre, core verb, and target mood. - -Critique dimensions: -- Gameplay readability. -- UI hierarchy and text fit. -- Procedural model silhouette and fidelity. -- Material, lighting, shadows, color, and contrast. -- Camera composition and motion clarity. -- Mobile framing and touch/control readability. -- Performance risk from proposed upgrades. - -Output: -- Pass/fail on whether the game looks polished enough for the current milestone. -- Top five blockers ordered by player impact. -- Recommended next skill/phase: `threejs-aaa-graphics-builder`, `threejs-game-ui-designer`, `threejs-debug-profiler`, or `threejs-qa-release`. -- Concrete acceptance criteria for the next pass. - ---- - -# Material, Lighting, and Render Quality Pass Prompt - -Use `threejs-aaa-graphics-builder` for scene-level render quality, material libraries, model materials, geometry factories, and visual scoring. - -Current problem: -- - -Target look: -- - -Work areas: -- Renderer color space, tone mapping, exposure, shadow settings, DPR cap. -- Key/fill/rim/environment lighting. -- Material roughness, metalness, emissive accents, vertex colors, generated textures, and decals. -- Fog, background, post-processing, and feedback effects only where they improve readability. -- Camera composition and gameplay-distance readability. - -Constraints: -- Improve lighting and materials before adding heavy post-processing. -- Keep threats, pickups, player, and objective readable during motion. -- Avoid excessive bloom, low-contrast fog, and particle clutter. -- Re-measure renderer info if visual complexity changes. - -Verification: -- Capture desktop and mobile screenshots. -- Check console/page errors and nonblank canvas pixels. -- Compare renderer calls/triangles/textures before and after when practical. -- Play the core loop and confirm effects do not hide gameplay information. - ---- - -# Technical Art Pass Prompt - -Use `threejs-aaa-graphics-builder` for a technical-art pass on this Three.js game. - -Current visual/performance risk: -- - -Target art direction: -- - -Required pass: -- Load `references/technical-art.md`. -- Write a technical art brief: hero surfaces, support surfaces, material kit, VFX language, lighting stack, render budget, asset strategy, mobile constraint. -- Convert art direction into renderable systems: materials, decals/trim, shaders, VFX, LOD, instancing, culling, imported asset cleanup. -- Make threats, rewards, player state, and objectives readable by shape/motion/value, not color alone. -- Keep API/generated asset calls out of browser runtime. - -Verification: -- Capture active desktop and mobile screenshots. -- Report renderer diagnostics: calls, triangles, geometries, textures, material count when available, DPR cap, shadow/post settings. -- Report imported/generated asset diagnostics when relevant: file size, bounds, scale, orientation, collision proxy, triangles/materials/textures/clips when available. -- Report VFX readability: trigger, duration, player-facing meaning, and reduced-motion concern if applicable. -- State what was optimized, what was intentionally left rich, and remaining performance risks. - ---- - -# Procedural Hero Asset Pass Prompt - -Use `threejs-aaa-graphics-builder` to create or upgrade a high-fidelity scratch-built Three.js hero asset. - -Asset brief: -- Role: -- Silhouette: -- Scale: -- Camera distance: -- Style references: -- Performance budget: - -Requirements: -- Build a reusable model factory that returns a named `THREE.Group`. -- Establish a recognizable silhouette before adding small detail. -- Add secondary and tertiary detail through bevels, trims, panels, ridges, tubes, decals, emissive elements, and material contrast. -- Add visible subassemblies, not just a few primitives: shell/body, core/cockpit, trims/rails, engines/emitters, decals/surface marks, and state feedback when relevant. -- Use shared geometries/materials where possible. -- Use PBR-style materials, shadows, color management, and lighting intentionally. -- Keep collision or gameplay proxies simpler than the visual mesh. - -Avoid: -- Placeholder stacks of primitives. -- Detail visible only from a showroom camera. -- Excessive segment counts, unique materials, or draw calls without gameplay value. -- Glow-only upgrades that leave the silhouette primitive. - -Verification: -- Build and run locally. -- Capture gameplay-camera screenshot and one inspection screenshot if useful. -- Report renderer info before/after when available. -- Verify the asset reads clearly at desktop and mobile gameplay distances. - ---- - -# Visual Polish Prompt - -Use `threejs-aaa-graphics-builder` to improve the game's visual clarity and identity. - -Use focused prompts instead when the main problem is narrower: -- Use `threejs-game-ui-designer/references/prompt-templates.md` for HUD/menu/interface quality prompts. -- Use the procedural hero asset or world prop kit sections in this file for scratch-built model fidelity inside the AAA graphics phase. -- Use the before/after visual critique section in this file when priorities are unclear. - -Target feel: -- - -Constraints: -- Keep the game readable during motion. -- Avoid generic purple gradients, excessive bloom, particle clutter, and static showroom composition. -- Prefer purposeful lighting, color contrast, silhouettes, material variation, and procedural geometry that supports gameplay. -- Hand off substantial UI craft to `threejs-game-ui-designer`; keep model/world/render construction under `threejs-aaa-graphics-builder`. -- Keep performance visible while polishing. - -Verification: -- Capture before/after screenshots where possible. -- Check desktop and mobile framing. -- Confirm the game remains interactive and no console errors were introduced. - ---- - -# World Prop Detail Kit Pass Prompt - -Use `threejs-aaa-graphics-builder` to create a reusable procedural prop/detail kit for this Three.js game's world. - -World role: -- - -Kit requirements: -- Define 4-8 reusable prop factories with shared materials. -- Include scale variants, color/material variants, and clear placement rules. -- Use instancing or shared geometry/materials for repeated details. -- Add visual detail that supports navigation, danger, reward, or atmosphere. -- Keep the kit coherent with the existing game UI and world lighting. -- For city/runner worlds, include skyline modules with setbacks/window bands/roof details, foreground speed props, track hardware, signage/cables/supports, and distant parallax layers. - -Performance constraints: -- Avoid unique material explosions. -- Keep repeated props instanced or pooled when practical. -- Track draw calls, triangles, geometries, textures, and frame impact. - -Verification: -- Capture before/after screenshots from gameplay camera. -- Check desktop and mobile readability. -- Report renderer diagnostics. -- Confirm no console/page errors and no obvious collision/occlusion issues. -- If the world is still dominated by stretched boxes, continue the prop-kit pass. - ---- - -# Fresh-Eyes Scorecard Review Prompt - -Use for the independent review pass required by `references/visual-scorecard.md` for premium/AAA/showcase claims. Give the reviewer ONLY the inputs below — no build history, no prior scores, no description of the work performed. - -Inputs: -- The COMPLETE screenshot capture set — every captured state, desktop and mobile, never a hand-picked subset: -- Scorecard rubric: `threejs-aaa-graphics-builder/references/visual-scorecard.md` -- Calibration anchors: `threejs-aaa-graphics-builder/assets/scorecard-anchors/` -- Inspector metrics JSON: - -Task: -- Score all ten scorecard categories from the screenshots alone, using the 0-3 anchors and calibration images. -- Cross-check scores against the metrics (colorEntropyBits, edgeDensity, luminance.contrast, dominantColorShare, renderBudget) and flag any score the numbers contradict. -- List every automatic failure you can see in the screenshots. -- Do not give benefit of the doubt: if a surface could be a 1 or a 2, score it 1 and say what visible change would earn the 2. - -Report: -- Ten category scores with one-sentence visual evidence each. -- Automatic failures observed. -- The three highest-impact changes to raise the lowest scores. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/render-recipes.md b/.agents/skills/threejs-aaa-graphics-builder/references/render-recipes.md deleted file mode 100644 index ad82f72130..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/render-recipes.md +++ /dev/null @@ -1,90 +0,0 @@ -# Render, Lighting, And VFX Recipes - -Use this after authored forms exist. Rendering polish cannot compensate for missing models, props, or readable gameplay silhouettes. - -## Renderer Setup - -- Set `renderer.outputColorSpace = THREE.SRGBColorSpace`. -- Choose tone mapping deliberately. `ACESFilmicToneMapping` often works for cinematic stylized scenes; simpler tone mapping can be better for bright arcade readability. -- Tune exposure against active gameplay, not a static title view. -- Cap DPR, especially on mobile. Start around `Math.min(devicePixelRatio, 1.5 or 2)` and profile. -- Update renderer, camera, composer, and CSS UI dimensions on resize. -- Use a transparent or explicit background only when composition requires it. - -## Camera Composition - -- Keep the next decision visible. The camera should show player, immediate threat/reward, and route. -- Add depth layers: foreground speed elements, playable midground, background scale cues. -- Use FOV and camera distance to communicate speed without hiding hazards. -- Use camera shake sparingly and clamp intensity. -- Add camera impulses for hits/near misses/boosts, then ease back quickly. -- Check mobile framing separately; vertical and narrow layouts often need different offsets. - -## Lighting Stack - -Use a small readable stack: - -- Key light: defines form and direction. -- Fill light: keeps gameplay objects legible. -- Rim/back light: separates player and hazards from background. -- Practical/emissive lights: authored beacons, engines, pickups, arena markers. -- Contact shadows or shadow blobs: ground important objects. - -Avoid many unmeasured dynamic lights. Prefer baked-looking material/emissive cues, light cards, or small unlit decals for repeated signals. - -## Shadows And Contact - -- Use shadows for hero/player, major hazards, and large world anchors. -- Use smaller shadow maps and limited shadow casters when profiling shows cost. -- Add cheap contact discs or transparent planes for pickups/hovering objects. -- Tune bias to avoid acne and peter-panning. -- Do not let shadows hide collision reads. - -## Materials - -Define material roles with the material kit in `references/technical-art.md` (`MeshStandardMaterial` for most surfaces, `MeshPhysicalMaterial` only where the premium feature is visible). At render time: - -- Prefer material contrast before post effects: matte vs glossy, metal vs plastic, transparent vs opaque, bright trim vs dark contact. -- Use emissive maps or small emissive parts for signals instead of making entire objects glow. -- Keep material roles matched across UI and world: danger, reward, shield, boost, objective. - -## Fog, Background, And Depth - -- Fog should reveal depth and mood, not hide empty worlds. -- Layer background silhouettes at varied scales and heights. -- Add parallax or slow-moving far layers for motion-heavy games. -- Avoid single flat sky colors when the world needs scale; use gradients only as support, not the whole art direction. -- Keep hazards/rewards readable against fog and background values. - -## Post-Processing - -Use post as a finishing pass: - -- Bloom: only authored emissive elements, not all bright materials. -- Vignette: subtle focus, never heavy darkness. -- Film grain/noise: low opacity; avoid compression-like artifacts. -- Chromatic aberration: only brief event-driven impacts or very subtle style. -- Motion blur/trails: prefer geometry trails or particles that preserve gameplay clarity. - -Always compare screenshots with post enabled/disabled and profile the cost. - -## Event-Driven VFX - -Tie effects to state using the event-driven VFX language in `references/technical-art.md` (pickup, hit/fail, boost/speed, near miss/combo, shield/invulnerable, spawn/despawn). Pool effects, reuse geometries/materials, and keep permanent particle fields cheap and sparse. - -## Readability Checks - -During active play, confirm: - -- Player orientation is clear. -- Threats differ from rewards by both shape and material. -- Important pickups are visible before reaction time expires. -- UI feedback does not cover the play path. -- VFX clarifies state instead of obscuring collisions. -- Background contrast does not swallow dark objects. - -## Performance Checks - -After render changes, report the renderer diagnostics from `references/technical-art.md` (calls, triangles, geometries, textures, materials, DPR/post/shadow settings), plus FPS/frame time and composer/post pass count when available. - -If performance drops, reduce post/shadow cost first, then cull/LOD/instance, then reduce asset density only where it is least visible. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/shader-cookbook.md b/.agents/skills/threejs-aaa-graphics-builder/references/shader-cookbook.md deleted file mode 100644 index 76b5d37570..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/shader-cookbook.md +++ /dev/null @@ -1,286 +0,0 @@ -# Shader And Material Cookbook - -Concrete material, shader, and post-processing recipes. Use with `references/technical-art.md` (budgets, when shader work is justified) and `references/render-recipes.md` (render pipeline). - -Targets three.js `^0.184`; imports use the `three/addons/*` alias (maps to `examples/jsm`). Every entry lists **When**, **Cost** (draw calls / fill rate / compile), and **Read** (the rule: effects clarify gameplay, never hide missing geometry). - -## Prerequisite: Renderer And Environment Map - -Metals and glossy dielectrics read as flat gray without an environment map to reflect. Set this up once before PBR materials. - -```ts -import * as THREE from 'three'; -import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; - -renderer.outputColorSpace = THREE.SRGBColorSpace; -renderer.toneMapping = THREE.ACESFilmicToneMapping; // simpler tone mapping for bright arcade reads -renderer.toneMappingExposure = 1.0; -renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); - -// 5-line env map: neutral studio IBL, no HDR file needed. -const pmrem = new THREE.PMREMGenerator(renderer); -scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; // r184: RoomEnvironment() takes no args -scene.environmentIntensity = 1.0; // r184 global multiplier over per-material envMapIntensity -pmrem.dispose(); -``` - -Needed by any scene with metal, ceramic, glass, or clearcoat. Cost is one PMREM bake at startup, near-zero per frame; it lights support surfaces so hero emissive/trim still wins attention. - -## PBR Material Recipes - -Copy the config; tune `color` to the palette. `envMapIntensity` values assume the env map above. Use `MeshStandardMaterial` unless a `MeshPhysicalMaterial`-only feature (clearcoat, transmission, sheen) is visible during play. - -```ts -// Painted metal (car body, ship hull panel) — dielectric paint over metal read via clearcoat. -new THREE.MeshPhysicalMaterial({ color: 0x1f6feb, metalness: 0.0, roughness: 0.5, - clearcoat: 0.9, clearcoatRoughness: 0.15, envMapIntensity: 1.0 }); - -// Bare brushed metal (raw steel, gun frame) — needs the env map to look metallic. -new THREE.MeshStandardMaterial({ color: 0xaeb4bd, metalness: 1.0, roughness: 0.4, envMapIntensity: 1.1 }); - -// Rubber / tire — near-black, no reflection, kills the env map. -new THREE.MeshStandardMaterial({ color: 0x0a0a0b, metalness: 0.0, roughness: 0.92, envMapIntensity: 0.35 }); - -// Matte plastic (housings, crates) — dielectric, mid roughness, muted reflection. -new THREE.MeshStandardMaterial({ color: 0xd23b3b, metalness: 0.0, roughness: 0.62, envMapIntensity: 0.6 }); - -// Glossy ceramic / clean hull — sharp reflection, add clearcoat for wet-look premium. -new THREE.MeshPhysicalMaterial({ color: 0xf5f5f5, metalness: 0.0, roughness: 0.12, - clearcoat: 1.0, clearcoatRoughness: 0.05, envMapIntensity: 1.0 }); - -// Emissive signal (beacon, pickup core) — dark base so only the glow reads; >1 intensity feeds bloom. -new THREE.MeshStandardMaterial({ color: 0x101010, emissive: 0x18e0ff, emissiveIntensity: 2.5, - metalness: 0.0, roughness: 0.4 }); - -// Cloth / fabric — high roughness + sheen for the soft edge highlight. -new THREE.MeshPhysicalMaterial({ color: 0x3a4a6b, metalness: 0.0, roughness: 0.9, - sheen: 1.0, sheenRoughness: 0.5, sheenColor: new THREE.Color(0x8899bb), envMapIntensity: 0.5 }); -``` - -**Read:** separate roles by roughness/metalness contrast (matte vs glossy, metal vs plastic), not hue alone. - -### Glass: real vs fake - -```ts -// REAL refractive glass — MeshPhysicalMaterial transmission. -new THREE.MeshPhysicalMaterial({ metalness: 0.0, roughness: 0.05, transmission: 1.0, - thickness: 0.5, ior: 1.5, envMapIntensity: 1.0 }); -``` - -- **When:** one or two hero surfaces (cockpit canopy, potion vial) at close range. -- **Cost:** high. Each transmissive material triggers an extra scene render into a transmission buffer every frame; fill-rate heavy and multiplies with resolution. Never use on repeated/instanced props. -- **Read:** refraction must not smear the hazard behind it into unreadability. - -```ts -// CHEAP fake glass — no transmission buffer. Use for repeated windows, visors, shields. -new THREE.MeshPhysicalMaterial({ color: 0x88ccff, metalness: 0.0, roughness: 0.1, - transparent: true, opacity: 0.25, clearcoat: 1.0, envMapIntensity: 1.5, depthWrite: false }); -``` - -- **Cost:** one transparent draw call, no extra render target. Add the fresnel rim below for a readable edge. - -## onBeforeCompile Patterns - -Inject GLSL into stock materials to keep PBR lighting for free. Rules that make this safe with shared materials: - -- **Cache key:** any material whose `onBeforeCompile` injects code MUST set `customProgramCacheKey` returning a string unique to that injection. Without it three can hand back a cached program compiled from a different (un-injected) material of the same type, silently dropping your code. -- **Sharing:** `onBeforeCompile` runs once per compiled program. Reuse one material instance across meshes and its uniforms update once for all. For per-object variation, use separate material instances (same cache key → program is still reused) or drive it from `instanceMatrix` / `instanceColor`. -- **Animating uniforms:** `onBeforeCompile` fires once, so stash the shader (`material.userData.shader = shader`) and write the uniform each frame: `if (m.userData.shader) m.userData.shader.uniforms.uTime.value = t;`. The snippets below use this pattern. - -### (a) Fresnel rim glow - -`vNormal` and `vViewPosition` (both view space) exist in the Standard/Physical fragment shader; `saturate` is defined in ``. - -```ts -material.onBeforeCompile = (shader) => { - shader.uniforms.uRimColor = { value: new THREE.Color(0x33ccff) }; - shader.uniforms.uRimPower = { value: 3.0 }; - shader.uniforms.uRimStrength = { value: 1.5 }; - shader.fragmentShader = - 'uniform vec3 uRimColor;\nuniform float uRimPower;\nuniform float uRimStrength;\n' + - shader.fragmentShader.replace( - '#include ', - `#include - float fres = pow(1.0 - saturate(dot(normalize(vNormal), normalize(vViewPosition))), uRimPower); - totalEmissiveRadiance += uRimColor * fres * uRimStrength;` - ); -}; -material.customProgramCacheKey = () => 'fresnel-rim'; -``` - -- **When:** shields, cloak/invuln states, silhouette separation from a busy background. -- **Cost:** a few ALU ops, no extra passes. -- **Read:** the rim marks a state change; keep base color readable when the rim is off. - -### (b) Scrolling emissive panels - -Inject a private UV varying so it works without a map assigned. - -```ts -material.onBeforeCompile = (shader) => { - shader.uniforms.uTime = { value: 0 }; - shader.uniforms.uPanelColor = { value: new THREE.Color(0x18e0ff) }; - material.userData.shader = shader; - shader.vertexShader = 'varying vec2 vCookUv;\n' + shader.vertexShader.replace( - '#include ', '#include \n vCookUv = uv;'); - shader.fragmentShader = - 'uniform float uTime;\nuniform vec3 uPanelColor;\nvarying vec2 vCookUv;\n' + - shader.fragmentShader.replace( - '#include ', - `#include - float scroll = fract(vCookUv.y * 6.0 - uTime * 0.5); - float band = smoothstep(0.46, 0.5, scroll) * smoothstep(0.54, 0.5, scroll); - totalEmissiveRadiance += uPanelColor * band * 2.0;` - ); -}; -material.customProgramCacheKey = () => 'scroll-emissive'; -``` - -- **When:** energy conduits, reactor walls, loading/charge bars, boost lanes. -- **Cost:** one `fract`/`smoothstep`, no textures. -- **Read:** scroll direction/speed should encode state (charging up, draining down). - -### (c) Wind sway (foliage / flags) - -`transformed` is object space and displaced before `` applies `instanceMatrix`, so read the instance translation column for per-instance phase. Assumes model origin at the base, up = +Y. - -```ts -material.onBeforeCompile = (shader) => { - shader.uniforms.uTime = { value: 0 }; - material.userData.shader = shader; - shader.vertexShader = 'uniform float uTime;\n' + shader.vertexShader.replace( - '#include ', - `#include - #ifdef USE_INSTANCING - float phase = instanceMatrix[3].x + instanceMatrix[3].z; // instance world offset - #else - float phase = 0.0; - #endif - float h = max(position.y, 0.0); // base stays planted, tips move most - transformed.x += sin(uTime * 1.5 + phase) * 0.08 * h; - transformed.z += cos(uTime * 1.1 + phase) * 0.05 * h;` - ); -}; -material.customProgramCacheKey = () => 'wind-sway'; -``` - -- **When:** grass cards, banners, antennae, kelp — background life, not gameplay geometry. -- **Cost:** two trig ops per vertex; free on an `InstancedMesh`. -- **Read:** sway is ambient motion; never move collidable/interactable geometry with it. - -### (d) Dissolve / spawn - -Threshold-discard with a glowing edge. Inject a local-position varying and a hash; drive `uProgress` 0→1 to despawn, 1→0 to spawn. - -```ts -material.onBeforeCompile = (shader) => { - shader.uniforms.uProgress = { value: 0 }; - shader.uniforms.uEdgeColor = { value: new THREE.Color(0xff6a00) }; - material.userData.shader = shader; - shader.vertexShader = 'varying vec3 vDisPos;\n' + shader.vertexShader.replace( - '#include ', '#include \n vDisPos = position;'); - shader.fragmentShader = - `uniform float uProgress;\nuniform vec3 uEdgeColor;\nvarying vec3 vDisPos; - float hash13(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); }\n` + - shader.fragmentShader.replace( - '#include ', - `float n = hash13(floor(vDisPos * 12.0)); - if (n < uProgress) discard; - float edge = smoothstep(uProgress, uProgress + 0.08, n); - gl_FragColor.rgb += uEdgeColor * (1.0 - edge) * 3.0; // post-tonemap add feeds bloom - #include ` - ); -}; -material.customProgramCacheKey = () => 'dissolve'; -``` - -- **When:** enemy death, teleport-in, pickup spawn, object streaming. -- **Cost:** one hash + `discard` (discard disables early-Z; keep it to spawning objects, not the whole scene). -- **Read:** the edge color/direction telegraphs the event — spawn vs destroy must look different. - -## Gradient Sky Dome - -Cheaper than a cubemap for stylized scenes: a `BackSide` sphere with a top/horizon lerp plus a sun disc and halo. - -```ts -const skyUniforms = { - uTop: { value: new THREE.Color(0x3a6fb0) }, - uHorizon: { value: new THREE.Color(0xcfe4f5) }, - uSunColor: { value: new THREE.Color(0xfff2cc) }, - uSunDir: { value: new THREE.Vector3(0.4, 0.28, 0.6).normalize() }, -}; -const sky = new THREE.Mesh( - new THREE.SphereGeometry(500, 32, 16), - new THREE.ShaderMaterial({ - side: THREE.BackSide, depthWrite: false, uniforms: skyUniforms, - vertexShader: `varying vec3 vDir; - void main(){ vDir = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`, - fragmentShader: `varying vec3 vDir; - uniform vec3 uTop, uHorizon, uSunColor, uSunDir; - void main(){ - float h = clamp(vDir.y * 0.5 + 0.5, 0.0, 1.0); - vec3 col = mix(uHorizon, uTop, pow(h, 0.6)); - float d = clamp(dot(normalize(vDir), normalize(uSunDir)), 0.0, 1.0); - col += uSunColor * (pow(d, 800.0) + pow(d, 8.0) * 0.25); // disc + halo - gl_FragColor = vec4(col, 1.0); - }`, - }) -); -sky.frustumCulled = false; -scene.add(sky); -``` - -- **When:** any stylized outdoor scene without a photographic backdrop. -- **Cost:** one draw call, no cubemap textures, no mips. -- **Read:** a raw `ShaderMaterial` bypasses tone mapping and sRGB conversion — author colors in display space; if the scene runs ACES, nudge them brighter. Keep horizon value distinct from hazards silhouetted against it. - -## Post-Processing Chain - -Finishing pass only. Move tone mapping/sRGB to `OutputPass`; keep `renderer.toneMapping` set so it reads it. - -```ts -import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; -import { RenderPass } from 'three/addons/postprocessing/RenderPass.js'; -import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js'; -import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js'; -import { OutputPass } from 'three/addons/postprocessing/OutputPass.js'; - -const composer = new EffectComposer(renderer); -composer.addPass(new RenderPass(scene, camera)); - -// UnrealBloomPass(resolution, strength, radius, threshold) -const bloom = new UnrealBloomPass(new THREE.Vector2(innerWidth, innerHeight), - 0.45, // strength: 0.35-0.6 - 0.3, // radius: 0.2-0.4 - 0.85); // threshold: only pixels brighter than this bloom -composer.addPass(bloom); - -const VignetteShader = { - uniforms: { tDiffuse: { value: null }, uStrength: { value: 0.85 }, uSize: { value: 0.72 } }, - vertexShader: `varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`, - fragmentShader: `uniform sampler2D tDiffuse; uniform float uStrength, uSize; varying vec2 vUv; - void main(){ - vec4 c = texture2D(tDiffuse, vUv); - float d = distance(vUv, vec2(0.5)); - c.rgb *= mix(1.0, smoothstep(uSize, uSize - 0.45, d), uStrength); - gl_FragColor = c; - }`, -}; -composer.addPass(new ShaderPass(VignetteShader)); -composer.addPass(new OutputPass()); // ALWAYS last: tone mapping + sRGB - -// loop: composer.render() instead of renderer.render() -// resize: composer.setSize(w, h); composer.setPixelRatio(Math.min(devicePixelRatio, 2)); -``` - -- **Bloom rule:** bloom sells authored emissive (threshold 0.85 keeps mid-bright materials out). It must never be the main source of detail — if a shape only reads because it glows, the geometry is missing. -- **Vignette cost:** one full-screen ShaderPass; keep `uStrength` subtle, never darken the play path. -- **Mobile:** the composer allocates full-resolution HDR targets, so cost scales with DPR². Cap DPR before adding passes. On low-end, skip the composer (call `renderer.render`) or run bloom-only via `composer.setPixelRatio(Math.min(devicePixelRatio, 1.25))`. Compare screenshots with post on/off and profile. - -## Cheap Tricks - -- **Vertex-color AO** — bake occlusion into the mesh: `geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3))`, material `{ vertexColors: true }`, darken cavities/creases. **When:** static props/terrain. **Cost:** one attribute, zero draw calls. **Read:** ground shapes with contact darkness; don't tint gameplay-critical surfaces. -- **Polygon-offset decals** — coplanar decal mesh with `{ polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1, transparent: true }` to kill z-fighting. **When:** panel lines, numbers, faction glyphs. **Cost:** +1 draw call each — instance repeats. **Read:** decals imply function/scale, not random surface noise. -- **Fake contact shadow** — flat `PlaneGeometry` with a radial-gradient `CanvasTexture`, `{ transparent: true, depthWrite: false }`, under the object; scale/fade alpha with height. **When:** hovering or moving props that don't warrant a shadow map. **Cost:** one draw call, no shadow pass. **Read:** anchors floating objects so position reads. -- **Emissive LOD signals** — swap `emissiveIntensity` or material by distance so far pickups/beacons still read, add geometry detail only up close. **When:** dense repeated signals. **Cost:** a material/uniform swap. **Read:** keep the signal color constant across LOD so identity survives the transition. -- **Matcap props** — `new THREE.MeshMatcapMaterial({ matcap })` bakes lighting into one texture; no lights or env needed. **When:** background/stylized props. **Cost:** the cheapest lit-looking material, one texture. **Read:** matcap ignores scene lights, so never use it where a dynamic light or state glow must show on the surface. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/technical-art.md b/.agents/skills/threejs-aaa-graphics-builder/references/technical-art.md deleted file mode 100644 index aab27be1df..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/technical-art.md +++ /dev/null @@ -1,167 +0,0 @@ -# Technical Art For Three.js Games - -Use this reference before premium/AAA/showcase graphics work, shader/material/post-processing changes, VFX systems, generated/imported asset cleanup, LOD/instancing work, or any visual pass that could affect browser performance. - -Technical art is the bridge between art direction and real-time constraints. The goal is not maximum detail; it is readable authored detail that survives active gameplay, mobile viewports, and WebGL budgets. - -Research basis: Three.js exposes renderer diagnostics through `WebGLRenderer.info`; `InstancedMesh` is designed for many objects sharing geometry/materials; `LOD` switches objects by distance; `KTX2Loader` supports Basis Universal GPU texture workflows; MDN WebGL best practices emphasize eliminating errors, understanding system limits, eager deletion, batching draw calls, per-pixel VRAM budgets, smaller back buffers, mipmaps, compressed textures, and high-DPI discipline. - -## Technical Art Brief - -Before implementation, write: - -- Art direction in renderable terms: shapes, materials, lighting, VFX, camera, UI/world motifs. -- Hero surfaces: what must look authored at active-play distance. -- Support surfaces: what can be procedural, instanced, simplified, or culled. -- Material kit: named roles, not one-off colors. -- VFX language: event-driven effects and state readability. -- Lighting stack: key/fill/rim/practical/contact/depth. -- Render budget target: draw calls, triangles, textures, materials, DPR, shadow/post cost. -- Asset strategy: procedural / generated 2D / generated 3D / hybrid / imported. -- Mobile constraint: what changes first if performance or readability fails. - -## Render Budget Starting Points - -These are starting contracts, not universal limits — measure on the target game, and document every deliberate overrun as a tradeoff. The canvas inspector (`npm run inspect:canvas`) compares live diagnostics against the same numbers and reports over-budget rows. - -| Metric (worst active-play view) | Desktop tier | Mobile tier | -| --- | --- | --- | -| Draw calls (`info.render.calls`) | <= 300 | <= 150 | -| Triangles (`info.render.triangles`) | <= 750k | <= 300k | -| Geometries (`info.memory.geometries`) | <= 300 | <= 200 | -| Textures (`info.memory.textures`) | <= 60 | <= 40 | -| Texture memory (est.) | <= 256 MB | <= 128 MB | -| Shadow-casting lights | <= 2 | 1 | -| Shadow map size | <= 2048 | <= 1024 | -| DPR cap | 2 | 1.5-2 | -| Post passes (beyond render+output) | <= 2 | 0-1 | - -How to spend within them: - -- Draw calls: repeated world/detail pieces should be instanced or merged by material. -- Triangles: spend on silhouettes near the camera; reduce background detail through LOD, impostors, or simplified meshes. -- Materials: share material roles aggressively. Unique material count often grows faster than geometry count. -- Textures: keep opaque large images compressed or small; avoid unique 2K+ textures for tiny repeated props. -- Shadows: reserve real shadows for hero objects and grounding anchors; use blob/contact meshes for small repeated props (see `references/shader-cookbook.md` for the cheap contact-shadow recipe). -- Post: every pass must earn its cost and preserve gameplay clarity; concrete chain settings are in `references/shader-cookbook.md`. - -Always report actual renderer diagnostics after the graphics pass: calls, triangles, geometries, textures, material count if available, post passes, shadow settings, DPR cap, and bottlenecks. - -## Material And Shader System - -Use a material kit of named shared roles, not one-off colors. Reuse each role across every mesh that plays the same part: - -- `bodyPrimary`: dominant player/world shell. -- `bodySecondary`: panel contrast. -- `trim`: rails, bevel highlights, borders, edge highlights. -- `hazard`: danger surfaces, damage cues, warning stripes. -- `reward`: collectible surfaces with readable value. -- `shieldBoost`: shield, boost, and status states. -- `glass`: cockpit, shield, lens, visor. -- `emissiveSignal`: authored glow strips, status lights, beacon cores. -- `groundContact`: dark matte surfaces and shadow receivers. -- `decalDark` and `decalLight`: panel lines, scratches, numbers, icons. -- UI/world signal colors shared between HUD and diegetic markers. - -Use `MeshStandardMaterial` for most surfaces. Use `MeshPhysicalMaterial` selectively for cockpit glass, clearcoat panels, iridescent shields, or premium hero details. Share materials across repeated meshes. - -Shader or `onBeforeCompile` work must have a reason: - -- State readability: shield ripple, heat, cloak, damage pulse. -- Surface identity: water, forcefield, hologram, scanline, energy core. -- Performance: cheap procedural variation instead of many textures. -- Composition: separating player/threat/reward from background. - -Reject shader work that only adds noise, bloom bait, or hidden cost without improving active-play decisions. When shader work is justified, use the proven recipes in `references/shader-cookbook.md` (material values, onBeforeCompile patterns, sky, post chain) instead of improvising GLSL. - -## VFX Readability - -Every VFX effect must answer: - -- What event or state triggers it? -- What does it tell the player? -- Does it point to player, threat, reward, objective, or impact? -- How long does it last? -- Is it pooled or cheap to recreate? -- Does it obscure collision, HUD, or the next decision? -- Is there a reduced-motion fallback for heavy shake/strobe? - -Use event-driven VFX over permanent particle clutter: - -- Pickup: ring contraction, shard burst, score trail, brief HUD echo. -- Hit/fail: impact ring, debris, damage flash, brief hit pause, camera impulse. -- Boost/speed: engine trail, lane streaks, FOV ease, side streaks, audio pitch. -- Near miss/combo: side spark, line snap, badge pulse, streak counter. -- Shield/invulnerable: refractive shell, rim pulse, absorbed-impact ripple, material swap. -- Spawn/despawn: anticipation pulse, telegraph, dissolve or scale snap. - -Pool effects and reuse geometries/materials. Permanent particle fields must stay cheap and sparse. - -## Instancing, LOD, And Culling - -Use instancing for many copies with the same geometry/material and different transforms: windows, bolts, lane markers, city lights, debris, foliage-like props, stars, crowd cards, track panels, repeated pickups, background modules. - -Rules: - -- Update `instanceMatrix.needsUpdate` and `instanceColor.needsUpdate` only after batched changes. -- Compute or update bounds for instanced groups when transforms change materially. -- Do not instance everything blindly. Different materials or constantly changing transforms can erase the win. -- Keep collision separate from instanced visual detail. - -Use LOD when: - -- A hero/background object spans large distance ranges. -- The silhouette matters near camera but not far away. -- Imported/generated models are heavier than needed for background use. - -Rules: - -- Add hysteresis or distance gaps to reduce visible popping. -- Use impostor cards or simplified silhouettes for far layers when appropriate. -- Verify LOD transitions during gameplay camera motion, not only static orbit. - -## Generated And Imported Asset Cleanup - -For every Tripo/imported GLB/FBX hero asset: - -- Confirm scale, pivot, forward/up orientation, bounds, and active-play silhouette. -- Create a simple collision proxy independent from the visual mesh. -- Inspect file size, approximate triangles, mesh count, material count, texture count, and animation clips when available. -- Replace or simplify excessive materials and textures. -- Add LOD or simplified background variant when reused many times. -- Verify PBR material readability under the game's lighting, not only in a model viewer. -- Keep API keys and temporary URLs out of client code and checked-in files. - -## Decals, Trim, And Surface Detail - -Prefer reusable surface systems: - -- Canvas-generated trim sheets for panel lines, markings, arrows, numbers. -- Thin offset decal meshes for hazard marks, faction symbols, lane glyphs, scuffs. -- Shared small textures for noise/wear rather than unique full-size images. -- Procedural UV-independent detail for repeated hard-surface props. - -Surface detail must reinforce scale, function, faction, route, or state. Do not add random lines everywhere. - -## Color And Readability - -Readability beats palette consistency: - -- Threats differ from rewards by shape and motion, not only hue. -- Interactables differ from background by silhouette/value/material. -- UI signal colors match world signal colors. -- Bloom/fog/darkness cannot be the primary separator. -- Colorblind-risk information has shape/icon/motion backup. - -## Technical Art Report - -Report: - -- Technical art brief. -- Material kit and shader/VFX decisions. -- Instancing/LOD/culling strategy. -- Render budget target and actual diagnostics. -- Imported/generated asset cleanup evidence. -- VFX readability checks. -- Mobile/DPR/post/shadow tradeoffs. -- Remaining visual performance risks. diff --git a/.agents/skills/threejs-aaa-graphics-builder/references/visual-scorecard.md b/.agents/skills/threejs-aaa-graphics-builder/references/visual-scorecard.md deleted file mode 100644 index b8c56daeca..0000000000 --- a/.agents/skills/threejs-aaa-graphics-builder/references/visual-scorecard.md +++ /dev/null @@ -1,147 +0,0 @@ -# Visual Scorecard - -Score active-play screenshots, not idle title screens or isolated showroom models. Use desktop and mobile screenshots when mobile is in scope. - -Scores are self-assessed against the anchors below, so they drift optimistic. Two countermeasures are mandatory for premium/AAA/showcase claims: cite Measured Evidence for the categories it supports, and run the Fresh-Eyes Review before finalizing. - -## Calibration Anchors - -Reference screenshots for score calibration are packaged in `threejs-aaa-graphics-builder/assets/scorecard-anchors/`: - -- `scene-1.jpg` — score ~1: primitive player and pickups on a flat sparse arena, utility HUD. -- `scene-2.jpg` — score ~2: authored track kit, imported hero asset, designed genre HUD, intentional lighting. -- `scene-3.jpg` — score ~2.5-3: dense layered world in active play, readable hero silhouette, event VFX, cohesive HUD. - -Before scoring World/environment, Hero/player, Materials/textures, or Lighting/render, view the anchors and compare: if your screenshot reads closer to `scene-1.jpg` than `scene-3.jpg` for that surface, the category is at most a 1-2 regardless of how much code was written. - -## Scoring Scale - -- 0: Placeholder. Default primitives, sparse world, unreadable state, debug UI, or no evidence. -- 1: Basic styled. Playable and themed, but still obvious prototype assets, flat composition, repeated silhouettes, or generic UI. -- 2: Premium stylized. Authored silhouettes, material/detail systems, readable state, cohesive UI/world, measured performance. -- 3: Showcase. Strong art direction, memorable hero and world, dense authored detail, excellent readability, polished VFX/rendering, and diagnostics. - -## Categories - -1. Art direction. - - 0: No clear theme. - - 1: Theme is mostly colors/fog. - - 2: Theme affects forms, materials, UI, world, and feedback. - - 3: Distinct identity visible in every surface. -2. Hero/player. - - 0: Default primitive stack. - - 1: Basic object with glow or simple attachments. - - 2: Authored silhouette, decals/trim, state cues, collision proxy. - - 3: Memorable model with layered construction and expressive feedback. -3. Obstacles/enemies. - - 0: Cubes/cones/spheres. - - 1: Recolored repeated silhouette. - - 2: Three readable variants with telegraphs and material cues. - - 3: Varied family with animation, anticipation, and gameplay clarity. -4. Rewards/interactables. - - 0: Plain sphere/ring/token. - - 1: Repeated object with simple glow. - - 2: Two authored forms with idle/collect states and UI feedback. - - 3: Desirable, animated, and clearly valued during motion. -5. World/environment. - - 0: Flat plane, empty arena, box skyline. - - 1: Themed but sparse repeated blocks. - - 2: Layered prop kit with foreground/midground/background and scale cues. - - 3: Dense authored world that supports gameplay readability. -6. Materials/textures. - - 0: Flat colors. - - 1: Basic roughness/metalness or emissive color. - - 2: Shared material roles, procedural decals, trim, panel lines, wear/noise. - - 3: Rich cohesive material language with measured texture/resource use. -7. Lighting/render. - - 0: Default lights or unreadable darkness. - - 1: Fog/bloom used as main style. - - 2: Intentional tone mapping, exposure, key/fill/rim, contact, depth. - - 3: Cinematic but readable composition with disciplined post-processing. -8. VFX/motion. - - 0: None or random particles. - - 1: Generic particles/trails. - - 2: Event-driven VFX for boost, pickup, hit, fail, combo, shield, or spawn. - - 3: High-impact effects that clarify gameplay and remain performant. -9. UI/HUD. - - 0: Debug text or missing UI. - - 1: Generic stat-card dashboard. - - 2: Genre-specific HUD states, meters/icons, responsive text fit. - - 3: Cohesive game interface with strong hierarchy and polished transitions. -10. Performance evidence. - - 0: No metrics after visual changes. - - 1: Informal "seems fine". - - 2: Renderer counts, build/browser QA, desktop/mobile screenshots, and technical-art budget notes. - - 3: Baseline/post metrics, bottleneck notes, budgets, optimized asset strategy, and VFX/readability tradeoffs. - -## Thresholds - -Premium: - -- Every category at least 2. -- Average at least 2.3. -- Desktop and mobile active-play screenshots captured when mobile is in scope. -- Renderer diagnostics reported after graphics changes. - -Showcase: - -- At least six categories score 3. -- No category below 2. -- Average at least 2.7. -- Performance evidence includes before/after or budget-aware notes. - -## Automatic Failures - -Any of these prevents a premium/AAA/showcase claim: - -- Active screenshot is primitive-dominant. -- Main world is mostly stretched boxes, flat planes, or a sparse arena. -- Hero asset is mostly default primitives plus glow. -- Obstacles or rewards are one repeated silhouette. -- HUD is mostly rectangular stat/debug cards. -- Fog, darkness, bloom, or particles hide missing authored geometry. -- UI overlaps the play path, clips text, or fails mobile safe areas. -- The game is not playable through real input. -- No active-play screenshot was captured. -- No renderer diagnostics were collected after major graphics work. -- No technical-art budget or imported/generated asset diagnostics were reported for premium graphics work. - -## Measured Evidence - -Run the canvas inspector (`npm run inspect:canvas`, or `threejs-qa-release/scripts/inspect-threejs-canvas.mjs`) on desktop and mobile and cite its `metrics` and `renderBudget` blocks in the scorecard. The numbers are advisory signals, not gates, but they must be reported and low values must be explained rather than ignored: - -- `colorEntropyBits` below ~3.0 or `dominantColorShare` above ~0.6 suggests a sparse, flat scene — supporting evidence against World/environment or Materials/textures scores above 2. -- `edgeDensity` below ~0.04 suggests primitive-dominant or empty framing — supporting evidence against World/environment and Hero/player scores above 2. -- `luminance.contrast` below ~60 suggests fog/darkness compression — supporting evidence against Lighting/render scores above 2. -- `renderBudget` rows over the tier budget require a documented tradeoff in the technical-art budget (see `references/technical-art.md`). -- Renderer diagnostics (calls, triangles, geometries, textures) back the Performance evidence category. - -## Fresh-Eyes Review - -The builder must not be the only grader. For premium/AAA/showcase claims: - -- If the runner supports subagents (Task tool or equivalent), spawn a reviewer with ONLY: the screenshots, this scorecard file, and the inspector metrics JSON. No build context, no prior scores. The reviewer must receive the COMPLETE capture set — every captured state, desktop and mobile — never a hand-picked subset; a curated selection can hide weak states or miss content the builder knows exists (capture states with the inspector's `--state` flag so nothing is gated behind live play). The reviewer fills the scorecard independently; reconcile by taking the lower score per category unless concrete evidence overturns it. Report both score sets. -- If subagents are unavailable, run an adversarial self-review before finalizing: for each category, write one sentence making the strongest case that the score is a 1, citing what is visible in the screenshot; only then assign the score. Include these sentences in the report. - -## Report Format - -```text -Visual scorecard: -- Art direction: before X / after Y - evidence: -- Hero/player: before X / after Y - evidence: -- Obstacles/enemies: before X / after Y - evidence: -- Rewards/interactables: before X / after Y - evidence: -- World/environment: before X / after Y - evidence: -- Materials/textures: before X / after Y - evidence: -- Lighting/render: before X / after Y - evidence: -- VFX/motion: before X / after Y - evidence: -- UI/HUD: before X / after Y - evidence: -- Performance evidence: before X / after Y - evidence: -Measured evidence: colorEntropyBits / edgeDensity / luminance.contrast / - dominantColorShare per viewport, renderer diagnostics, render budget rows -Fresh-eyes review: subagent scores or adversarial self-review notes -Average: -Automatic failures remaining: -``` - -If any category remains below threshold, state the exact next pass instead of declaring completion. diff --git a/.agents/skills/threejs-game-director/SKILL.md b/.agents/skills/threejs-game-director/SKILL.md deleted file mode 100644 index c1bee879cc..0000000000 --- a/.agents/skills/threejs-game-director/SKILL.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -name: threejs-game-director -description: "Primary entrypoint for complete Three.js browser game creation and premium iteration. Use by default for build-a-game, upgrade, polish, premium, AAA, high-fidelity, showcase, from-scratch, endless runner, arcade, action, or release-ready requests. Orchestrates sibling skills for gameplay, AAA graphics, UI, debug/profile, and QA/release, plus 3D/image/audio generators for characters, vehicles, weapons, buildings, props, skies, textures, logos, icons, GUI art, and SFX/voice. Keeps skill-loading, reference, asset-sourcing, and phase ledgers so users never choose skills manually." ---- - -# Three.js Game Director - -## Purpose - -Own the end-to-end game outcome. Build the playable loop, route through the right phases, verify evidence, and do not call prototype-quality work premium. "Less basic" from the user means the current visual level is rejected: treat it as the premium bar. - -## Runner Capability Check - -Before planning, note what this runner can do and adapt: - -1. **Invoke sibling skills directly?** Usually not — the runner invokes only this skill. Load sibling `SKILL.md` files with file-read tools instead. Never claim a skill was "invoked" when it was only loaded/read. -2. **Read files by path?** Resolve every skill and reference path through the path ladder below. If a required file cannot be read anywhere on the ladder, record the failure in the ledger and use `references/phase-playbook.md` as the fallback procedure for that phase. -3. **Run shell commands (node + python3)?** If yes, use the packaged scripts (scaffold creator, credential probe, canvas inspector, report audit). If not, ask the user to run each command and paste the output; never fabricate script output. -4. **Drive a browser / run Playwright?** If yes, capture screenshots and canvas inspection yourself. If not, ask the user to run `npm run verify:visual` and `npm run inspect:canvas` and paste the results; report unverified visuals as a residual risk, never as verified. - -### Skill Path Ladder - -Try in order, expanding `~` to the user's home directory when the read tool requires absolute paths: - -1. `..//SKILL.md` relative to this skill's directory -2. `~/.claude/skills//SKILL.md` -3. `~/.codex/skills//SKILL.md` -4. `~/.agents/skills//SKILL.md` -5. `skills//SKILL.md` in the repository source - -Reference files resolve the same way: `/references/.md`. Sibling skills point back to this ladder instead of restating it. - -## Sibling Skill Loading - -For broad work (complete, premium, AAA, polished, high-fidelity, showcase, from-scratch, upgrade, release-ready), load all five phase skills before implementation: `threejs-gameplay-systems`, `threejs-aaa-graphics-builder`, `threejs-game-ui-designer`, `threejs-debug-profiler`, `threejs-qa-release`. For narrow director-invoked work, load the directly relevant sibling plus `threejs-qa-release`. Do not skip sibling loading because this director bundles a phase playbook. - -Load generator skills before deciding generated assets are unnecessary, whenever their trigger surfaces exist in premium/AAA/showcase/complete/release-ready/"less basic" work: - -- `threejs-3d-generator/SKILL.md` — characters, creatures, bosses, vehicles, ships, weapons, buildings, signature props, complex pickups, hero environment pieces, rigging/animation, textured imports. -- `threejs-image-generator/SKILL.md` — concept/reference sheets, texture and material references, skies/backgrounds, logos, icons, decals, GUI/title/menu art, terrain/sky plates, image-to-3D inputs. -- `threejs-audio-generator/SKILL.md` — SFX, ambience, UI sounds, vehicle/weapon/boss audio, announcer/dialogue, voice conversion, audio cleanup. - -## External Asset Sourcing Gate - -- Never record "not-needed" for a generator before loading its `SKILL.md` when trigger surfaces exist. -- Before claiming an API key is unavailable, run the credential probe and paste its literal `KEY=SET|MISSING` output into the report. Each generator script also has its own `probe` subcommand. - -```bash -bash /scripts/probe_asset_credentials.sh -``` - -- For premium hero surfaces (player, enemy, boss, creature, vehicle, ship, weapon, building, signature prop), procedural-only is not an allowed final answer without real blocker evidence: a `MISSING` probe line, or an attempted generation command plus its API/network/quota error. Otherwise at least one high-value surface must show a 3D generator task ID, downloaded GLB/GLTF/FBX path, image generator output path, or documented hybrid chain. -- For premium active gameplay, missing audio is a reported gap unless the user asked for silent/offline output or the audio key/API is blocked. -- Fill the external asset sourcing ledger before the graphics phase. The ledger template and the allowed skip reasons live in `references/phase-playbook.md`. - -## Reference Gate - -References are phase-entry gates, not optional enrichment. The canonical per-phase Required References list lives in `references/phase-playbook.md`; load that file at planning time for broad work and at phase entry otherwise. - -- Load required references at phase entry, not at the end. -- Track every required reference in the reference ledger with yes/no/not-needed, path, and failure reason. -- A phase cannot be marked `done` until its required references are loaded, or the final answer reports the reference as unavailable and the phase as blocked/fallback. -- For premium/AAA/showcase claims, the final response must include the filled 10-category visual scorecard from `threejs-aaa-graphics-builder/references/visual-scorecard.md`, including measured evidence, average, and automatic failures remaining. Do not substitute a personal rubric. -- Thorough mode is the default for broad, premium, AAA, showcase, complete, and release-ready requests. Economy mode is allowed only for narrow fixes that do not claim premium quality. - -If Task/subagent/workflow tools are available, delegate each major phase to a focused worker with the phase `SKILL.md` plus its required references explicitly loaded. If unavailable, execute serially after loading the same files. - -## Ledgers - -Keep four ledgers: skill-loading, reference, external asset sourcing, and phase execution. Templates live in `references/phase-playbook.md`. - -Compaction rule: report every row that has meaningful state (yes/no/blocked/done/skipped plus path or evidence), and collapse consecutive `not-needed` rows into a single line naming them. Never omit or compress rows that carry real state. - -## Phase Routing - -- `threejs-gameplay-systems`: design brief, core loop contract, level/encounter plan, first playable slice, architecture, mechanics, entities, input, camera, physics selection, game feel. -- External asset sourcing: credential probe, generator skill loading, source decision per surface, task IDs/output files or blocker evidence. Must complete before the graphics phase is `done` for premium work. -- `threejs-aaa-graphics-builder`: basic-looking screenshots, asset architecture, models, materials, technical art, shaders, VFX, lighting/render, visual scorecard. -- `threejs-game-ui-designer`: HUDs, menus, overlays, responsive UI, icons, safe areas, UI states. -- `threejs-debug-profiler`: blank canvas, render/runtime bugs, loading, resize, mobile input/render bugs, performance profiling. -- `threejs-qa-release`: browser QA, screenshots, canvas pixels, responsive checks, visual test harness decision, bot playtest, production build, preview, release notes. -- `threejs-3d-generator` / `threejs-image-generator` / `threejs-audio-generator`: external AI-generated 3D models and rigs, 2D concepts/textures/logos/GUI art, and SFX/ambience/voice. - -When a sibling skill file is loaded, follow its workflow for that phase. Phase entry/exit evidence, ledger templates, and the fallback procedure for unloadable siblings all live in `references/phase-playbook.md`. - -## Packaged Runtime Resources - -New projects use the gameplay skill's scaffold creator; canvas verification uses the generated game's `npm run inspect:canvas` or the QA skill's packaged inspector: - -```bash -python3 /scripts/create_threejs_game.py ./my-game -node /scripts/inspect-threejs-canvas.mjs --url http://127.0.0.1:5188 -``` - -## Premium Completion Rule - -Premium, AAA, polished, complete, release-ready, and showcase requests require visible quality across gameplay, hero/player, obstacles/enemies, rewards/interactables, world kit, HUD/menu states, render/lighting/materials, feel, performance/mobile, and QA. If screenshots are dominated by primitives, flat roads/arenas, generic stat cards, sparse worlds, or glow-only detail, the task is not done. The full completion gate is in `references/phase-playbook.md`. - -## Required Verification - -- Build/typecheck; local browser run; console/page error check. -- Game design brief, core loop contract, and level/encounter plan for broad game creation or major gameplay changes. -- Active desktop and mobile screenshots plus nonblank canvas pixel evidence. -- Main input/objective/fail-or-restart path exercised. -- Visual scorecard with measured evidence for premium/AAA claims, plus a fresh-eyes review pass per `threejs-aaa-graphics-builder/references/visual-scorecard.md`. -- External asset sourcing ledger, credential probe output, and real external outputs or blocker evidence for premium asset-category claims. -- Audio evidence or a reported blocker for premium active-gameplay claims. -- Renderer diagnostics when graphics changed; technical art budget and VFX/readability evidence when premium graphics changed. -- Visual test harness decision, and bot playtest evidence when release-ready gameplay is claimed. -- Final ledgers with evidence and remaining blockers. - -## Report Audit - -When shell tools are available, draft the final evidence report to a markdown file and audit it before finalizing broad or premium work: - -```bash -python3 /scripts/audit_reference_report.py --premium /path/to/final-report.md -``` - -Use `--premium` for premium/AAA/showcase/high-fidelity/polished/complete/release-ready/"less basic" claims; add `--physics` for physics-heavy games; add `--audio` when generated or integrated audio is in scope; add `--no-design` only for debug/perf/QA-only reports with no gameplay claims. If the audit fails, fix the missing sections or state the exact blocker instead of claiming completion. If the script is unavailable, manually enforce the same sections listed in Required Verification. - -## Final Response - -Report the ledgers (compacted per the rule above), game design brief, core loop contract, level/encounter plan, files changed, run URL, controls, verification commands, screenshots/artifacts, renderer/performance notes, technical art budget, visual test harness decision, quality gates passed, skipped phases, and remaining risks. For premium/AAA/showcase claims, include the filled visual scorecard with measured evidence and automatic failures remaining. Be precise: "invoked" means a slash/tool skill invocation; "loaded" means the file was read into context; "executed phase" means the work was performed under loaded skill guidance or the phase playbook. diff --git a/.agents/skills/threejs-game-director/agents/openai.yaml b/.agents/skills/threejs-game-director/agents/openai.yaml deleted file mode 100644 index 6cf64d6dcb..0000000000 --- a/.agents/skills/threejs-game-director/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Three.js Game Director" - short_description: "Orchestrate complete Three.js games" - default_prompt: "Load threejs-game-director/SKILL.md (try ~/.codex/skills/threejs-game-director/SKILL.md, then ~/.claude/skills, ~/.agents/skills, or repo skills/) and follow it exactly, including the runner capability check, sibling skill loading, ledgers, reference gates, and required verification. Non-negotiables: start broad game work with a design brief, core loop contract, and level/encounter plan; run the credential probe and load the generator skills before deciding generated assets are unnecessary; run the report audit when shell tools are available; do not call prototype-quality work premium." diff --git a/.agents/skills/threejs-game-director/references/phase-playbook.md b/.agents/skills/threejs-game-director/references/phase-playbook.md deleted file mode 100644 index 7f862aeea8..0000000000 --- a/.agents/skills/threejs-game-director/references/phase-playbook.md +++ /dev/null @@ -1,218 +0,0 @@ -# Director Phase Playbook - -The canonical phase specification for `threejs-game-director`. Load this file at planning time for broad work. When a sibling skill file is loaded, that sibling owns its phase's workflow and this file supplies phase entry/exit evidence, ledger templates, and gate details. When a sibling `SKILL.md` cannot be loaded, the matching phase section here is the fallback procedure — record the missing path and reason in the ledger; the fallback is never a reason to skip attempting sibling loading first. - -Path resolution for every file named here uses the Skill Path Ladder in `threejs-game-director/SKILL.md`. - -## Non-Negotiable Rules - -- Do not claim another skill was invoked unless the runner actually invoked it; "loaded" means its file was read into context. -- Broad game builds start with a compact game design brief, core loop contract, and level/encounter plan before implementation. -- Load each phase's required reference files at phase entry, not at final judgment. A phase cannot be `done` if its required references were skipped. -- Record an external asset sourcing ledger before the graphics phase; run the credential probe before claiming any generator key is unavailable. -- Premium graphics phases include a technical-art budget and readability pass, not only visual polish. -- QA phases decide whether a visual test harness is warranted and report added/extended/skipped evidence. -- A broad request is not complete at first playable slice when the user asked for premium, AAA, polished, showcase, complete, release-ready, or "less basic". -- Prefer a small authored vertical slice over a larger placeholder scene. Treat primitive-dominant models, box skylines, flat arenas, generic stat-card HUDs, and glow/fog-only detail as prototype placeholders. -- Verify through browser evidence before calling the game done. - -## Ledger Templates - -Compaction rule (from `SKILL.md`): report every row with meaningful state; collapse consecutive `not-needed` rows into one line naming them. - -```text -Skill-loading ledger: -- Director: active -- Gameplay systems: yes/no, path or reason: -- AAA graphics: yes/no, path or reason: -- UI: yes/no, path or reason: -- Debug/profile: yes/no, path or reason: -- QA/release: yes/no, path or reason: -- 3D generator: yes/no/not-needed, path or reason: -- Image generator: yes/no/not-needed, path or reason: -- Audio generator: yes/no/not-needed, path or reason: - -External asset sourcing ledger: -- Credential probe output: -- Hero/player source: -- Enemies/vehicles/weapons source: -- Signature props/pickups source: -- World/sky/background source: -- Materials/textures/decals source: -- Logos/icons/GUI art source: -- Audio/SFX/voice source: -- Chosen sources per surface: procedural / threejs-image-generator / threejs-3d-generator / threejs-audio-generator / hybrid -- External assets generated: yes/no, outputs (task IDs / file paths) or skip reason: -- Audio assets generated: yes/no/not-needed, outputs or skip reason: - -Reference ledger: one yes/no/not-needed row with path or reason per required -reference that applies to the task (see Required References below). - -Phase ledger: -- Gameplay systems: pending/running/done/skipped - evidence: -- External asset sourcing: pending/running/done/skipped - evidence: -- AAA graphics: pending/running/done/skipped - evidence: -- UI: pending/running/done/skipped - evidence: -- Debug/profile: pending/running/done/skipped - evidence: -- QA/release: pending/running/done/skipped - evidence: -``` - -Mark a phase `done` only after implementation plus verification evidence. If a phase is skipped, state why it is out of scope or blocked. - -## Allowed External-Generation Skip Reasons - -After the relevant generator skills are loaded, actual external generation may be skipped only when: - -- The user explicitly requested no external AI/assets or offline-only output. -- Credential probe output shows the relevant key is `MISSING`. -- A real API/network/quota error occurs after an attempted generation command; include the command and error summary. -- The surface is a repeated low-value prop better handled by instancing/procedural kits. -- A non-hero repeated/support surface already scores 2+ and the ledger explains why external generation would not improve the active screenshot. - -Do not write `not-needed` for a generator skill before loading it when trigger surfaces are present. The hero-surface evidence rule is in `threejs-game-director/SKILL.md` (External Asset Sourcing Gate). - -## Required References - -Load these files before the matching phase starts: - -- Gameplay systems: `threejs-gameplay-systems/references/gameplay-workflows.md` -- Game design and level design, for broad new-game creation, major gameplay upgrades, level/arena/track/wave/hole/puzzle work, encounter design, progression/difficulty work, or premium gameplay claims: `threejs-gameplay-systems/references/game-design-level-design.md` -- Game feel, for feel/juice/impact tuning or any premium/polished gameplay claim: `threejs-gameplay-systems/references/game-feel.md` -- Physics selection, when physics/collision-heavy gameplay is in scope: `threejs-gameplay-systems/references/physics-engine-selection.md` -- New-game checklist, when creating a game or first playable slice: `threejs-gameplay-systems/references/checklists/new-game-definition-of-done.md` -- Game design and level design checklist, when creating a game, upgrading major gameplay, designing levels/encounters, or claiming premium gameplay: `threejs-gameplay-systems/references/checklists/game-design-level-design.md` -- Game feel checklist, when tuning feel or claiming premium gameplay: `threejs-gameplay-systems/references/checklists/game-feel.md` -- Endless runner checklist, when building or upgrading an endless runner: `threejs-gameplay-systems/references/checklists/endless-runner-premium-quality.md` -- AAA graphics, for any graphics phase: `threejs-aaa-graphics-builder/references/visual-scorecard.md`, `threejs-aaa-graphics-builder/references/implementation-blueprint.md`, `threejs-aaa-graphics-builder/references/model-recipes.md`, and `threejs-aaa-graphics-builder/references/render-recipes.md` -- Shader and material cookbook, for premium/AAA/showcase graphics or custom shader/material/post-processing work: `threejs-aaa-graphics-builder/references/shader-cookbook.md` -- Technical art, for premium/AAA/showcase graphics, shaders/material systems, VFX systems, generated/imported asset cleanup, LOD/instancing, or visual performance work: `threejs-aaa-graphics-builder/references/technical-art.md` -- AAA graphics checklists, for premium/AAA/showcase claims: `threejs-aaa-graphics-builder/references/checklists/aaa-game-quality-gate.md` and `threejs-aaa-graphics-builder/references/checklists/aaa-visual-scorecard.md` -- Technical art checklist, for premium/AAA/showcase graphics or visual performance claims: `threejs-aaa-graphics-builder/references/checklists/technical-art-quality.md` -- UI: `threejs-game-ui-designer/references/ui-patterns.md` -- UI checklists, when UI/HUD/menu/touch layout is in scope: `threejs-game-ui-designer/references/checklists/game-ui-quality.md`, `threejs-game-ui-designer/references/checklists/hud-readability.md`, and `threejs-game-ui-designer/references/checklists/responsive-ui-fit.md` -- Debug/profile: `threejs-debug-profiler/references/debug-profile-checklists.md`, plus `threejs-debug-profiler/references/checklists/scene-debugging.md` or `threejs-debug-profiler/references/checklists/performance-profile.md` when debugging or profiling -- QA/release: `threejs-qa-release/references/qa-release-checklists.md`, plus for final verification `threejs-qa-release/references/checklists/visual-verification.md`, `threejs-qa-release/references/checklists/playtest-qa.md`, and `threejs-qa-release/references/checklists/release.md` -- Visual test harness, when premium/release-ready visual QA, generated asset visibility, UI regression protection, or screenshot baselines are warranted: `threejs-qa-release/references/visual-test-harness.md` and `threejs-qa-release/references/checklists/visual-test-harness.md` -- Bot playtest, for release-ready gameplay claims or difficulty/fairness verification: `threejs-qa-release/references/playtest-bot.md` and `threejs-qa-release/references/checklists/bot-playtest.md` -- 3D generator, when loaded by the external asset sourcing gate: `threejs-3d-generator/references/api-notes.md` and `threejs-3d-generator/references/threejs-integration.md` -- 3D plus image generator, when both are loaded: `threejs-3d-generator/references/image-generator-workflows.md` -- Audio generator, when loaded for a game: `threejs-audio-generator/references/audio-workflows.md` - -Prompt templates are packaged in `references/prompt-templates.md` under the director and relevant sibling skills. Load them only when the user asks for a reusable prompt or task template. - -## Phase 1: Discovery And Playable Contract - -- Inspect package scripts, dependencies, app structure, renderer setup, loop ownership, input, camera, UI, diagnostics, and existing screenshots. -- Define the design brief: player promise, target feeling, primary verb, objective, pressure, reward/progression, fail/retry, skill expression, and non-goals. -- Define the core loop contract: player verb, objective, pressure, reward, fail state, restart. -- Define the first level/encounter plan: spatial format, player start, first decision, first threat, first reward, landmarks, escalation, recovery beats, and readability. -- Define target devices and performance budget. If absent, assume desktop plus mobile browser, WebGL/WebGL2 fallback, and capped DPR. -- Identify the highest-risk surfaces: blank/broken canvas, no playable loop, weak controls, basic graphics, unreadable UI, or unverified release. - -Exit evidence: current scripts/dependencies known; game design brief, core loop contract, and level/encounter plan stated; phase ledger initialized. - -For a new project, use the gameplay skill's packaged scaffold creator: - -```bash -python3 /scripts/create_threejs_game.py ./my-game -``` - -## Phase 2: Gameplay Systems - -Build or repair the playable loop before visual depth. - -- Add renderer, scene, camera, resize, update loop, input intents, state machine, entities, collision or physics, scoring/progression, fail/retry, HUD state, audio/VFX hooks, and diagnostics. -- Implement from the design brief and level/encounter plan. Do not bolt mechanics onto a static scene after the fact. If the level/arena/track is decorative rather than decision-shaping, return to the plan before adding art. -- If the game is physics-heavy, load the physics selection reference, choose an engine explicitly, and prefer Rapier unless the task fits custom collision or a small cannon-es fallback. -- Keep ownership boundaries clear: `core`, `game`, `entities`, `systems`, `assets`, `ui`, `tests`. -- Tune movement, camera follow, FOV, acceleration, cooldowns, difficulty, and restart through short play loops. Apply the game-feel reference (hitstop, screenshake, easing, impact feedback) for premium/polished gameplay claims. -- Keep collision proxies simpler than detailed meshes; avoid multiple animation loops, duplicated state, and per-frame allocations in hot paths. -- Route all gameplay randomness through the scaffold's seeded RNG so the deterministic test hooks keep working. - -Exit evidence: build/typecheck passes; browser opens with nonblank canvas; main control path changes state; objective or score progresses; fail/retry path exists when relevant; game design/level checklist outcome reported for broad builds; game-feel checklist outcome reported for premium gameplay claims; physics engine choice, timestep, collider strategy, and diagnostics reported when physics is in scope; new-game checklist outcome reported for new games. - -## Phase 3: External Asset Sourcing - -Run before the premium graphics pass when trigger surfaces exist. - -- Run the credential probe and paste output. -- Load `threejs-3d-generator`, `threejs-image-generator`, and/or `threejs-audio-generator` when their trigger surfaces exist, plus their required references. -- Decide source per high-value surface: procedural / threejs-image-generator / threejs-3d-generator / threejs-audio-generator / hybrid. -- Generate at least one high-value external output for premium hero surfaces unless the probe or an attempted generation shows a real blocker. -- Record task IDs, downloaded GLB/GLTF/FBX paths, image/audio output paths, or blocker evidence. - -Exit evidence: credential probe output; generator rows in the skill-loading and reference ledgers; filled asset sourcing ledger; external outputs or blocker evidence. - -## Phase 4: AAA Graphics - -Use when screenshots look basic or the user asks for premium quality. - -- Score active-play screenshots across the ten scorecard categories before and after. -- Add production graphics architecture: material library, procedural textures, decals, model factories, world prop kit, VFX system, lighting/render pipeline, diagnostics. -- Add technical art architecture: material kit, shader/VFX purpose, instancing/LOD/culling strategy, imported asset cleanup plan, render budget with numeric targets, and mobile DPR/shadow/post tradeoffs. -- Use the shader cookbook for custom material/shader/post work instead of improvising unproven effects. -- Upgrade all visible surfaces, not only the player: hero, hazards, rewards, ground/track/arena, foreground props, background layers, interactable telegraphs, material variation, and state VFX. -- Use the generator skills per the asset sourcing ledger; complete Phase 3 before deciding procedural code is enough. -- Build authored forms (bevels, extrusions, curves, tubes, lathes, custom geometry, decals, trim, panel lines, instanced repeats, collision proxies) before adding lighting, tone mapping, shadows, fog, and post-processing. - -Exit evidence: before/after scorecard with all ten categories, average, and automatic failures remaining; measured evidence from canvas-inspector metrics (draw calls, triangles, pixel statistics) cited for the categories they support; active desktop and mobile screenshots; renderer diagnostics; technical art budget target vs actuals; imported asset diagnostics (task IDs, file paths, scale/bounds, collision proxy, animation clips) when generated 3D was used; no scorecard category below 2 for premium claims. - -## Phase 5: UI - -Use when HUD/menu/interface craft affects quality or readability. - -- Inventory gameplay, pause, settings, fail/retry, milestone/win, loading/error, and touch states. -- Replace utility stat-card grids with game-specific meters, compact clusters, icons, badges, alerts, cooldown rings, reticles, diegetic labels, and stateful overlays. -- Use stable dimensions, safe-area padding, fixed-width numeric fields, text fit, and responsive constraints. -- Wire UI to game state; avoid duplicated game rules inside UI code. UI must never block the player, threats, pickups, next decision, or critical touch controls. - -Exit evidence: desktop and mobile screenshots for relevant states; text-fit and overlap check; touch target and safe-area check when mobile is in scope; UI checklist outcomes. - -## Phase 6: Debug And Profile - -Use whenever the canvas is blank/broken, interaction fails, mobile behavior breaks, or visual changes add cost. - -- Reproduce locally and read console/page/network errors. -- Check canvas CSS size and drawing-buffer size, renderer/context, loop ownership, camera, near/far, lights, fog, transforms, materials, loaders, asset paths, and resize behavior. -- For performance, measure production preview where possible: FPS/frame time, draw calls, triangles, geometries, materials, textures, memory, bundle, and expensive post/shadows. -- Optimize one bottleneck at a time using instancing, shared resources, culling, LOD, pooling, adaptive DPR, cheaper shadows/post, and explicit disposal. - -Exit evidence: root cause or measured bottleneck stated; baseline/post metrics when optimizing; broken path retested. - -## Phase 7: QA And Release - -Use before calling broad work complete. - -- Run build/typecheck; start dev or preview server; check console/page/network errors. -- Capture active desktop and mobile screenshots; sample canvas pixels for nonblank and varied output using the generated game's `npm run inspect:canvas` or: - -```bash -node /scripts/inspect-threejs-canvas.mjs --url http://127.0.0.1:5188 -``` - -- Trigger main input, objective progression, fail/retry, and recent risky paths. -- Verify HUD text fit, safe areas, touch targets, resize, and mobile input. -- Decide whether to add or extend a visual test harness (Playwright screenshot baselines with deterministic test hooks); report added/extended/skipped. -- Run the bot playtest for release-ready gameplay claims; report time-to-first-fail, progression, and softlock evidence. -- For premium/AAA claims, run the fresh-eyes scorecard review per `threejs-aaa-graphics-builder/references/visual-scorecard.md`. -- For release, verify production preview, base path, static assets, debug gating, bundle/large assets, and deployment assumptions. - -Exit evidence: commands run with pass/fail; URL used; screenshot/artifact paths; inspector metrics JSON; visual test harness decision with states covered, thresholds, and flake risks; bot playtest results when run; issues fixed or listed with owners; residual risks. - -## Completion Gate - -For premium/AAA/showcase claims, all of these must be true: - -- Skill-loading, reference, and external asset sourcing ledgers are present. -- Credential probe output plus external output evidence or blocker evidence is present for premium asset-category claims. -- Playable loop works through real input; game design brief, core loop contract, and level/encounter plan are reported for broad builds. -- Active-play screenshots exist for desktop and mobile. -- Visual scorecard uses the authored rubric, cites measured evidence, has no category below 2, and averages at least 2.3. -- A fresh-eyes review pass confirmed or corrected the scorecard (subagent review, or the adversarial self-review fallback). -- HUD/menu states are readable and responsive. -- Renderer diagnostics and technical art budget target-vs-actuals exist after graphics changes. -- Visual test harness decision is reported; bot playtest evidence exists for release-ready gameplay claims. -- Build and browser QA passed or blockers are clearly reported. -- Physics-heavy games include engine choice, timestep, collider strategy, sensors, CCD use, and body/collider diagnostics. - -If any gate fails, continue iterating or report the exact blocker instead of calling the game premium. diff --git a/.agents/skills/threejs-game-director/references/prompt-templates.md b/.agents/skills/threejs-game-director/references/prompt-templates.md deleted file mode 100644 index f1f95b6498..0000000000 --- a/.agents/skills/threejs-game-director/references/prompt-templates.md +++ /dev/null @@ -1,127 +0,0 @@ -# Three.js Game Director Prompt Templates - -Reusable prompt templates packaged with this skill. Use only templates relevant to the current request, and adapt placeholders to the game/project context. - ---- - -# New Three.js Game Prompt - -Use `threejs-game-director` for a complete or premium Three.js browser game. It should automatically route through gameplay systems, AAA graphics, UI, debug/profile, and QA/release phases. - -Use `threejs-gameplay-systems` directly only when the requested output is explicitly a small first prototype or gameplay-system change. - -Game idea: -- Core verb: -- Objective: -- Camera: -- Visual tone: -- Target devices: -- Time budget: - -Requirements: -- Use TypeScript, Vite, and Three.js modules. -- Start with a compact game design brief, core loop contract, and level/encounter plan before implementation. -- Build a playable loop, not a static scene. -- Keep the first version small enough to verify quickly, then continue quality passes if the target is complete/premium. -- Include desktop keyboard input and mobile touch input when target devices include mobile. -- Add HUD feedback for objective, score, health, time, or state. -- For premium requests, replace prototype HUD/models/world detail with designed UI, procedural asset kits, technical art budget, and renderer diagnostics. -- During QA, decide whether a visual test harness is warranted; add/extend it for release-ready visual states or report the skip reason. -- Run build and visual verification before reporting done. - -Final response: -- list files created or changed -- describe playable controls -- report build, browser, console, screenshot, canvas-pixel, and viewport evidence -- report game design brief, level/encounter plan, technical-art budget, and visual-harness decision when in scope -- list remaining risks - ---- - -# AAA Three.js Game Pass Prompt - -Use `threejs-game-director` to upgrade this Three.js browser game from prototype-quality to premium showcase quality. - -Target: -- Genre: -- Core verb: -- Desired mood: -- Target devices: -- Performance budget: - -Automatic skill flow: -- Use `threejs-gameplay-systems` first for game design brief, core loop contract, level/encounter plan, controls, camera, impact, difficulty, and restart loop. -- Use the director's active-play screenshot scorecard first if screenshots exist or can be captured. -- Use `threejs-aaa-graphics-builder` when screenshots still look basic or when multiple graphics surfaces are weak. -- Use `threejs-game-ui-designer` for HUD, menus, overlays, icons, text fit, and touch UI. -- Use `threejs-debug-profiler` before and after expensive visual changes. -- Use `threejs-qa-release` before calling the pass complete, including a visual test harness decision when release-ready visual regression risk exists. - -Quality priorities: -- Prefer a smaller authored vertical slice over a larger placeholder game. -- Replace utility HUD boxes with designed, genre-specific interface states. -- Replace placeholder primitives with authored silhouettes and reusable procedural kits. -- Build a minimum premium asset set: hero/player, three obstacle/enemy variants, two reward/interactable variants, world prop kit, and material kit. -- Add a technical art brief: material kit, VFX language, instancing/LOD/culling strategy, imported asset cleanup, DPR/shadow/post tradeoffs, and render budget. -- Add depth layers, parallax, foreground/midground/background composition, and material contrast. -- Make rewards, threats, player state, and objectives readable during motion. -- Add feedback for speed, pickup, near miss, hit, fail, restart, streak, and milestone. -- Keep render cost visible through renderer diagnostics. - -Prototype rejection tests: -- Main world is mostly stretched boxes or flat planes. -- Player/hero asset is mostly default primitives with glow. -- Obstacles/pickups are one repeated silhouette. -- HUD is mostly rectangular stat cards. -- Fog/darkness/bloom hides missing geometry. - -Verification: -- Build and run locally. -- Capture desktop and mobile screenshots after interaction. -- Check console/page errors and nonblank canvas pixels. -- Check UI text fit, overlap, safe areas, and touch targets. -- Report draw calls, triangles, geometries, textures, and frame-time/FPS evidence when available. -- Report technical art budget/readability evidence and visual test harness added/extended/skipped. -- Compare against `threejs-aaa-graphics-builder/references/checklists/aaa-game-quality-gate.md`. -- Compare against `threejs-aaa-graphics-builder/references/checklists/aaa-visual-scorecard.md`. -- Do not report the task as premium-complete if any prototype rejection test still fails. - ---- - -# Premium Endless Runner Pass Prompt - -Use `threejs-game-director` to upgrade this endless runner into a premium, high-fidelity browser game. - -Current blockers: -- - -Runner-specific targets: -- Player avatar/vehicle silhouette: -- Obstacle families: -- Reward/readability language: -- World theme: -- Speed/impact feel: -- HUD states: - -Required upgrades: -- Replace simple stat-card HUDs with a genre-specific runner HUD: compact status, readable progress, combo/streak, overdrive/boost, fail/retry, pause/settings. -- Replace cube obstacles and basic pickups with distinct procedural model families that read instantly at speed. -- Build at least three obstacle families, two reward variants, one detailed player vehicle/avatar, and one reusable track/city prop kit. -- Add route/lane detail, near-field props, mid-field silhouettes, far parallax, and speed lines that do not hide hazards. -- Improve player avatar/vehicle detail: layered chassis/body, trim, emissive signals, animation, trail/wake, and readable collision footprint. -- Add hazard telegraphing, pickup magnet/collect feedback, near-miss feedback, speed ramp cues, milestone gates, and crash/retry polish. -- Tune camera FOV, follow lag, shake, roll, and effects for speed without disorientation. - -Avoid: -- Giant untextured skyline boxes as the main world detail. -- Glow as the only fidelity technique. -- HUD panels that look like debug readouts. -- Repeating the same obstacle silhouette too frequently. -- Effects that obscure the next lane decision. - -Verification: -- Use `threejs-gameplay-systems/references/checklists/endless-runner-premium-quality.md`. -- Capture desktop and mobile screenshots during action, not only idle. -- Report renderer diagnostics for worst-case visible segment. -- Play long enough to see speed ramp, pickups, hazards, fail/retry, and any boost state. -- If the screenshot still reads as road plus boxes plus basic pickups, continue modeling/world/UI passes instead of reporting done. diff --git a/.agents/skills/threejs-game-director/scripts/audit_reference_report.py b/.agents/skills/threejs-game-director/scripts/audit_reference_report.py deleted file mode 100755 index 9007ef669f..0000000000 --- a/.agents/skills/threejs-game-director/scripts/audit_reference_report.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python3 -"""Audit a Three.js game director final report for required skill evidence.""" - -from __future__ import annotations - -import argparse -import re -import sys -from pathlib import Path - - -BASE_REQUIRED = [ - "skill-loading ledger", - "reference ledger", - "phase ledger", - "gameplay systems", - "aaa graphics", - "ui", - "debug/profile", - "qa/release", -] - -# Required by default; skip with --no-design for debug/perf/QA-only reports. -DESIGN_REQUIRED = [ - "game design brief", - "core loop", - "level/encounter plan", -] - -PHYSICS_MARKERS = [ - "physics engine", - "timestep", - "collider", -] - -PREMIUM_SCORECARD = [ - "art direction", - "hero/player", - "obstacles/enemies", - "rewards/interactables", - "world/environment", - "materials/textures", - "lighting/render", - "vfx/motion", - "ui/hud", - "performance evidence", - "measured evidence", - "fresh-eyes review", - "average", - "automatic failures", -] - -PREMIUM_ASSET_SOURCING = [ - "external asset sourcing", - "credential probe output", - "tripo_api_key=", - "gemini_api_key=", - "3d generator", - "image generator", - "chosen sources", - "hero/player", - "world/sky/background", - "materials/textures/decals", -] - -PREMIUM_TECHNICAL_ART = [ - "technical art", - "render budget", - "vfx readability", -] - -PREMIUM_VISUAL_HARNESS = [ - "visual test harness", -] - -PREMIUM_AUDIO = [ - "audio", - "audio generator", - "elevenlabs_api_key=", -] - -EXTERNAL_OUTPUT_PATTERNS = [ - re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b"), - re.compile(r"\b[\w./-]*assets/(models|concepts|textures|ui|images|audio)/[\w./-]+\.(glb|gltf|fbx|png|jpg|jpeg|webp|mp3|wav|ogg|m4a)\b"), - re.compile(r"\b[\w./-]+\.(glb|gltf|fbx)\b"), -] - -AUDIO_OUTPUT_PATTERNS = [ - re.compile(r"\b[\w./-]*assets/audio/[\w./-]+\.(mp3|wav|ogg|m4a)\b"), -] - -NON_CREDENTIAL_BLOCKER_MARKERS = [ - "api error", - "network error", - "quota", - "offline-only", - "offline only", - "user requested no external", - "no external ai", - "no external assets", -] - -VERIFICATION_MARKERS = [ - "build", - "console", - "page error", - "desktop", - "mobile", - "screenshot", - "canvas", - "pixel", -] - - -def normalize(text: str) -> str: - text = text.lower() - text = text.replace("skill loading ledger", "skill-loading ledger") - text = text.replace("skill loaded ledger", "skill-loading ledger") - text = text.replace("reference loading ledger", "reference ledger") - text = text.replace("asset sourcing ledger", "external asset sourcing") - text = text.replace("external asset ledger", "external asset sourcing") - text = text.replace("gameplay brief", "game design brief") - text = text.replace("design brief", "game design brief") - text = text.replace("playable loop", "core loop") - text = text.replace("level plan", "level/encounter plan") - text = text.replace("encounter plan", "level/encounter plan") - text = text.replace("level and encounter plan", "level/encounter plan") - text = text.replace("technical-art", "technical art") - text = text.replace("technical art budget", "technical art render budget") - text = text.replace("render-budget", "render budget") - text = text.replace("visual harness", "visual test harness") - text = text.replace("screenshot baseline", "visual test harness") - text = text.replace("threejs-3d-generator", "3d generator") - text = text.replace("threejs-image-generator", "image generator") - text = text.replace("threejs-audio-generator", "audio generator") - text = text.replace("tripo 3d assets", "3d generator") - text = text.replace("tripo 3d generation", "3d generator") - text = text.replace("tripo 3d", "3d generator") - text = text.replace("tripo loaded", "3d generator loaded") - text = text.replace("nano banana pro", "image generator") - text = text.replace("nano banana", "image generator") - text = text.replace("nanobanana", "image generator") - text = text.replace("nano-banana", "image generator") - text = text.replace("phase-execution ledger", "phase ledger") - text = text.replace("phase execution ledger", "phase ledger") - text = text.replace("debug and profile", "debug/profile") - text = text.replace("debug profile", "debug/profile") - text = text.replace("qa and release", "qa/release") - text = text.replace("qa release", "qa/release") - text = text.replace("page errors", "page error") - text = text.replace("fresh eyes review", "fresh-eyes review") - text = text.replace("fresh-eyes scorecard review", "fresh-eyes review") - text = text.replace("independent reviewer scores", "fresh-eyes review") - text = text.replace("adversarial self-review", "fresh-eyes review") - text = text.replace("measured visual evidence", "measured evidence") - text = text.replace("inspector metrics", "measured evidence") - return re.sub(r"\s+", " ", text) - - -def marker_pattern(marker: str) -> re.Pattern[str]: - """Match markers on word boundaries so short markers like 'ui' cannot be - satisfied incidentally by substrings of unrelated words (e.g. 'build').""" - prefix = r"\b" if re.match(r"\w", marker) else "" - suffix = r"\b" if re.search(r"\w$", marker) else "" - return re.compile(prefix + re.escape(marker) + suffix) - - -def missing_markers(text: str, markers: list[str]) -> list[str]: - return [marker for marker in markers if not marker_pattern(marker).search(text)] - - -def has_external_output_evidence(text: str) -> bool: - return any(pattern.search(text) for pattern in EXTERNAL_OUTPUT_PATTERNS) - - -def has_audio_output_evidence(text: str) -> bool: - return any(pattern.search(text) for pattern in AUDIO_OUTPUT_PATTERNS) - - -def has_external_blocker(text: str) -> bool: - both_credentials_missing = "tripo_api_key=missing" in text and "gemini_api_key=missing" in text - non_credential_blocker = any(marker in text for marker in NON_CREDENTIAL_BLOCKER_MARKERS) - return both_credentials_missing or non_credential_blocker - - -def has_audio_blocker(text: str) -> bool: - return "elevenlabs_api_key=missing" in text or any(marker in text for marker in NON_CREDENTIAL_BLOCKER_MARKERS) - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Check that a Three.js director final report includes required ledgers, scorecard, and verification evidence." - ) - parser.add_argument("report", help="Path to the markdown/text final report draft.") - parser.add_argument( - "--premium", - action="store_true", - help="Require the premium/AAA visual scorecard and full verification evidence.", - ) - parser.add_argument( - "--physics", - action="store_true", - help="Require physics engine choice and diagnostics evidence.", - ) - parser.add_argument( - "--audio", - action="store_true", - help="Require generated/integrated audio evidence or a real blocker.", - ) - parser.add_argument( - "--no-design", - action="store_true", - help="Skip game-design markers (design brief, core loop, level/encounter plan) for debug/perf/QA-only reports.", - ) - args = parser.parse_args() - - report_path = Path(args.report) - if not report_path.exists(): - print(f"Missing report file: {report_path}", file=sys.stderr) - return 1 - - text = normalize(report_path.read_text(encoding="utf-8")) - missing = missing_markers(text, BASE_REQUIRED) - if not args.no_design: - missing.extend(missing_markers(text, DESIGN_REQUIRED)) - - if args.premium: - missing.extend(missing_markers(text, PREMIUM_SCORECARD)) - missing.extend(missing_markers(text, PREMIUM_ASSET_SOURCING)) - missing.extend(missing_markers(text, PREMIUM_TECHNICAL_ART)) - missing.extend(missing_markers(text, PREMIUM_VISUAL_HARNESS)) - missing.extend(missing_markers(text, VERIFICATION_MARKERS)) - if not has_external_output_evidence(text) and not has_external_blocker(text): - missing.append("real external asset evidence or blocker") - if "not-needed" in text and "procedural" in text and not has_external_output_evidence(text) and not has_external_blocker(text): - missing.append("procedural/not-needed requires external output evidence or blocker") - - if args.physics: - missing.extend(missing_markers(text, PHYSICS_MARKERS)) - - if args.audio: - missing.extend(missing_markers(text, PREMIUM_AUDIO)) - if not has_audio_output_evidence(text) and not has_audio_blocker(text): - missing.append("real audio asset evidence or blocker") - - if missing: - print("Director report audit failed. Missing required markers:") - for marker in missing: - print(f"- {marker}") - return 1 - - print("Director report audit passed.") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/.agents/skills/threejs-game-director/scripts/probe_asset_credentials.sh b/.agents/skills/threejs-game-director/scripts/probe_asset_credentials.sh deleted file mode 100755 index 21a88fc616..0000000000 --- a/.agents/skills/threejs-game-director/scripts/probe_asset_credentials.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Prints exactly one line per key in the form KEY=SET or KEY=MISSING. -# The literal MISSING token is a contract: skill skip rules and -# audit_reference_report.py blocker detection grep for it. -PROBE_SNIPPET=' - report_key() { - if [ -n "${2:-}" ]; then - printf "%s=SET\n" "$1" - else - printf "%s=MISSING\n" "$1" - fi - } - report_key TRIPO_API_KEY "${TRIPO_API_KEY:-}" - report_key GEMINI_API_KEY "${GEMINI_API_KEY:-}" - report_key ELEVENLABS_API_KEY "${ELEVENLABS_API_KEY:-}" -' - -if command -v zsh >/dev/null 2>&1; then - zsh -lc ' - source "$HOME/.zprofile" >/dev/null 2>&1 || true - source "$HOME/.zshrc" >/dev/null 2>&1 || true - '"$PROBE_SNIPPET" -else - bash -lc ' - source "$HOME/.bash_profile" >/dev/null 2>&1 || true - source "$HOME/.bashrc" >/dev/null 2>&1 || true - '"$PROBE_SNIPPET" -fi diff --git a/.agents/skills/threejs-gameplay-systems/SKILL.md b/.agents/skills/threejs-gameplay-systems/SKILL.md deleted file mode 100644 index d87c83bd53..0000000000 --- a/.agents/skills/threejs-gameplay-systems/SKILL.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -name: threejs-gameplay-systems -description: "Build and iterate playable Three.js game systems. Combines starter scaffold creation, architecture, game design, level design, gameplay implementation, combat/encounter design, and game-feel tuning (hitstop, screenshake, easing, impact feedback). Use for first playable slices, new Vite/TypeScript/Three.js game setup, design briefs, core loops, level/arena/track/wave/hole/puzzle design, game loops, entity systems, input, collision/physics, scoring, objectives, audio hooks, camera, controls, difficulty, feedback, juice, and maintainable structure." ---- - -# Three.js Gameplay Systems - -## Purpose - -Create or evolve a playable browser game loop with clear ownership, responsive controls, deterministic update order, strong design intent, playable spaces, and verified player-facing behavior. - -## Use When - -Starting a new game, repairing a weak prototype, adding mechanics/entities, designing architecture, defining a game design brief, planning levels/arenas/tracks/waves/holes/puzzles, tuning camera/controls, implementing rules/objectives, building encounters, or improving game feel. - -## Workflow - -Load `references/gameplay-workflows.md` as the first action when the task includes first playable setup, architecture, mechanics, entities, input, camera, collision/physics, scoring, objectives, feedback, or feel tuning. - -Load `references/game-design-level-design.md` before broad new-game creation, major gameplay changes, level/arena/track/wave/hole/puzzle design, combat/encounter design, progression/difficulty work, or any claim that gameplay is premium, polished, complete, or less generic. - -Load `references/physics-engine-selection.md` before adding or changing physics, collision-heavy gameplay, vehicle movement, rolling balls, mini-golf, pool/snooker, pinball, rigid-body puzzles, character controllers, sensors, high-speed projectiles, moving platforms, or physics QA. - -Load `references/game-feel.md` before feel/juice/impact tuning, or before claiming gameplay is premium or polished. Track every loaded reference in a reference ledger with yes/no, path, and failure reason. Do not mark the gameplay phase complete while a required reference is skipped. - -Load `references/checklists/new-game-definition-of-done.md` before claiming a new game or first playable slice is complete. - -Load `references/checklists/game-design-level-design.md` before claiming a new game, major gameplay upgrade, level/encounter pass, premium gameplay, or polished gameplay is complete. - -Load `references/checklists/game-feel.md` before claiming feel/impact tuning or premium gameplay is complete. - -Load `references/checklists/endless-runner-premium-quality.md` for endless runner work. - -Load `references/prompt-templates.md` only when the user asks for reusable prompts, starter prompts, or a task template. - -Load `threejs-audio-generator` when implementing real SFX, ambience, UI sounds, voice/TTS, or audio cleanup beyond simple placeholder hooks. Gameplay code should emit audio events; the audio skill should generate or process the actual assets and define the runtime audio matrix. - -1. Inspect project structure, scripts, dependencies, current loop, input, camera, entities, state, UI, and diagnostics. -2. Write the compact game design brief: player promise, target feeling, primary verb, objective, pressure, reward, fail/retry, skill expression, non-goals. -3. Define the core loop contract: verb, objective, pressure, reward/progression, fail/retry. -4. Define the level/encounter plan before implementation: start, first decision, first threat, first reward, landmarks, escalation, recovery beats, readability, and tuning knobs. -5. Choose small architecture boundaries: `core`, `game`, `entities`, `systems`, `assets`, `ui`, `tests`. -6. Implement mechanics in playable increments: input, state, entity, collision/physics, feedback, HUD/audio hook, diagnostics. -7. Tune feel with `references/game-feel.md`: movement, acceleration, camera follow/FOV/shake, hitstop, impact feedback, cooldowns, difficulty, restart loop. -8. Keep hot paths allocation-light and update order explicit. -9. Verify with build, browser, screenshot, canvas pixels, console/page errors, and one real input path. - -## Packaged Scaffold - -Use the bundled scaffold when starting a new project or when the user asks for a starter game: - -```bash -python3 /scripts/create_threejs_game.py ./my-game -``` - -The script copies `assets/threejs-vite-game/`, rewrites the project name in `package.json` and `package-lock.json`, and keeps generated games self-contained with their own visual test and canvas-inspection script. Use `--force` only when the target directory may be overwritten. - -## Library Guidance - -- Use TypeScript, Vite, Three.js modules. -- Physics/collision engine choice (custom collision vs Rapier vs cannon-es), timestep, and collider strategy: follow `references/physics-engine-selection.md`. -- `lil-gui` for live-tuned constants when useful. -- Web Audio for runtime playback and procedural feedback; `threejs-audio-generator` for generated game audio assets. - -## Common Failure Modes - -- Static demo instead of playable loop. -- Static scene with mechanics bolted on after the fact, instead of a design brief plus level/encounter plan driving implementation. -- Core loop is described but not proven through real input, pressure, reward/progression, and fail/retry. -- Level/track/arena/map is decorative and does not shape player decisions. -- Mechanic compiles but cannot be triggered by real input. -- Camera/controls feel delayed or hide the next decision. -- State changes do not drive UI/audio/VFX. -- Architecture abstractions appear before mechanics need them. - -## Final Response - -Report the reference ledger, game design brief, core loop contract, level/encounter plan, gameplay checklist outcome, behavior, controls, changed files, architecture choices, tuned values, verification evidence, artifacts, and remaining edge cases. diff --git a/.agents/skills/threejs-gameplay-systems/agents/openai.yaml b/.agents/skills/threejs-gameplay-systems/agents/openai.yaml deleted file mode 100644 index 1b97ac140c..0000000000 --- a/.agents/skills/threejs-gameplay-systems/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Three.js Gameplay Systems" - short_description: "Design and build playable Three.js systems" - default_prompt: "Load threejs-gameplay-systems/SKILL.md (try ~/.codex/skills/threejs-gameplay-systems/SKILL.md, then ~/.claude/skills, ~/.agents/skills, or repo skills/) and follow it exactly, including its reference-loading rules and reference ledger. Non-negotiables: design brief, core loop contract, and level/encounter plan before broad implementation; verify through build, browser, and one real input path; report the reference ledger and checklist outcomes." diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/.gitignore b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/.gitignore deleted file mode 100644 index f259ac578c..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules/ -dist/ -test-results/ -artifacts/ -*.log -.DS_Store diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/index.html b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/index.html deleted file mode 100644 index 55d9e431f7..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/index.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - Three.js Vite Game - - -
- -
-
- Relays - 0/8 -
-
- Time - 00:00 -
-
Collect relays
-
- -
- - - diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/package-lock.json b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/package-lock.json deleted file mode 100644 index cdcdc7982c..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/package-lock.json +++ /dev/null @@ -1,991 +0,0 @@ -{ - "name": "threejs-vite-game", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "threejs-vite-game", - "version": "0.1.0", - "dependencies": { - "lil-gui": "^0.21.0", - "three": "^0.184.0" - }, - "devDependencies": { - "@playwright/test": "^1.60.0", - "@types/node": "^25.9.0", - "@types/pngjs": "^6.0.5", - "@types/three": "^0.184.1", - "pngjs": "^7.0.0", - "typescript": "^6.0.3", - "vite": "^8.0.13" - } - }, - "node_modules/@dimforge/rapier3d-compat": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", - "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/@oxc-project/types": { - "version": "0.152.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz", - "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/oxc-project" - } - }, - "node_modules/@playwright/test": { - "version": "1.60.0", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz", - "integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "playwright": "1.60.0" - }, - "bin": { - "playwright": "cli.js" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz", - "integrity": "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.12.tgz", - "integrity": "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.12.tgz", - "integrity": "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.12.tgz", - "integrity": "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.12.tgz", - "integrity": "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.12.tgz", - "integrity": "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.12.tgz", - "integrity": "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.12.tgz", - "integrity": "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.12.tgz", - "integrity": "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.12.tgz", - "integrity": "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.12.tgz", - "integrity": "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.12.tgz", - "integrity": "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.12.tgz", - "integrity": "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.12.tgz", - "integrity": "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.12.tgz", - "integrity": "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tweenjs/tween.js": { - "version": "23.1.3", - "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", - "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "25.9.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.0.tgz", - "integrity": "sha512-AOQwYUNolgy3VosiRqXrACUXTN8nJUtPl7FJXMqZVyxiiCLhQuG3jXKvCS1ALr+Y2OmZhzzLVlYPEqJaiqkaJQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": ">=7.24.0 <7.24.7" - } - }, - "node_modules/@types/pngjs": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/@types/pngjs/-/pngjs-6.0.5.tgz", - "integrity": "sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/stats.js": { - "version": "0.17.4", - "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", - "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/three": { - "version": "0.184.1", - "resolved": "https://registry.npmjs.org/@types/three/-/three-0.184.1.tgz", - "integrity": "sha512-6q4VdiqVsrTRqmk62/BnlcAvIrnDM0zf2ZDVKI5kZiniWrSaOHaQzmbp+BNzoggc/8tgW412pL//wZIxu2PPTA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@dimforge/rapier3d-compat": "~0.12.0", - "@tweenjs/tween.js": "~23.1.3", - "@types/stats.js": "*", - "@types/webxr": ">=0.5.17", - "fflate": "~0.8.2", - "meshoptimizer": "~1.1.1" - } - }, - "node_modules/@types/webxr": { - "version": "0.5.24", - "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", - "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", - "dev": true, - "license": "MIT" - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/fflate": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", - "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", - "dev": true, - "license": "MIT" - }, - "node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/lightningcss": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", - "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.33.0", - "lightningcss-darwin-arm64": "1.33.0", - "lightningcss-darwin-x64": "1.33.0", - "lightningcss-freebsd-x64": "1.33.0", - "lightningcss-linux-arm-gnueabihf": "1.33.0", - "lightningcss-linux-arm64-gnu": "1.33.0", - "lightningcss-linux-arm64-musl": "1.33.0", - "lightningcss-linux-x64-gnu": "1.33.0", - "lightningcss-linux-x64-musl": "1.33.0", - "lightningcss-win32-arm64-msvc": "1.33.0", - "lightningcss-win32-x64-msvc": "1.33.0" - } - }, - "node_modules/lightningcss-android-arm64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", - "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", - "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", - "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", - "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", - "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", - "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", - "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", - "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", - "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", - "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", - "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lil-gui": { - "version": "0.21.0", - "resolved": "https://registry.npmjs.org/lil-gui/-/lil-gui-0.21.0.tgz", - "integrity": "sha512-tpvxN7v1GvE/Tv+GRopfOp0W7fVEjF4PltkuX8vOCIfim22rD1ztvfkoEMcv9lzQeuNUSeIrUmUjBwmlW/oUew==", - "license": "MIT" - }, - "node_modules/meshoptimizer": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", - "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", - "dev": true, - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "3.3.19", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", - "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", - "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/playwright": { - "version": "1.60.0", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz", - "integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "playwright-core": "1.60.0" - }, - "bin": { - "playwright": "cli.js" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "fsevents": "2.3.2" - } - }, - "node_modules/playwright-core": { - "version": "1.60.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz", - "integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "playwright-core": "cli.js" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/pngjs": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz", - "integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.19.0" - } - }, - "node_modules/postcss": { - "version": "8.5.28", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", - "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.18", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/rolldown": { - "version": "1.2.12", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.12.tgz", - "integrity": "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@oxc-project/types": "=0.152.0", - "@rolldown/pluginutils": "^1.0.0" - }, - "bin": { - "rolldown": "bin/cli.mjs" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.12", - "@rolldown/binding-android-arm64": "1.2.12", - "@rolldown/binding-darwin-arm64": "1.2.12", - "@rolldown/binding-darwin-x64": "1.2.12", - "@rolldown/binding-freebsd-x64": "1.2.12", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.12", - "@rolldown/binding-linux-arm64-gnu": "1.2.12", - "@rolldown/binding-linux-arm64-musl": "1.2.12", - "@rolldown/binding-linux-ppc64-gnu": "1.2.12", - "@rolldown/binding-linux-s390x-gnu": "1.2.12", - "@rolldown/binding-linux-x64-gnu": "1.2.12", - "@rolldown/binding-linux-x64-musl": "1.2.12", - "@rolldown/binding-openharmony-arm64": "1.2.12", - "@rolldown/binding-win32-arm64-msvc": "1.2.12", - "@rolldown/binding-win32-x64-msvc": "1.2.12" - } - }, - "node_modules/source-map-js": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", - "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/three": { - "version": "0.184.0", - "resolved": "https://registry.npmjs.org/three/-/three-0.184.0.tgz", - "integrity": "sha512-wtTRjG92pM5eUg/KuUnHsqSAlPM296brTOcLgMRqEeylYTh/CdtvKUvCyyCQTzFuStieWxvZb8mVTMvdPyUpxg==", - "license": "MIT" - }, - "node_modules/tinyglobby": { - "version": "0.2.17", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", - "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.4" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/typescript": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", - "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "7.24.6", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", - "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", - "dev": true, - "license": "MIT" - }, - "node_modules/vite": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.2.tgz", - "integrity": "sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "lightningcss": "^1.33.0", - "picomatch": "^4.0.7", - "postcss": "^8.5.28", - "rolldown": "~1.2.11", - "tinyglobby": "^0.2.17" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.7.1", - "esbuild": "^0.27.0 || ^0.28.0", - "jiti": ">=1.21.0", - "less": "^4.0.0", - "sass": "^1.70.0", - "sass-embedded": "^1.70.0", - "stylus": ">=0.54.8", - "sugarss": "^5.0.0", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "@vitejs/devtools": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/vite/node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - } - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/package.json b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/package.json deleted file mode 100644 index 5bec22ca39..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "threejs-vite-game", - "version": "0.1.0", - "private": true, - "type": "module", - "scripts": { - "dev": "vite --host 127.0.0.1", - "build": "tsc && vite build", - "preview": "vite preview --host 127.0.0.1", - "test": "playwright test", - "verify:visual": "playwright test tests/visual.spec.ts", - "inspect:canvas": "node scripts/inspect-threejs-canvas.mjs" - }, - "dependencies": { - "lil-gui": "^0.21.0", - "three": "^0.184.0" - }, - "devDependencies": { - "@playwright/test": "^1.60.0", - "@types/node": "^25.9.0", - "@types/pngjs": "^6.0.5", - "@types/three": "^0.184.1", - "pngjs": "^7.0.0", - "typescript": "^6.0.3", - "vite": "^8.0.13" - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/playwright.config.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/playwright.config.ts deleted file mode 100644 index d2763f3bc8..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/playwright.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { defineConfig, devices } from '@playwright/test'; - -export default defineConfig({ - testDir: './tests', - // One worker: parallel headless WebGL contexts contend for the GPU, and the - // frame-time collapse makes game time drift from wall time, flaking timed - // gameplay phases and screenshot baselines. - workers: 1, - timeout: 30_000, - expect: { - timeout: 5_000, - }, - use: { - baseURL: 'http://127.0.0.1:5188', - trace: 'retain-on-failure', - screenshot: 'only-on-failure', - }, - webServer: { - command: 'npm run dev', - url: 'http://127.0.0.1:5188', - reuseExistingServer: false, - timeout: 20_000, - }, - projects: [ - { - name: 'desktop-chrome', - use: { - ...devices['Desktop Chrome'], - // devices['Desktop Chrome'] sets no channel, so Playwright launches the - // bundled headless shell, which has no GPU backend and falls back to - // SwiftShader (CPU) — roughly 4x slower raster and meaningless FPS. - // The full Chromium build renders headless on the real GPU. - channel: 'chromium', - viewport: { width: 1280, height: 720 }, - }, - }, - { - name: 'mobile-safari', - use: { - ...devices['iPhone 13'], - }, - }, - ], -}); diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/scripts/inspect-threejs-canvas.mjs b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/scripts/inspect-threejs-canvas.mjs deleted file mode 100755 index 98306fe79c..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/scripts/inspect-threejs-canvas.mjs +++ /dev/null @@ -1,310 +0,0 @@ -#!/usr/bin/env node -import { chromium, devices } from '@playwright/test'; -import { mkdir, writeFile } from 'node:fs/promises'; -import path from 'node:path'; -import { PNG } from 'pngjs'; - -// Starting-point render budgets (see threejs-aaa-graphics-builder -// references/technical-art.md). Over-budget rows are reported, not fatal. -const RENDER_BUDGETS = { - desktop: { calls: 300, triangles: 750_000, geometries: 300, textures: 60 }, - mobile: { calls: 150, triangles: 300_000, geometries: 200, textures: 40 }, -}; - -function parseArgs(argv) { - const args = { - url: 'http://127.0.0.1:5188', - out: 'artifacts/canvas-inspection', - mobile: false, - wait: 750, - state: null, - seed: undefined, - }; - - for (let i = 0; i < argv.length; i += 1) { - const value = argv[i]; - if (value === '--url') args.url = argv[++i]; - else if (value === '--out') args.out = argv[++i]; - else if (value === '--mobile') args.mobile = true; - else if (value === '--wait') args.wait = Number(argv[++i]); - else if (value === '--state') args.state = argv[++i]; - else if (value === '--seed') args.seed = Number(argv[++i]); - else if (value === '-h' || value === '--help') { - console.log( - 'Usage: inspect-threejs-canvas.mjs [--url URL] [--out DIR] [--mobile] [--wait MS] [--state NAME] [--seed N]\n' + - ' --state/--seed drive window.__THREE_GAME_TEST_HOOKS__ (setState/seed) before capture\n' + - ' so specific game states can be measured deterministically.', - ); - process.exit(0); - } else { - throw new Error(`Unknown argument: ${value}`); - } - } - - return args; -} - -const round = (value, digits) => Number(value.toFixed(digits)); - -// Objective pixel statistics used as "Measured Evidence" in the visual -// scorecard. Computed on a coarse luminance grid so cost stays trivial. -function computePixelMetrics(png) { - const stepX = Math.max(1, Math.floor(png.width / 160)); - const stepY = Math.max(1, Math.floor(png.height / 90)); - const cols = Math.floor(png.width / stepX); - const rows = Math.floor(png.height / stepY); - const luminance = new Float64Array(cols * rows); - const bucketCounts = new Map(); - let samples = 0; - - for (let gy = 0; gy < rows; gy += 1) { - for (let gx = 0; gx < cols; gx += 1) { - const offset = ((gy * stepY) * png.width + gx * stepX) * 4; - const r = png.data[offset]; - const g = png.data[offset + 1]; - const b = png.data[offset + 2]; - luminance[gy * cols + gx] = 0.2126 * r + 0.7152 * g + 0.0722 * b; - const key = `${r >> 4},${g >> 4},${b >> 4}`; - bucketCounts.set(key, (bucketCounts.get(key) ?? 0) + 1); - samples += 1; - } - } - - const sorted = Array.from(luminance).sort((a, b) => a - b); - const mean = sorted.reduce((sum, v) => sum + v, 0) / sorted.length; - const p5 = sorted[Math.floor(sorted.length * 0.05)]; - const p95 = sorted[Math.floor(sorted.length * 0.95)]; - - let entropy = 0; - let dominant = 0; - for (const count of bucketCounts.values()) { - const p = count / samples; - entropy -= p * Math.log2(p); - dominant = Math.max(dominant, count); - } - - let edges = 0; - let checked = 0; - for (let gy = 0; gy < rows - 1; gy += 1) { - for (let gx = 0; gx < cols - 1; gx += 1) { - const i = gy * cols + gx; - const dx = Math.abs(luminance[i] - luminance[i + 1]); - const dy = Math.abs(luminance[i] - luminance[i + cols]); - if (Math.max(dx, dy) > 12) edges += 1; - checked += 1; - } - } - - return { - colorBuckets: bucketCounts.size, - colorEntropyBits: round(entropy, 2), - edgeDensity: round(edges / checked, 3), - luminance: { - mean: round(mean, 1), - p5: round(p5, 1), - p95: round(p95, 1), - contrast: round(p95 - p5, 1), - }, - dominantColorShare: round(dominant / samples, 3), - nonBackgroundShare: round(1 - dominant / samples, 3), - }; -} - -// Playwright's default headless is chromium_headless_shell, which ships no GPU -// backend and silently falls back to SwiftShader (CPU). Every frame-time and FPS -// number measured that way is software-rendered fiction. channel:'chromium' runs -// the full Chromium build in new headless mode against the real GPU. -async function launchBrowser() { - try { - return await chromium.launch({ channel: 'chromium' }); - } catch { - console.error( - 'warning: channel:"chromium" is unavailable, falling back to the bundled headless shell.\n' + - ' Rendering will be software (SwiftShader) and any FPS/frame-time evidence is invalid.\n' + - ' Fix with: npx playwright install chromium', - ); - return chromium.launch(); - } -} - -// Records which GPU actually rasterized the run, so a software fallback can never -// masquerade as performance evidence again. Reuses the game's own context when it -// is WebGL rather than allocating a second one. -async function readGpuInfo(page) { - const info = await page.evaluate(() => { - const canvas = document.querySelector('canvas'); - if (!canvas) return null; - let gl = null; - try { - gl = canvas.getContext('webgl2') ?? canvas.getContext('webgl'); - } catch { - gl = null; - } - if (!gl) return null; - const debug = gl.getExtension('WEBGL_debug_renderer_info'); - return { - renderer: debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER), - vendor: debug ? gl.getParameter(debug.UNMASKED_VENDOR_WEBGL) : gl.getParameter(gl.VENDOR), - }; - }); - - if (!info?.renderer) { - return { renderer: null, vendor: null, softwareRendered: null }; - } - - return { - ...info, - softwareRendered: /swiftshader|llvmpipe|software|basic render/i.test(info.renderer), - }; -} - -function checkRenderBudget(renderer, mode) { - if (!renderer) return null; - const budget = RENDER_BUDGETS[mode]; - const rows = Object.entries(budget).map(([metric, limit]) => { - const actual = renderer[metric]; - return { - metric, - actual: typeof actual === 'number' ? actual : null, - limit, - ok: typeof actual === 'number' ? actual <= limit : null, - }; - }); - return { - tier: mode, - note: 'starting-point budget; adjust per game and document overrides', - rows, - withinBudget: rows.every((row) => row.ok !== false), - }; -} - -async function sampleCanvas(page, mode) { - const locator = page.locator('canvas').first(); - const rect = await locator.boundingBox(); - if (!rect || rect.width < 32 || rect.height < 32) { - return { ok: false, reason: 'canvas-too-small', rect }; - } - - const buffer = await locator.screenshot(); - const png = PNG.sync.read(buffer); - let min = 255; - let max = 0; - let alphaPixels = 0; - const colors = new Set(); - const stride = Math.max(1, Math.floor((png.width * png.height) / 4096)); - - for (let pixel = 0; pixel < png.width * png.height; pixel += stride) { - const offset = pixel * 4; - const r = png.data[offset]; - const g = png.data[offset + 1]; - const b = png.data[offset + 2]; - const a = png.data[offset + 3]; - min = Math.min(min, r, g, b); - max = Math.max(max, r, g, b); - if (a > 0) alphaPixels += 1; - colors.add(`${r >> 4},${g >> 4},${b >> 4},${a >> 6}`); - } - - const variance = max - min; - const diagnostics = await page.evaluate(() => { - const canvas = document.querySelector('canvas'); - return { - drawingBuffer: canvas - ? { width: canvas.width, height: canvas.height } - : null, - game: window.__THREE_GAME_DIAGNOSTICS__ ?? null, - }; - }); - - const ok = alphaPixels > 256 && (variance > 8 || colors.size > 3); - return { - ok, - reason: ok ? 'nonblank' : 'low-variance', - rect, - drawingBuffer: diagnostics.drawingBuffer, - alphaPixels, - variance, - colorBuckets: colors.size, - metrics: computePixelMetrics(png), - renderBudget: checkRenderBudget(diagnostics.game?.renderer ?? null, mode), - diagnostics: diagnostics.game, - }; -} - -async function main() { - const args = parseArgs(process.argv.slice(2)); - await mkdir(args.out, { recursive: true }); - - const browser = await launchBrowser(); - const context = await browser.newContext(args.mobile - ? { ...devices['iPhone 13'], userAgent: undefined } - : { viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 }); - const page = await context.newPage(); - const consoleErrors = []; - const pageErrors = []; - - page.on('console', (message) => { - if (message.type() === 'error') consoleErrors.push(message.text()); - }); - page.on('pageerror', (error) => pageErrors.push(error.message)); - - await page.goto(args.url, { waitUntil: 'networkidle' }); - await page.waitForSelector('canvas', { state: 'visible', timeout: 10_000 }); - - if (args.state || args.seed !== undefined) { - const applied = await page.evaluate(({ seed, state }) => { - const hooks = window.__THREE_GAME_TEST_HOOKS__; - if (!hooks) return false; - if (typeof seed === 'number') hooks.seed?.(seed); - if (state) hooks.setState?.(state); - return true; - }, { seed: args.seed, state: args.state }); - if (!applied) { - console.error( - 'warning: --state/--seed requested but __THREE_GAME_TEST_HOOKS__ is not defined; capturing the current state instead', - ); - } - } - - await page.waitForTimeout(args.wait); - - const mode = args.mobile ? 'mobile' : 'desktop'; - const baseName = args.state ? `${mode}-${args.state}` : mode; - const gpu = await readGpuInfo(page); - const result = await sampleCanvas(page, mode); - const screenshotPath = path.join(args.out, `${baseName}.png`); - await page.screenshot({ path: screenshotPath, fullPage: true }); - - if (gpu.softwareRendered) { - console.error( - `warning: this run rasterized on ${gpu.renderer} (software). Pixel and budget ` + - 'checks remain valid; any FPS or frame-time reading from it does not.', - ); - } - - const report = { - url: args.url, - mode, - state: args.state, - seed: args.seed ?? null, - screenshotPath, - gpu, - result, - consoleErrors, - pageErrors, - }; - - await writeFile(path.join(args.out, `${baseName}.json`), `${JSON.stringify(report, null, 2)}\n`); - await browser.close(); - - console.log(JSON.stringify(report, null, 2)); - - if (!result.ok || consoleErrors.length > 0 || pageErrors.length > 0) { - process.exit(1); - } -} - -main().catch((error) => { - console.error(error); - process.exit(1); -}); diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/InputController.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/InputController.ts deleted file mode 100644 index 4808598c3e..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/InputController.ts +++ /dev/null @@ -1,138 +0,0 @@ -import * as THREE from 'three'; - -type PointerState = { - active: boolean; - id: number | null; - centerX: number; - centerY: number; - radius: number; -}; - -export class InputController { - private readonly keys = new Set(); - private readonly pointer = new THREE.Vector2(); - private readonly keyVector = new THREE.Vector2(); - private readonly pointerState: PointerState = { - active: false, - id: null, - centerX: 0, - centerY: 0, - radius: 1, - }; - - private dashDown = false; - - private readonly onKeyDown = (event: KeyboardEvent) => { - this.keys.add(event.code); - if (event.code === 'Space' || event.code === 'ShiftLeft' || event.code === 'ShiftRight') { - this.dashDown = true; - } - }; - - private readonly onKeyUp = (event: KeyboardEvent) => { - this.keys.delete(event.code); - if (event.code === 'Space' || event.code === 'ShiftLeft' || event.code === 'ShiftRight') { - this.dashDown = false; - } - }; - - private readonly onStickDown = (event: PointerEvent) => { - event.preventDefault(); - const rect = this.stick.getBoundingClientRect(); - this.pointerState.active = true; - this.pointerState.id = event.pointerId; - this.pointerState.centerX = rect.left + rect.width / 2; - this.pointerState.centerY = rect.top + rect.height / 2; - this.pointerState.radius = rect.width * 0.42; - try { - this.stick.setPointerCapture(event.pointerId); - } catch { - // Synthetic test events do not always have a capturable pointer id. - } - this.updatePointer(event.clientX, event.clientY); - }; - - private readonly onStickMove = (event: PointerEvent) => { - if (!this.pointerState.active || event.pointerId !== this.pointerState.id) return; - event.preventDefault(); - this.updatePointer(event.clientX, event.clientY); - }; - - private readonly onStickUp = (event: PointerEvent) => { - if (event.pointerId !== this.pointerState.id) return; - event.preventDefault(); - this.pointerState.active = false; - this.pointerState.id = null; - this.pointer.set(0, 0); - this.updateKnob(); - }; - - private readonly onDashDown = (event: PointerEvent) => { - event.preventDefault(); - this.dashDown = true; - }; - - private readonly onDashUp = (event: PointerEvent) => { - event.preventDefault(); - this.dashDown = false; - }; - - constructor( - private readonly stick: HTMLElement, - private readonly knob: HTMLElement, - private readonly dashButton: HTMLElement, - ) { - window.addEventListener('keydown', this.onKeyDown); - window.addEventListener('keyup', this.onKeyUp); - this.stick.addEventListener('pointerdown', this.onStickDown); - this.stick.addEventListener('pointermove', this.onStickMove); - this.stick.addEventListener('pointerup', this.onStickUp); - this.stick.addEventListener('pointercancel', this.onStickUp); - this.dashButton.addEventListener('pointerdown', this.onDashDown); - this.dashButton.addEventListener('pointerup', this.onDashUp); - this.dashButton.addEventListener('pointercancel', this.onDashUp); - this.dashButton.addEventListener('pointerleave', this.onDashUp); - } - - readMovement(target: THREE.Vector2): THREE.Vector2 { - this.keyVector.set(0, 0); - if (this.keys.has('KeyA') || this.keys.has('ArrowLeft')) this.keyVector.x -= 1; - if (this.keys.has('KeyD') || this.keys.has('ArrowRight')) this.keyVector.x += 1; - if (this.keys.has('KeyW') || this.keys.has('ArrowUp')) this.keyVector.y -= 1; - if (this.keys.has('KeyS') || this.keys.has('ArrowDown')) this.keyVector.y += 1; - - target.copy(this.keyVector).add(this.pointer); - if (target.lengthSq() > 1) target.normalize(); - return target; - } - - isDashHeld(): boolean { - return this.dashDown; - } - - dispose(): void { - window.removeEventListener('keydown', this.onKeyDown); - window.removeEventListener('keyup', this.onKeyUp); - this.stick.removeEventListener('pointerdown', this.onStickDown); - this.stick.removeEventListener('pointermove', this.onStickMove); - this.stick.removeEventListener('pointerup', this.onStickUp); - this.stick.removeEventListener('pointercancel', this.onStickUp); - this.dashButton.removeEventListener('pointerdown', this.onDashDown); - this.dashButton.removeEventListener('pointerup', this.onDashUp); - this.dashButton.removeEventListener('pointercancel', this.onDashUp); - this.dashButton.removeEventListener('pointerleave', this.onDashUp); - } - - private updatePointer(clientX: number, clientY: number): void { - const dx = clientX - this.pointerState.centerX; - const dy = clientY - this.pointerState.centerY; - this.pointer.set(dx / this.pointerState.radius, dy / this.pointerState.radius); - if (this.pointer.lengthSq() > 1) this.pointer.normalize(); - this.updateKnob(); - } - - private updateKnob(): void { - const distance = 38; - this.knob.style.transform = `translate(calc(-50% + ${this.pointer.x * distance}px), calc(-50% + ${this.pointer.y * distance}px))`; - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/Loop.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/Loop.ts deleted file mode 100644 index 974d4a8d20..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/Loop.ts +++ /dev/null @@ -1,31 +0,0 @@ -export class Loop { - private frameId = 0; - private lastTime = 0; - private running = false; - - constructor( - private readonly update: (deltaSeconds: number, elapsedSeconds: number) => void, - private readonly render: () => void, - ) {} - - start(): void { - if (this.running) return; - this.running = true; - this.lastTime = performance.now(); - this.frameId = requestAnimationFrame(this.tick); - } - - stop(): void { - this.running = false; - cancelAnimationFrame(this.frameId); - } - - private readonly tick = (time: number) => { - if (!this.running) return; - const deltaSeconds = Math.min((time - this.lastTime) / 1000, 0.05); - this.lastTime = time; - this.update(deltaSeconds, time / 1000); - this.render(); - this.frameId = requestAnimationFrame(this.tick); - }; -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/Renderer.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/Renderer.ts deleted file mode 100644 index 902b5ddfaf..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/core/Renderer.ts +++ /dev/null @@ -1,39 +0,0 @@ -import * as THREE from 'three'; - -export function createRenderer(canvas: HTMLCanvasElement): THREE.WebGLRenderer { - const renderer = new THREE.WebGLRenderer({ - canvas, - antialias: true, - alpha: false, - powerPreference: 'high-performance', - }); - renderer.outputColorSpace = THREE.SRGBColorSpace; - renderer.toneMapping = THREE.ACESFilmicToneMapping; - renderer.toneMappingExposure = 1.05; - renderer.shadowMap.enabled = true; - renderer.shadowMap.type = THREE.PCFShadowMap; - return renderer; -} - -export function resizeRenderer( - renderer: THREE.WebGLRenderer, - camera: THREE.PerspectiveCamera, - maxDpr = 2, -): boolean { - const canvas = renderer.domElement; - const width = Math.max(1, Math.floor(canvas.clientWidth)); - const height = Math.max(1, Math.floor(canvas.clientHeight)); - const dpr = Math.min(window.devicePixelRatio || 1, maxDpr); - const bufferWidth = Math.floor(width * dpr); - const bufferHeight = Math.floor(height * dpr); - const needsResize = canvas.width !== bufferWidth || canvas.height !== bufferHeight; - - if (needsResize) { - renderer.setPixelRatio(dpr); - renderer.setSize(width, height, false); - camera.aspect = width / height; - camera.updateProjectionMatrix(); - } - - return needsResize; -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/entities/Pickup.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/entities/Pickup.ts deleted file mode 100644 index 001bdf3a87..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/entities/Pickup.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as THREE from 'three'; - -export class Pickup { - readonly group = new THREE.Group(); - readonly radius = 0.62; - active = true; - - private readonly coreGeometry = new THREE.IcosahedronGeometry(0.42, 1); - private readonly ringGeometry = new THREE.TorusGeometry(0.58, 0.028, 8, 32); - private readonly coreMaterial = new THREE.MeshStandardMaterial({ - color: '#48baa7', - emissive: '#0f5249', - emissiveIntensity: 0.8, - roughness: 0.28, - metalness: 0.1, - }); - private readonly ringMaterial = new THREE.MeshBasicMaterial({ - color: '#f6f1df', - }); - - constructor( - readonly index: number, - position: THREE.Vector3, - ) { - const core = new THREE.Mesh(this.coreGeometry, this.coreMaterial); - core.castShadow = true; - this.group.add(core); - - const ring = new THREE.Mesh(this.ringGeometry, this.ringMaterial); - ring.rotation.x = Math.PI / 2; - this.group.add(ring); - - this.group.position.copy(position); - } - - update(delta: number, elapsed: number): void { - if (!this.active) return; - this.group.rotation.y += delta * 1.8; - this.group.children[0].rotation.x -= delta * 1.2; - this.group.position.y = 0.78 + Math.sin(elapsed * 2.6 + this.index) * 0.16; - } - - collect(): void { - this.active = false; - this.group.visible = false; - } - - reset(): void { - this.active = true; - this.group.visible = true; - } - - dispose(): void { - this.coreGeometry.dispose(); - this.ringGeometry.dispose(); - this.coreMaterial.dispose(); - this.ringMaterial.dispose(); - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/entities/Player.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/entities/Player.ts deleted file mode 100644 index 26ba98d400..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/entities/Player.ts +++ /dev/null @@ -1,75 +0,0 @@ -import * as THREE from 'three'; -import type { InputController } from '../core/InputController'; - -export type PlayerTuning = { - speed: number; - dashMultiplier: number; - acceleration: number; -}; - -export type ArenaBounds = { - halfWidth: number; - halfDepth: number; -}; - -export class Player { - readonly group = new THREE.Group(); - readonly velocity = new THREE.Vector3(); - - private readonly move = new THREE.Vector2(); - private readonly targetVelocity = new THREE.Vector3(); - private readonly bodyMaterial = new THREE.MeshStandardMaterial({ - color: '#f5ba49', - roughness: 0.48, - metalness: 0.12, - }); - private readonly accentMaterial = new THREE.MeshStandardMaterial({ - color: '#48baa7', - roughness: 0.32, - metalness: 0.18, - emissive: '#123f39', - emissiveIntensity: 0.35, - }); - private readonly bodyGeometry = new THREE.CapsuleGeometry(0.38, 0.58, 6, 12); - private readonly noseGeometry = new THREE.ConeGeometry(0.22, 0.5, 4); - - constructor() { - const body = new THREE.Mesh(this.bodyGeometry, this.bodyMaterial); - body.castShadow = true; - body.receiveShadow = true; - body.position.y = 0.68; - this.group.add(body); - - const nose = new THREE.Mesh(this.noseGeometry, this.accentMaterial); - nose.castShadow = true; - nose.position.set(0, 0.68, -0.58); - nose.rotation.x = Math.PI / 2; - this.group.add(nose); - } - - update(delta: number, elapsed: number, input: InputController, tuning: PlayerTuning, bounds: ArenaBounds): void { - input.readMovement(this.move); - const dash = input.isDashHeld() ? tuning.dashMultiplier : 1; - this.targetVelocity.set(this.move.x, 0, this.move.y).multiplyScalar(tuning.speed * dash); - - const smoothing = 1 - Math.exp(-tuning.acceleration * delta); - this.velocity.lerp(this.targetVelocity, smoothing); - this.group.position.addScaledVector(this.velocity, delta); - - this.group.position.x = THREE.MathUtils.clamp(this.group.position.x, -bounds.halfWidth + 0.8, bounds.halfWidth - 0.8); - this.group.position.z = THREE.MathUtils.clamp(this.group.position.z, -bounds.halfDepth + 0.8, bounds.halfDepth - 0.8); - - if (this.velocity.lengthSq() > 0.001) { - this.group.rotation.y = Math.atan2(this.velocity.x, -this.velocity.z); - } - - this.group.position.y = 0.06 + Math.sin(elapsed * 9) * Math.min(this.velocity.length() / 40, 0.08); - } - - dispose(): void { - this.bodyGeometry.dispose(); - this.noseGeometry.dispose(); - this.bodyMaterial.dispose(); - this.accentMaterial.dispose(); - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/game/Game.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/game/Game.ts deleted file mode 100644 index afa4c1eba9..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/game/Game.ts +++ /dev/null @@ -1,342 +0,0 @@ -import * as THREE from 'three'; -import { InputController } from '../core/InputController'; -import { Loop } from '../core/Loop'; -import { createRenderer, resizeRenderer } from '../core/Renderer'; -import { Pickup } from '../entities/Pickup'; -import { Player, type ArenaBounds } from '../entities/Player'; -import { AudioSystem } from '../systems/AudioSystem'; -import { CameraRig } from '../systems/CameraRig'; -import { CollisionSystem } from '../systems/CollisionSystem'; -import { DebugTools, type DebugTuning } from '../systems/DebugTools'; -import { Hud } from '../systems/Hud'; -import { createSeededRandom } from '../utils/random'; - -const ARENA: ArenaBounds = { - halfWidth: 11, - halfDepth: 7, -}; - -export class Game { - private readonly renderer: THREE.WebGLRenderer; - private readonly scene = new THREE.Scene(); - private readonly camera = new THREE.PerspectiveCamera(48, 1, 0.1, 80); - private readonly input: InputController; - private readonly player = new Player(); - private readonly pickups: Pickup[] = []; - private readonly collision = new CollisionSystem(); - private readonly audio = new AudioSystem(); - private readonly hud = new Hud(); - private readonly cameraRig = new CameraRig(this.camera); - private readonly loop = new Loop( - (delta, elapsed) => this.update(delta, elapsed), - () => this.render(), - ); - - private readonly tuning: DebugTuning = { - speed: 5.8, - dashMultiplier: 1.75, - acceleration: 13, - cameraLag: 0.16, - exposure: 1.05, - maxDpr: 2, - }; - - private readonly debugTools: DebugTools; - private frame = 0; - private score = 0; - private elapsed = 0; - private complete = false; - // Route ALL gameplay randomness through this.rng (never Math.random) so the - // seed() test hook keeps screenshot baselines and bot playtests deterministic. - private rng = createSeededRandom(1); - private pausedForScreenshot = false; - private reducedMotion = false; - - constructor(private readonly canvas: HTMLCanvasElement) { - this.renderer = createRenderer(canvas); - this.renderer.toneMappingExposure = this.tuning.exposure; - - const stick = this.getElement('#touch-stick'); - const knob = this.getElement('#touch-knob'); - const dashButton = this.getElement('#dash-button'); - this.input = new InputController(stick, knob, dashButton); - - this.debugTools = new DebugTools(this.tuning, () => { - this.renderer.toneMappingExposure = this.tuning.exposure; - resizeRenderer(this.renderer, this.camera, this.tuning.maxDpr); - }); - - this.createScene(); - this.hud.setTarget(this.pickups.length); - this.cameraRig.snapTo(this.player.group.position); - resizeRenderer(this.renderer, this.camera, this.tuning.maxDpr); - this.installTestHooks(); - this.publishDiagnostics(); - } - - start(): void { - this.loop.start(); - } - - dispose(): void { - this.loop.stop(); - this.input.dispose(); - this.audio.dispose(); - this.debugTools.dispose(); - for (const pickup of this.pickups) pickup.dispose(); - this.player.dispose(); - this.renderer.dispose(); - window.__THREE_GAME_DIAGNOSTICS__ = undefined; - window.__THREE_GAME_TEST_HOOKS__ = undefined; - } - - private update(delta: number, elapsed: number): void { - this.frame += 1; - if (this.pausedForScreenshot) { - this.publishDiagnostics(); - return; - } - if (!this.complete) this.elapsed += delta; - - resizeRenderer(this.renderer, this.camera, this.tuning.maxDpr); - // Reduced motion freezes ambient animation time so screenshots are stable. - const animDelta = this.reducedMotion ? 0 : delta; - const animElapsed = this.reducedMotion ? 0 : elapsed; - this.player.update(delta, animElapsed, this.input, this.tuning, ARENA); - - for (const pickup of this.pickups) { - pickup.update(animDelta, animElapsed); - } - - const collected = this.collision.collectPickups(this.player.group.position, this.pickups, 0.55); - for (const pickup of collected) { - this.score += 1; - this.audio.pickup(pickup.index); - this.hud.flashPickup(); - } - - if (this.score >= this.pickups.length) { - this.complete = true; - } - - this.cameraRig.update(delta, this.player.group.position, this.tuning.cameraLag); - this.hud.update(this.score, this.pickups.length, this.elapsed, this.complete); - this.publishDiagnostics(); - } - - private render(): void { - this.renderer.render(this.scene, this.camera); - } - - private createScene(): void { - this.scene.background = new THREE.Color('#151713'); - this.scene.fog = new THREE.Fog('#151713', 20, 44); - - const hemisphere = new THREE.HemisphereLight('#f6f1df', '#2b322d', 1.7); - this.scene.add(hemisphere); - - const sun = new THREE.DirectionalLight('#fff1bf', 2.6); - sun.position.set(-5, 9, 6); - sun.castShadow = true; - sun.shadow.mapSize.set(2048, 2048); - sun.shadow.camera.near = 0.5; - sun.shadow.camera.far = 30; - sun.shadow.camera.left = -14; - sun.shadow.camera.right = 14; - sun.shadow.camera.top = 12; - sun.shadow.camera.bottom = -12; - this.scene.add(sun); - - this.scene.add(this.createArena()); - this.scene.add(this.player.group); - this.createPickups(); - } - - private createArena(): THREE.Group { - const arena = new THREE.Group(); - const floorTexture = this.createFloorTexture(); - floorTexture.wrapS = THREE.RepeatWrapping; - floorTexture.wrapT = THREE.RepeatWrapping; - floorTexture.repeat.set(ARENA.halfWidth / 2, ARENA.halfDepth / 2); - - const floor = new THREE.Mesh( - new THREE.PlaneGeometry(ARENA.halfWidth * 2, ARENA.halfDepth * 2, 1, 1), - new THREE.MeshStandardMaterial({ - color: '#2a2c25', - map: floorTexture, - roughness: 0.72, - metalness: 0.02, - }), - ); - floor.rotation.x = -Math.PI / 2; - floor.receiveShadow = true; - arena.add(floor); - - const railMaterial = new THREE.MeshStandardMaterial({ - color: '#d94f35', - roughness: 0.52, - metalness: 0.08, - }); - const longRailGeometry = new THREE.BoxGeometry(ARENA.halfWidth * 2 + 1, 0.55, 0.42); - const shortRailGeometry = new THREE.BoxGeometry(0.42, 0.55, ARENA.halfDepth * 2 + 1); - const rails = [ - new THREE.Mesh(longRailGeometry, railMaterial), - new THREE.Mesh(longRailGeometry, railMaterial), - new THREE.Mesh(shortRailGeometry, railMaterial), - new THREE.Mesh(shortRailGeometry, railMaterial), - ]; - rails[0].position.set(0, 0.28, -ARENA.halfDepth - 0.24); - rails[1].position.set(0, 0.28, ARENA.halfDepth + 0.24); - rails[2].position.set(-ARENA.halfWidth - 0.24, 0.28, 0); - rails[3].position.set(ARENA.halfWidth + 0.24, 0.28, 0); - for (const rail of rails) { - rail.castShadow = true; - rail.receiveShadow = true; - arena.add(rail); - } - - const markerMaterial = new THREE.MeshBasicMaterial({ color: '#f5ba49' }); - const markerGeometry = new THREE.RingGeometry(0.68, 0.72, 48); - const centerMarker = new THREE.Mesh(markerGeometry, markerMaterial); - centerMarker.rotation.x = -Math.PI / 2; - centerMarker.position.y = 0.018; - arena.add(centerMarker); - - return arena; - } - - private createPickups(): void { - const positions = [ - [-8, -4], - [-3, -5], - [3, -4.8], - [8, -3], - [-7.5, 3.5], - [-1.5, 4.7], - [4.5, 3.8], - [8.2, 1.4], - ]; - - positions.forEach(([x, z], index) => { - const pickup = new Pickup(index, new THREE.Vector3(x, 0.8, z)); - this.pickups.push(pickup); - this.scene.add(pickup.group); - }); - } - - private createFloorTexture(): THREE.CanvasTexture { - const size = 256; - const textureCanvas = document.createElement('canvas'); - textureCanvas.width = size; - textureCanvas.height = size; - const context = textureCanvas.getContext('2d'); - if (!context) throw new Error('Could not create floor texture context.'); - - context.fillStyle = '#282a24'; - context.fillRect(0, 0, size, size); - context.strokeStyle = 'rgba(246, 241, 223, 0.08)'; - context.lineWidth = 1; - for (let i = 0; i <= size; i += 32) { - context.beginPath(); - context.moveTo(i, 0); - context.lineTo(i, size); - context.moveTo(0, i); - context.lineTo(size, i); - context.stroke(); - } - context.strokeStyle = 'rgba(245, 186, 73, 0.24)'; - context.lineWidth = 2; - context.strokeRect(8, 8, size - 16, size - 16); - - const texture = new THREE.CanvasTexture(textureCanvas); - texture.colorSpace = THREE.SRGBColorSpace; - return texture; - } - - private installTestHooks(): void { - // Deterministic hooks consumed by tests/visual-regression.template.ts and - // bot playtests. Keep these real when evolving the game: silent no-op hooks - // produce flaky screenshot baselines. - window.__THREE_GAME_TEST_HOOKS__ = { - seed: (value: number) => { - this.rng = createSeededRandom(value); - }, - setState: (name: string) => { - if (name === 'active-play') this.resetRun(); - else if (name === 'complete') this.completeRun(); - else console.warn(`Unknown test state: ${name}`); - }, - setPausedForScreenshot: (paused: boolean) => { - this.pausedForScreenshot = paused; - }, - setReducedMotion: (enabled: boolean) => { - this.reducedMotion = enabled; - }, - hideDebugUi: (hidden: boolean) => { - this.debugTools.setHidden(hidden); - }, - }; - } - - private resetRun(): void { - this.score = 0; - this.elapsed = 0; - this.complete = false; - this.player.group.position.set(0, this.player.group.position.y, 0); - this.player.velocity.set(0, 0, 0); - for (const pickup of this.pickups) { - pickup.reset(); - pickup.group.rotation.y = this.rng() * Math.PI * 2; - } - this.cameraRig.snapTo(this.player.group.position); - this.hud.setTarget(this.pickups.length); - this.hud.update(this.score, this.pickups.length, this.elapsed, this.complete); - } - - private completeRun(): void { - for (const pickup of this.pickups) { - if (pickup.active) pickup.collect(); - } - this.score = this.pickups.length; - this.complete = true; - this.hud.update(this.score, this.pickups.length, this.elapsed, this.complete); - } - - private publishDiagnostics(): void { - const info = this.renderer.info; - window.__THREE_GAME_DIAGNOSTICS__ = { - frame: this.frame, - elapsed: this.elapsed, - score: this.score, - targetScore: this.pickups.length, - complete: this.complete, - player: { - position: { - x: this.player.group.position.x, - y: this.player.group.position.y, - z: this.player.group.position.z, - }, - speed: this.player.velocity.length(), - }, - renderer: { - calls: info.render.calls, - triangles: info.render.triangles, - geometries: info.memory.geometries, - textures: info.memory.textures, - }, - canvas: { - clientWidth: this.canvas.clientWidth, - clientHeight: this.canvas.clientHeight, - width: this.canvas.width, - height: this.canvas.height, - dpr: Math.min(window.devicePixelRatio || 1, this.tuning.maxDpr), - }, - }; - } - - private getElement(selector: string): HTMLElement { - const element = document.querySelector(selector); - if (!element) throw new Error(`Missing element: ${selector}`); - return element; - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/main.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/main.ts deleted file mode 100644 index 25bbeca3ae..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/main.ts +++ /dev/null @@ -1,17 +0,0 @@ -import './styles.css'; -import { Game } from './game/Game'; - -const canvas = document.querySelector('#game-canvas'); - -if (!canvas) { - throw new Error('Missing #game-canvas element.'); -} - -const game = new Game(canvas); -game.start(); - -if (import.meta.hot) { - import.meta.hot.dispose(() => { - game.dispose(); - }); -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/styles.css b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/styles.css deleted file mode 100644 index 20179d4e11..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/styles.css +++ /dev/null @@ -1,156 +0,0 @@ -:root { - color: #f6f1df; - background: #111312; - font-family: - Avenir Next, - Avenir, - "Segoe UI", - sans-serif; - font-synthesis: none; - text-rendering: geometricPrecision; -} - -* { - box-sizing: border-box; -} - -html, -body, -#app { - width: 100%; - height: 100%; - margin: 0; - overflow: hidden; -} - -body { - min-width: 320px; -} - -#app { - position: relative; - background: - radial-gradient(circle at 18% 18%, rgba(245, 186, 73, 0.16), transparent 26rem), - radial-gradient(circle at 82% 72%, rgba(72, 186, 167, 0.14), transparent 24rem), - #111312; -} - -#game-canvas { - display: block; - width: 100vw; - height: 100vh; - outline: none; - touch-action: none; -} - -#hud { - position: absolute; - top: max(16px, env(safe-area-inset-top)); - left: max(16px, env(safe-area-inset-left)); - display: flex; - align-items: center; - gap: 10px; - pointer-events: none; - color: #f6f1df; - text-transform: uppercase; - letter-spacing: 0; -} - -.hud-metric { - min-width: 92px; - padding: 8px 10px; - border: 1px solid rgba(246, 241, 223, 0.24); - background: rgba(17, 19, 18, 0.72); - box-shadow: 0 8px 24px rgba(0, 0, 0, 0.24); - backdrop-filter: blur(10px); -} - -.hud-metric span { - display: block; - color: rgba(246, 241, 223, 0.68); - font-size: 0.68rem; -} - -.hud-metric strong { - display: block; - margin-top: 2px; - font-size: 1.08rem; -} - -#status-line { - min-width: 132px; - padding: 9px 11px; - border-left: 3px solid #f5ba49; - background: rgba(17, 19, 18, 0.6); - font-weight: 700; - font-size: 0.78rem; -} - -#touch-controls { - position: absolute; - right: max(18px, env(safe-area-inset-right)); - bottom: max(18px, env(safe-area-inset-bottom)); - left: max(18px, env(safe-area-inset-left)); - display: none; - justify-content: space-between; - align-items: flex-end; - pointer-events: none; -} - -#touch-stick { - position: relative; - width: clamp(96px, 24vw, 132px); - aspect-ratio: 1; - border: 1px solid rgba(246, 241, 223, 0.28); - border-radius: 50%; - background: rgba(17, 19, 18, 0.52); - pointer-events: auto; - touch-action: none; -} - -#touch-knob { - position: absolute; - top: 50%; - left: 50%; - width: 42%; - aspect-ratio: 1; - border-radius: 50%; - background: #f5ba49; - box-shadow: 0 0 24px rgba(245, 186, 73, 0.44); - transform: translate(-50%, -50%); -} - -#dash-button { - width: clamp(74px, 18vw, 96px); - aspect-ratio: 1; - border: 1px solid rgba(246, 241, 223, 0.3); - border-radius: 50%; - color: #111312; - background: #48baa7; - font-weight: 800; - pointer-events: auto; - touch-action: none; -} - -@media (pointer: coarse), (max-width: 760px) { - #hud { - right: max(12px, env(safe-area-inset-right)); - left: max(12px, env(safe-area-inset-left)); - flex-wrap: wrap; - gap: 8px; - } - - .hud-metric { - min-width: 78px; - padding: 7px 8px; - } - - #status-line { - min-width: min(148px, 48vw); - font-size: 0.72rem; - } - - #touch-controls { - display: flex; - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/AudioSystem.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/AudioSystem.ts deleted file mode 100644 index 60320f7aaa..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/AudioSystem.ts +++ /dev/null @@ -1,47 +0,0 @@ -export class AudioSystem { - private context: AudioContext | null = null; - private unlocked = false; - - constructor() { - const unlock = () => { - void this.unlock(); - window.removeEventListener('pointerdown', unlock); - window.removeEventListener('keydown', unlock); - }; - window.addEventListener('pointerdown', unlock, { once: true }); - window.addEventListener('keydown', unlock, { once: true }); - } - - async unlock(): Promise { - if (this.unlocked) return; - const AudioContextClass = - window.AudioContext || - (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext; - if (!AudioContextClass) return; - this.context = new AudioContextClass(); - await this.context.resume(); - this.unlocked = true; - } - - pickup(index: number): void { - if (!this.context || this.context.state !== 'running') return; - const oscillator = this.context.createOscillator(); - const gain = this.context.createGain(); - const now = this.context.currentTime; - - oscillator.type = 'triangle'; - oscillator.frequency.setValueAtTime(320 + index * 22, now); - oscillator.frequency.exponentialRampToValueAtTime(680 + index * 24, now + 0.12); - gain.gain.setValueAtTime(0.0001, now); - gain.gain.exponentialRampToValueAtTime(0.08, now + 0.02); - gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.18); - oscillator.connect(gain).connect(this.context.destination); - oscillator.start(now); - oscillator.stop(now + 0.2); - } - - dispose(): void { - void this.context?.close(); - this.context = null; - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/CameraRig.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/CameraRig.ts deleted file mode 100644 index 4026bf160d..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/CameraRig.ts +++ /dev/null @@ -1,26 +0,0 @@ -import * as THREE from 'three'; - -export class CameraRig { - private readonly desiredPosition = new THREE.Vector3(); - private readonly lookTarget = new THREE.Vector3(); - - constructor( - private readonly camera: THREE.PerspectiveCamera, - private readonly offset = new THREE.Vector3(0, 9.5, 9.5), - ) {} - - snapTo(target: THREE.Vector3): void { - this.desiredPosition.copy(target).add(this.offset); - this.camera.position.copy(this.desiredPosition); - this.lookTarget.copy(target).add(new THREE.Vector3(0, 0.4, 0)); - this.camera.lookAt(this.lookTarget); - } - - update(delta: number, target: THREE.Vector3, lag: number): void { - this.desiredPosition.copy(target).add(this.offset); - const factor = 1 - Math.exp(-delta / Math.max(0.001, lag)); - this.camera.position.lerp(this.desiredPosition, factor); - this.lookTarget.copy(target).add(new THREE.Vector3(0, 0.35, -1.2)); - this.camera.lookAt(this.lookTarget); - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/CollisionSystem.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/CollisionSystem.ts deleted file mode 100644 index d58ea41e02..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/CollisionSystem.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as THREE from 'three'; -import type { Pickup } from '../entities/Pickup'; - -export class CollisionSystem { - private readonly delta = new THREE.Vector3(); - - collectPickups(playerPosition: THREE.Vector3, pickups: Pickup[], playerRadius: number): Pickup[] { - const collected: Pickup[] = []; - - for (const pickup of pickups) { - if (!pickup.active) continue; - this.delta.copy(playerPosition).sub(pickup.group.position); - this.delta.y = 0; - const radius = playerRadius + pickup.radius; - if (this.delta.lengthSq() <= radius * radius) { - pickup.collect(); - collected.push(pickup); - } - } - - return collected; - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/DebugTools.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/DebugTools.ts deleted file mode 100644 index bda716eedd..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/DebugTools.ts +++ /dev/null @@ -1,36 +0,0 @@ -import GUI from 'lil-gui'; -import type { PlayerTuning } from '../entities/Player'; - -export type DebugTuning = PlayerTuning & { - cameraLag: number; - exposure: number; - maxDpr: number; -}; - -export class DebugTools { - private gui: GUI | null = null; - - constructor(tuning: DebugTuning, onChange: () => void) { - const enabled = new URLSearchParams(window.location.search).has('debug'); - if (!enabled) return; - - this.gui = new GUI({ title: 'Game tuning' }); - this.gui.add(tuning, 'speed', 2, 14, 0.1); - this.gui.add(tuning, 'dashMultiplier', 1, 3, 0.05); - this.gui.add(tuning, 'acceleration', 4, 22, 0.1); - this.gui.add(tuning, 'cameraLag', 0.02, 0.8, 0.01); - this.gui.add(tuning, 'maxDpr', 1, 2, 0.25).onChange(onChange); - this.gui.add(tuning, 'exposure', 0.6, 1.8, 0.01).onChange(onChange); - } - - setHidden(hidden: boolean): void { - if (!this.gui) return; - if (hidden) this.gui.hide(); - else this.gui.show(); - } - - dispose(): void { - this.gui?.destroy(); - this.gui = null; - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/Hud.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/Hud.ts deleted file mode 100644 index 2d1d859cff..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/systems/Hud.ts +++ /dev/null @@ -1,36 +0,0 @@ -export class Hud { - private readonly scoreValue = this.getElement('#score-value'); - private readonly targetValue = this.getElement('#target-value'); - private readonly timerValue = this.getElement('#timer-value'); - private readonly statusLine = this.getElement('#status-line'); - - setTarget(target: number): void { - this.targetValue.textContent = String(target); - } - - update(score: number, target: number, elapsed: number, complete: boolean): void { - this.scoreValue.textContent = String(score); - this.targetValue.textContent = String(target); - const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0'); - const seconds = Math.floor(elapsed % 60).toString().padStart(2, '0'); - this.timerValue.textContent = `${minutes}:${seconds}`; - this.statusLine.textContent = complete ? 'Relay grid online' : 'Collect relays'; - } - - flashPickup(): void { - this.statusLine.animate( - [ - { transform: 'translateY(0)', borderLeftColor: '#f5ba49' }, - { transform: 'translateY(-3px)', borderLeftColor: '#48baa7' }, - { transform: 'translateY(0)', borderLeftColor: '#f5ba49' }, - ], - { duration: 220, easing: 'ease-out' }, - ); - } - - private getElement(selector: string): HTMLElement { - const element = document.querySelector(selector); - if (!element) throw new Error(`Missing HUD element: ${selector}`); - return element; - } -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/utils/dispose.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/utils/dispose.ts deleted file mode 100644 index ebefccc2e9..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/utils/dispose.ts +++ /dev/null @@ -1,29 +0,0 @@ -import * as THREE from 'three'; - -export function disposeObject3D(root: THREE.Object3D): void { - root.traverse((object: THREE.Object3D) => { - const mesh = object as THREE.Mesh; - if (mesh.geometry) { - mesh.geometry.dispose(); - } - - const materials = Array.isArray(mesh.material) ? mesh.material : mesh.material ? [mesh.material] : []; - for (const material of materials) { - disposeMaterial(material); - } - }); -} - -function disposeMaterial(material: THREE.Material): void { - const values = Object.values(material as unknown as Record); - for (const value of values) { - if (isThreeTexture(value)) { - value.dispose(); - } - } - material.dispose(); -} - -function isThreeTexture(value: unknown): value is THREE.Texture { - return Boolean(value && typeof value === 'object' && (value as { isTexture?: boolean }).isTexture); -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/utils/random.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/utils/random.ts deleted file mode 100644 index c584d7a6fe..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/utils/random.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Deterministic seeded RNG (mulberry32). Route ALL gameplay randomness through - * a seeded generator instead of Math.random so the __THREE_GAME_TEST_HOOKS__ - * seed() hook keeps visual baselines and bot playtests reproducible. - */ -export function createSeededRandom(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = state; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/vite-env.d.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/vite-env.d.ts deleted file mode 100644 index a2abb4acce..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/src/vite-env.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -/// - -interface ThreeGameDiagnostics { - frame: number; - elapsed: number; - score: number; - targetScore: number; - complete: boolean; - player: { - position: { x: number; y: number; z: number }; - speed: number; - }; - renderer: { - calls: number; - triangles: number; - geometries: number; - textures: number; - }; - canvas: { - clientWidth: number; - clientHeight: number; - width: number; - height: number; - dpr: number; - }; -} - -interface ThreeGameTestHooks { - /** Re-seed the game RNG; all gameplay randomness must flow through it. */ - seed(value: number): void; - /** Jump to a named state for baselines (scaffold: 'active-play' | 'complete'). */ - setState(name: string): void; - /** Freeze the simulation while continuing to render the current frame. */ - setPausedForScreenshot(paused: boolean): void; - /** Freeze ambient/idle animation time so screenshots are stable. */ - setReducedMotion(enabled: boolean): void; - /** Hide debug UI (lil-gui) before capturing. */ - hideDebugUi(hidden: boolean): void; -} - -interface Window { - __THREE_GAME_DIAGNOSTICS__?: ThreeGameDiagnostics; - __THREE_GAME_TEST_HOOKS__?: ThreeGameTestHooks; -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/bot-playtest.template.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/bot-playtest.template.ts deleted file mode 100644 index 17d76c7ba2..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/bot-playtest.template.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { expect, test } from '@playwright/test'; - -// Copy this file to tests/bot-playtest.spec.ts to enable automated playtests. -// The bot drives the game through scripted real input and measures whether the -// game actually progresses: score/objective movement, player motion, softlock -// windows, and error-free play. Adapt `INPUT_SCRIPT` to your game's controls -// and level layout — keep the progression assertion; a bot that cannot make -// the objective move is evidence the game is unclear or broken. -// -// Requires window.__THREE_GAME_DIAGNOSTICS__ (frame/score/complete/player) and -// window.__THREE_GAME_TEST_HOOKS__ (seed/setState) — both ship in the scaffold. - -type BotSnapshot = { - frame: number; - score: number; - complete: boolean; - x: number; - z: number; -}; - -// Keyboard sweep tuned to the scaffold arena (22x14, pickups in two rows). -// Each step holds keys for `ms` then samples diagnostics. -const INPUT_SCRIPT: Array<{ keys: string[]; ms: number }> = [ - { keys: ['KeyW'], ms: 1000 }, - { keys: ['KeyA'], ms: 1900 }, - { keys: ['KeyD'], ms: 3400 }, - { keys: ['KeyW'], ms: 350 }, - { keys: ['KeyA'], ms: 3400 }, - { keys: ['KeyS'], ms: 1700 }, - { keys: ['KeyD'], ms: 3400 }, - { keys: ['KeyS'], ms: 350 }, - { keys: ['KeyA'], ms: 3400 }, -]; - -test('bot playtest: scripted input drives progress without errors', async ({ page }, testInfo) => { - test.skip( - testInfo.project.name !== 'desktop-chrome', - 'The bot uses keyboard input; mobile touch input is exercised by visual.spec.ts.', - ); - test.setTimeout(90_000); - - const pageErrors: string[] = []; - const consoleErrors: string[] = []; - page.on('pageerror', (error) => pageErrors.push(error.message)); - page.on('console', (message) => { - if (message.type() === 'error') consoleErrors.push(message.text()); - }); - - await page.goto('/'); - await page.waitForFunction(() => (window.__THREE_GAME_DIAGNOSTICS__?.frame ?? 0) > 10); - await page.evaluate(() => { - window.__THREE_GAME_TEST_HOOKS__?.seed(12345); - window.__THREE_GAME_TEST_HOOKS__?.setState('active-play'); - }); - - const sample = (): Promise => - page.evaluate(() => { - const d = window.__THREE_GAME_DIAGNOSTICS__; - if (!d) return null; - return { - frame: d.frame, - score: d.score, - complete: d.complete, - x: d.player.position.x, - z: d.player.position.z, - }; - }); - - const before = await sample(); - expect(before, 'diagnostics must be published before the bot can play').not.toBeNull(); - - const snapshots: BotSnapshot[] = [before as BotSnapshot]; - let softlockWindows = 0; - let distance = 0; - let stepOfFirstScore = -1; - - for (const [index, step] of INPUT_SCRIPT.entries()) { - for (const key of step.keys) await page.keyboard.down(key); - await page.waitForTimeout(step.ms); - for (const key of step.keys) await page.keyboard.up(key); - - const snap = await sample(); - const prev = snapshots[snapshots.length - 1]; - if (snap) { - const moved = Math.hypot(snap.x - prev.x, snap.z - prev.z); - distance += moved; - const progressed = snap.score > prev.score || (snap.complete && !prev.complete); - if (progressed && stepOfFirstScore === -1) stepOfFirstScore = index; - // Softlock signature: frames advance while held input neither moves the - // player nor progresses the objective. - if (snap.frame > prev.frame && moved < 0.2 && !progressed) softlockWindows += 1; - snapshots.push(snap); - } - } - - const after = snapshots[snapshots.length - 1]; - const report = { - steps: INPUT_SCRIPT.length, - framesAdvanced: after.frame - (before as BotSnapshot).frame, - scoreBefore: (before as BotSnapshot).score, - scoreAfter: after.score, - complete: after.complete, - distanceTravelled: Number(distance.toFixed(2)), - stepOfFirstScore, - softlockWindows, - consoleErrors, - pageErrors, - }; - await testInfo.attach('bot-playtest-report', { - body: JSON.stringify(report, null, 2), - contentType: 'application/json', - }); - console.log(`bot playtest: ${JSON.stringify(report)}`); - - expect(pageErrors, 'page errors during bot play').toEqual([]); - expect(consoleErrors, 'console errors during bot play').toEqual([]); - expect(report.framesAdvanced, 'game loop must keep running').toBeGreaterThan(100); - expect(report.distanceTravelled, 'player must respond to scripted input').toBeGreaterThan(5); - expect(report.softlockWindows, 'held input repeatedly produced no motion or progress').toBeLessThanOrEqual(2); - expect( - report.scoreAfter, - 'scripted sweep should progress the objective — tune INPUT_SCRIPT to your level layout', - ).toBeGreaterThan(report.scoreBefore); -}); diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/visual-regression.template.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/visual-regression.template.ts deleted file mode 100644 index 4252e53a47..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/visual-regression.template.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { expect, test, type Page } from '@playwright/test'; - -// Copy this file to tests/visual-regression.spec.ts when the game is stable -// enough for screenshot baselines. First run: -// npx playwright test tests/visual-regression.spec.ts --update-snapshots -// Then compare: -// npx playwright test tests/visual-regression.spec.ts -// -// REQUIREMENT: the game must implement window.__THREE_GAME_TEST_HOOKS__ -// (see src/game/Game.ts installTestHooks and src/vite-env.d.ts). Without real -// hooks, baselines capture a live animating scene and every rerun diffs. -// prepareDeterministicScreenshot fails loudly if the hooks object is missing. - -async function prepareDeterministicScreenshot(page: Page, stateName: string) { - await page.goto('/'); - await page.waitForFunction(() => (window.__THREE_GAME_DIAGNOSTICS__?.frame ?? 0) > 10); - - const hasHooks = await page.evaluate(() => Boolean(window.__THREE_GAME_TEST_HOOKS__)); - if (!hasHooks) { - throw new Error( - '__THREE_GAME_TEST_HOOKS__ is not defined. Implement the deterministic test hooks ' + - '(seed/setState/setPausedForScreenshot/setReducedMotion/hideDebugUi) before ' + - 'enabling visual baselines — see threejs-qa-release references/visual-test-harness.md.', - ); - } - - await page.evaluate((name) => { - const hooks = window.__THREE_GAME_TEST_HOOKS__; - hooks?.seed(12345); - hooks?.setReducedMotion(true); - hooks?.hideDebugUi(true); - hooks?.setState(name); - hooks?.setPausedForScreenshot(true); - }, stateName); - - await page.waitForTimeout(150); -} - -// State names must match the game's setState implementation. The scaffold -// supports 'active-play' and 'complete'; add baselines for your game's own -// states (fail/retry, menus, boss phases) as you implement them. - -test('active play visual baseline', async ({ page }, testInfo) => { - await prepareDeterministicScreenshot(page, 'active-play'); - await expect(page).toHaveScreenshot(`active-play-${testInfo.project.name}.png`, { - fullPage: true, - maxDiffPixelRatio: 0.015, - }); -}); - -test('complete state visual baseline', async ({ page }, testInfo) => { - await prepareDeterministicScreenshot(page, 'complete'); - await expect(page).toHaveScreenshot(`complete-${testInfo.project.name}.png`, { - fullPage: true, - maxDiffPixelRatio: 0.015, - }); -}); diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/visual.spec.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/visual.spec.ts deleted file mode 100644 index c2ee4442bb..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tests/visual.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { expect, test } from '@playwright/test'; -import { PNG } from 'pngjs'; - -type CanvasSample = { - ok: boolean; - reason: string; - variance?: number; - colorBuckets?: number; -}; - -async function sampleCanvas(page: import('@playwright/test').Page): Promise { - const canvas = page.locator('#game-canvas'); - const box = await canvas.boundingBox(); - if (!box || box.width < 32 || box.height < 32) { - return { ok: false, reason: 'canvas-too-small' }; - } - - const buffer = await canvas.screenshot(); - const png = PNG.sync.read(buffer); - let min = 255; - let max = 0; - let alphaPixels = 0; - const buckets = new Set(); - const stride = Math.max(1, Math.floor((png.width * png.height) / 4096)); - - for (let pixel = 0; pixel < png.width * png.height; pixel += stride) { - const offset = pixel * 4; - const r = png.data[offset]; - const g = png.data[offset + 1]; - const b = png.data[offset + 2]; - const a = png.data[offset + 3]; - min = Math.min(min, r, g, b); - max = Math.max(max, r, g, b); - if (a > 0) alphaPixels += 1; - buckets.add(`${r >> 4},${g >> 4},${b >> 4},${a >> 6}`); - } - - const variance = max - min; - return { - ok: alphaPixels > 256 && (variance > 8 || buckets.size > 3), - reason: 'sampled', - variance, - colorBuckets: buckets.size, - }; -} - -test('renders a nonblank interactive game canvas', async ({ page }, testInfo) => { - const consoleErrors: string[] = []; - const pageErrors: string[] = []; - page.on('console', (message) => { - if (message.type() === 'error') consoleErrors.push(message.text()); - }); - page.on('pageerror', (error) => pageErrors.push(error.message)); - - await page.goto('/'); - await expect(page.locator('#game-canvas')).toBeVisible(); - await page.waitForFunction(() => (window.__THREE_GAME_DIAGNOSTICS__?.frame ?? 0) > 10); - - const sample = await sampleCanvas(page); - expect(sample, JSON.stringify(sample)).toMatchObject({ ok: true }); - - const before = await page.evaluate(() => window.__THREE_GAME_DIAGNOSTICS__?.player.position.z ?? 0); - - if (testInfo.project.name.includes('mobile')) { - const stick = page.locator('#touch-stick'); - await expect(stick).toBeVisible(); - const box = await stick.boundingBox(); - expect(box).not.toBeNull(); - if (box) { - await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); - await page.mouse.down(); - await page.mouse.move(box.x + box.width / 2, box.y + box.height * 0.05, { steps: 6 }); - await page.waitForTimeout(450); - await page.mouse.up(); - } - } else { - await page.keyboard.down('KeyW'); - await page.waitForTimeout(450); - await page.keyboard.up('KeyW'); - } - - await expect - .poll(async () => page.evaluate(() => window.__THREE_GAME_DIAGNOSTICS__?.player.position.z ?? 0)) - .toBeLessThan(before - 0.3); - - const screenshot = await page.screenshot({ fullPage: true }); - await testInfo.attach(`${testInfo.project.name}-game`, { - body: screenshot, - contentType: 'image/png', - }); - - expect(consoleErrors).toEqual([]); - expect(pageErrors).toEqual([]); -}); diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tsconfig.json b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tsconfig.json deleted file mode 100644 index 4c5de900a4..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/tsconfig.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "useDefineForClassFields": true, - "module": "ESNext", - "moduleResolution": "Bundler", - "allowImportingTsExtensions": false, - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - "skipLibCheck": true, - "isolatedModules": true, - "noEmit": true, - "types": ["vite/client", "node"] - }, - "include": ["src", "tests", "playwright.config.ts"] -} diff --git a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/vite.config.ts b/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/vite.config.ts deleted file mode 100644 index 5fa4634f3c..0000000000 --- a/.agents/skills/threejs-gameplay-systems/assets/threejs-vite-game/vite.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { defineConfig } from 'vite'; - -export default defineConfig({ - server: { - host: '127.0.0.1', - port: 5188, - strictPort: true, - }, - preview: { - host: '127.0.0.1', - port: 4188, - strictPort: true, - }, - build: { - sourcemap: true, - chunkSizeWarningLimit: 900, - }, -}); diff --git a/.agents/skills/threejs-gameplay-systems/references/checklists/endless-runner-premium-quality.md b/.agents/skills/threejs-gameplay-systems/references/checklists/endless-runner-premium-quality.md deleted file mode 100644 index c43e4ee834..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/checklists/endless-runner-premium-quality.md +++ /dev/null @@ -1,21 +0,0 @@ -# Endless Runner Premium Quality Checklist - -- Player avatar or vehicle has a strong readable silhouette from the chase camera. -- Player avatar or vehicle includes visible subassemblies such as body shell, cockpit/core, fins/wings, engines, trim, emissive state, and trail. -- Player collision footprint is visually understandable at speed. -- Obstacle families have distinct silhouettes, colors/materials, and telegraphing. -- At least three obstacle families are present: low barrier, gate/arch, moving/animated or special hazard. -- Rewards/pickups are readable at distance and have collection feedback. -- At least two reward/interactable variants exist beyond one recolored pickup. -- Lane/path markings communicate safe choices without turning into visual noise. -- Foreground, midground, and background layers create speed and depth. -- World segments include reusable procedural prop kits, not only stretched boxes. -- Skyline/world modules include rooflines, setbacks, signage/window bands, supports, cables, antennas, or parallax layers. -- Speed effects reinforce motion while preserving the next lane decision. -- Camera FOV, follow smoothing, shake, roll, and horizon framing support speed without nausea. -- HUD prioritizes run state: distance/progress, score/streak, health/shield, boost/overdrive, fail/retry. -- HUD is not a grid of generic debug/stat cards unless that is an intentional diegetic style. -- Fail, crash, near miss, boost, milestone, and restart states have polished feedback. -- Mobile layout keeps controls away from hazards, player focal area, and safe-area edges. -- Worst-case segment performance is checked with renderer diagnostics. -- The game is playtested through ramp-up, ordinary collection, hazard avoidance, failure, and restart. diff --git a/.agents/skills/threejs-gameplay-systems/references/checklists/game-design-level-design.md b/.agents/skills/threejs-gameplay-systems/references/checklists/game-design-level-design.md deleted file mode 100644 index 25406acaaf..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/checklists/game-design-level-design.md +++ /dev/null @@ -1,19 +0,0 @@ -# Game Design And Level Design Checklist - -Use before claiming a new game, major gameplay upgrade, level/encounter pass, premium gameplay, or polished gameplay is complete. - -- A game design brief names player promise, target feeling, primary verb, objective, pressure, reward, fail/retry, and non-goals. -- The core loop is written as verb -> objective -> pressure -> reward/progression -> failure/retry. -- The loop is implemented through real input, not only described. -- The first playable minute includes at least one objective, one meaningful pressure source, one feedback/reward event, and one setback or fail/retry path when genre-appropriate. -- Player skill expression is explicit: what a better player does differently. -- Difficulty curve is named and tied to parameters, spawn tables, wave composition, speed, resource economy, or spatial constraints. -- Level/track/arena/map/wave/hole/puzzle plan includes start, first decision, first threat, first reward, landmarks, escalation, recovery beats, and failure readability. -- Greybox/blockout scale and routes are proven before expensive visual detail. -- Obstacles, enemies, rewards, and interactables are placed to create decisions, not random clutter. -- Camera framing supports the next decision in the planned space. -- UI/HUD communicates objective, pressure, reward, or fail state. -- Game-feel tuning covers control response, simulated space, camera, feedback, and restart speed. -- At least one active playtest loop was used to tune values. -- Fun-factor rejection tests have no unresolved blocker for the requested quality bar. -- Final report includes design brief, core loop contract, level/encounter plan, tuning notes, evidence, and remaining design risks. diff --git a/.agents/skills/threejs-gameplay-systems/references/checklists/game-feel.md b/.agents/skills/threejs-gameplay-systems/references/checklists/game-feel.md deleted file mode 100644 index bdc4badda6..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/checklists/game-feel.md +++ /dev/null @@ -1,20 +0,0 @@ -# Game Feel Checklist - -Use before claiming a game feels good, is juicy, is polished, or is premium. Pairs with references/game-feel.md. - -- The primary verb produces a visible response within 100ms of input. -- Every scoring, pickup, damage, and death event has at least one visual and one audio response. -- Screenshake is trauma-based with the `trauma²` curve, per-second decay, and a hard cap. -- Trauma magnitude scales with event weight (pickup subtle, explosion unmistakable). -- Hitstop scales the gameplay delta only; camera, shake, tweens, and HUD keep the real delta. -- Hitstop is reserved for heavy contact, not fired on every minor event. -- The render loop is never paused to create a freeze; only gameplay delta is scaled. -- Squash-and-stretch preserves volume and settles with an overshoot (easeOutBack). -- FOV punch calls updateProjectionMatrix() and decays back to base. -- Impact flash stores the material's base emissive value and tweens back to it. -- Feedback never obscures the next player decision (shake/flash/hitstop stay readable). -- Gamepad rumble is feature-detected and matched in strength to the event. -- Repeated audio samples use pitch/volume variance so they never sound identical. -- All gameplay and effect randomness routes through createSeededRandom, never Math.random. -- Time-based effects are driven by accumulated game time, not wall clock. -- Each core event maps to a full feedback stack (see the tuning table), not a single cue. diff --git a/.agents/skills/threejs-gameplay-systems/references/checklists/new-game-definition-of-done.md b/.agents/skills/threejs-gameplay-systems/references/checklists/new-game-definition-of-done.md deleted file mode 100644 index a07a983522..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/checklists/new-game-definition-of-done.md +++ /dev/null @@ -1,20 +0,0 @@ -# New Game Definition Of Done - -- The project installs with `npm install`. -- `npm run dev` starts a local Vite server. -- `npm run build` completes. -- The first screen is the game, not a landing page. -- The player can interact within 5 seconds. -- A compact game design brief exists: player promise, primary verb, objective, pressure, reward, fail/retry, and non-goals. -- A level/encounter plan exists for the first playable space, track, arena, wave, hole, table, or puzzle. -- There is a clear objective, score, timer, health, level target, or fail condition. -- The core loop is proven through real input, not only described in text. -- The first playable minute includes at least one meaningful decision and one feedback/reward event. -- Keyboard/mouse input works on desktop. -- Touch or pointer input works if mobile is in scope. -- The camera frames the playable area at desktop and mobile sizes. -- HUD text is readable and does not cover critical gameplay. -- Browser console has no blocking errors. -- A screenshot proves the canvas rendered. -- A canvas-pixel check proves the canvas is not blank. -- Final report names design brief, level/encounter plan, controls, verification evidence, and remaining risks. diff --git a/.agents/skills/threejs-gameplay-systems/references/game-design-level-design.md b/.agents/skills/threejs-gameplay-systems/references/game-design-level-design.md deleted file mode 100644 index 0a8aa6a107..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/game-design-level-design.md +++ /dev/null @@ -1,155 +0,0 @@ -# Game Design And Level Design - -Use this reference before broad new-game creation, major mechanic changes, progression tuning, level/arena/track/wave design, combat encounters, or any claim that gameplay is premium, polished, complete, or less generic. - -This is not a long design document. It is a compact player-facing contract that turns an idea into implementable rules, spaces, pacing, and tuning checks. - -Research basis: Unity's GDD guidance emphasizes player goals, rules/mechanics, difficulty, core loop, and feedback; MDA separates mechanics, runtime dynamics, and player experience; Unity's level-design material emphasizes concept, blockout/greybox, playtest, and iteration; Steve Swink's game-feel framing centers real-time control, simulated space, and polish. - -## Design Brief Gate - -Before implementation, write a brief with: - -- Player promise: the fantasy in one sentence. -- Target feeling: tense, fast, tactical, elegant, chaotic, precise, cozy, etc. -- Primary verb: steer, aim, shoot, place, dodge, bank, sink, parry, solve. -- Secondary verbs: boost, upgrade, collect, block, drift, aim, reload, switch lane. -- Core loop: what the player repeats every 5-30 seconds. -- Progression loop: what changes across 1-5 minutes. -- Fail/retry loop: how the player loses, learns, and restarts. -- Scoring/economy: what is rewarded, what is spent, what creates risk. -- Skill expression: what a better player does differently. -- Readability promise: how the next decision is communicated. -- Non-goals: features intentionally out of scope for this slice. - -Reject "explore a cool scene" as a design brief. A game brief must include player decisions, pressure, feedback, and consequence. - -## Core Loop Contract - -Write the loop as: - -```text -Player does [verb] to achieve [objective] while [pressure] creates risk; success gives [reward/progression], failure causes [cost/retry]. -``` - -Then prove the loop in code: - -- The primary verb is mapped to real input. -- The objective is visible in the world or HUD. -- Pressure exists within the first playable minute. -- Reward/progression changes game state, not only visuals. -- Failure or setback teaches what happened. -- Restart/retry is fast enough to encourage another attempt. - -## MDA Check - -Use this as a compact design review: - -- Mechanics: exact rules, controls, collisions, timers, spawn tables, physics, scoring. -- Dynamics: what happens when a real player uses those rules under pressure. -- Aesthetics: the intended feeling and whether screenshots/playtest evidence supports it. - -If the intended feeling does not emerge from the current mechanics, change mechanics or level layout. Do not try to fix missing dynamics with graphics alone. - -## Level And Encounter Plan - -Before building a track, arena, map, wave set, table, or puzzle space, define: - -- Spatial format: lane, circuit, arena, corridor, open field, table, grid, tower path, puzzle room. -- Camera contract: what the camera can and cannot see. -- Player start, first decision, first reward, first threat. -- Safe zone or learning space, if the genre needs one. -- Main route plus optional risk/reward route, if applicable. -- Landmarks or orientation anchors. -- Escalation: how challenge increases every 20-60 seconds or per wave/hole/lap/phase. -- Recovery beats: where the player can breathe or regain control. -- Failure readability: how hazards, attacks, misses, and penalties are telegraphed. -- Reuse plan: which pieces are modular, randomized, or parameterized. - -Greybox first: use simple shapes to prove scale, route, timing, line-of-sight, collision, and pacing before investing in art detail. - -## Genre Patterns - -### Endless Runner - -- Teach lanes or steering with an early safe segment. -- Alternate compression and release: dense hazard groups, then reward/visibility windows. -- Use at least three obstacle families with distinct silhouettes and telegraphs. -- Difficulty can ramp via speed, lane pressure, obstacle combinations, and reward placement. - -### Arcade Racer - -- Define handling fantasy first: drift-heavy, grip racing, hover glide, combat racer, rally. -- Track should have readable apexes, braking/drift cues, recovery width, landmarks, and route rhythm. -- Add skill tests: clean racing line, boost timing, drift angle, traffic threading, shortcut risk. - -### Dogfight / Space Shooter - -- Define engagement range, turn rate, projectile speed, lock-on/lead affordance, and escape options. -- Encounters need target readability, off-screen threat indicators, and moments to reacquire orientation. -- Use waves or objectives that force movement, not only circular chasing. - -### Tower Defense - -- Define path topology, chokepoints, build zones, enemy archetypes, tower roles, economy cadence, and wave tells. -- Good maps create placement decisions, not just optimal obvious tiles. -- Waves should test different tower roles and expose upcoming enemy types before punishment. - -### Billiards / Pool / Snooker - -- Physics and rules are the game design. Use readable shot aim, cue force, spin/english, turn state, legal target feedback, foul feedback, and camera reset. -- Level design is table readability: pockets, rails, ball colors, aim lines, shadows, and overhead/low camera options. - -### Mini Golf - -- Each hole should have one clear read, one trick, and one risk/reward route. -- Escalate via ramps, banks, moving blockers, portals, split paths, gravity changes, and timing windows. -- Avoid holes where the first shot outcome is unreadable from the tee. - -### Boss Fight / Action Arena - -- Define boss phases, telegraphs, recovery windows, player punish windows, arena hazards, and camera lock behavior. -- Every attack needs a readable tell, avoid/defend option, impact feedback, and cooldown. -- Phases should add combinations or arena pressure, not just more health. - -### Puzzle / Physics Game - -- State the rule being taught in each puzzle. -- First puzzle teaches, second confirms, third twists. -- Failure should reveal information. Avoid hidden dependency chains that require guessing. - -## Difficulty And Pacing - -Use a curve, not random escalation: - -- Introduce one new concept at a time. -- Combine known concepts after they are understood. -- Add breathing space after high-pressure moments. -- Increase challenge through timing, density, speed, resource scarcity, enemy mix, or spatial constraints. -- Keep early failures recoverable unless the genre is intentionally harsh. -- Tune with named constants and record changes. - -## Fun-Factor Rejection Tests - -Reject or iterate if any are true: - -- The first 30 seconds lack a real decision. -- The player can ignore the main mechanic and still progress. -- The objective is unclear without reading source code or instructions. -- Failure happens before the player can understand why. -- Challenge is only "more things" rather than better combinations. -- Rewards do not change strategy, score, progression, or feel. -- The space is decorative and does not shape decisions. -- The game is fun only in the designer's explanation, not in active play. - -## Report Requirements - -Report: - -- Game design brief. -- Core loop contract. -- Level/encounter plan. -- Difficulty/pacing plan. -- Tuning constants changed. -- Fun-factor rejection tests passed or remaining failures. -- Evidence from active play, not just a screenshot. diff --git a/.agents/skills/threejs-gameplay-systems/references/game-feel.md b/.agents/skills/threejs-gameplay-systems/references/game-feel.md deleted file mode 100644 index 72a5230300..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/game-feel.md +++ /dev/null @@ -1,315 +0,0 @@ -# Game Feel - -Use this reference when a game "works" but does not feel good: the primary verb lands without weight, hits read as bookkeeping, pickups vanish silently. Game feel (juice) is the layer of response, contact feedback, and audio-visual sync that turns correct mechanics into satisfying ones. - -Game feel is state communication, not decoration. Apply effects in this order of operations; each layer depends on the one before it: - -1. Input latency: the primary verb must produce a visible response within ~100ms. Fix this first; no amount of juice hides a laggy control. -2. Response curves: acceleration, easing, and overshoot on the player's own motion. -3. Contact feedback: what happens at the moment of impact, pickup, or score (flash, squash, hitstop, shake). -4. Camera: shake, kick, FOV punch that amplify contact without hiding the field of play. -5. Audio-visual sync: sound fires on the same frame as the visual, with pitch/volume variance so repeats stay alive. - -Readability rule: feedback must clarify game state, never obscure the next decision. If shake, flash, or hitstop hides the thing the player must react to next, it is a bug, not polish. Scale every effect so the strongest events (death, explosion) are unmistakable and the weakest (pickup) stay subtle. - -All code below is copy-pasteable, strict-TS clean, dependency-free, and matches the scaffold (`update(delta, elapsed)`, class systems, `createSeededRandom`). - -## Tween / Easing Helper - -No external tween library. A tiny manager updated with `delta`, plus three curves that cover 90% of feel work. - -```ts -export type Easing = (t: number) => number; - -export const easeInQuad: Easing = (t) => t * t; -export const easeOutCubic: Easing = (t) => 1 - Math.pow(1 - t, 3); -export const easeOutBack: Easing = (t) => { - const c1 = 1.70158; - const c3 = c1 + 1; - return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2); -}; - -interface ActiveTween { - elapsed: number; - duration: number; - easing: Easing; - onUpdate: (value: number) => void; - onComplete?: () => void; -} - -export class TweenManager { - private readonly tweens: ActiveTween[] = []; - - tween( - durationSec: number, - onUpdate: (value: number) => void, - easing: Easing = easeOutCubic, - onComplete?: () => void, - ): void { - this.tweens.push({ elapsed: 0, duration: durationSec, easing, onUpdate, onComplete }); - } - - update(delta: number): void { - for (let i = this.tweens.length - 1; i >= 0; i -= 1) { - const t = this.tweens[i]; - t.elapsed += delta; - const k = Math.min(t.elapsed / t.duration, 1); - t.onUpdate(t.easing(k)); - if (t.elapsed >= t.duration) { - t.onComplete?.(); - this.tweens.splice(i, 1); - } - } - } -} -``` - -Update the manager with the **real** delta (feedback must stay live during hitstop). `easeOutBack` returns values above 1 near the end; that overshoot is the bounce. - -## Trauma-Based Screenshake - -Add trauma on events; shake is `trauma²` so small events barely move the camera and big ones snap hard. Trauma decays linearly per second and is hard-capped. Drive the noise from accumulated game time (deterministic), not wall clock. - -```ts -import * as THREE from 'three'; - -const TRAUMA_MAX = 1; -const TRAUMA_DECAY = 1.4; // trauma units per second -const MAX_OFFSET = 0.55; // world units at full shake -const MAX_ROLL = 0.1; // radians at full shake - -// Deterministic value noise in [-1, 1]; per-axis seed keeps axes independent. -function pseudoNoise(t: number, seed: number): number { - const x = Math.sin(t * 12.9898 + seed * 78.233) * 43758.5453; - return (x - Math.floor(x)) * 2 - 1; -} - -export class ShakeRig { - private trauma = 0; - private time = 0; - - addTrauma(amount: number): void { - this.trauma = Math.min(TRAUMA_MAX, this.trauma + amount); - } - - // Call every frame AFTER CameraRig has written the base transform. - update(delta: number, camera: THREE.PerspectiveCamera): void { - this.time += delta; - this.trauma = Math.max(0, this.trauma - TRAUMA_DECAY * delta); - if (this.trauma <= 0) return; - const shake = this.trauma * this.trauma; - const freq = this.time * 32; - camera.position.x += MAX_OFFSET * shake * pseudoNoise(freq, 1); - camera.position.y += MAX_OFFSET * shake * pseudoNoise(freq, 2); - camera.rotation.z += MAX_ROLL * shake * pseudoNoise(freq, 3); - } -} -``` - -Recommended trauma per event: pickup `0.15`, hit `0.4`, explosion `0.7`. Cap at `1.0` so stacked events cannot fling the camera. The additive offset does not accumulate because `CameraRig` re-derives position from the follow target and `lookAt` re-derives rotation every frame. - -## Hitstop - -A brief freeze on heavy contact sells weight. Scale the gameplay delta, never the render loop. - -```ts -// Fields on Game: -private timeScale = 1; -private hitstopRemaining = 0; - -hitstop(durationMs: number, scale = 0.05): void { - this.hitstopRemaining = Math.max(this.hitstopRemaining, durationMs / 1000); - this.timeScale = scale; -} - -private update(delta: number, elapsed: number): void { - if (this.hitstopRemaining > 0) { - this.hitstopRemaining -= delta; // decay in REAL time - if (this.hitstopRemaining <= 0) this.timeScale = 1; - } - const gameplayDelta = delta * this.timeScale; - - // Gameplay reads the scaled delta so the world crawls... - this.player.update(gameplayDelta, elapsed, this.input, this.tuning, ARENA); - for (const pickup of this.pickups) pickup.update(gameplayDelta, elapsed); - - // ...but camera, shake, tweens, and HUD read the REAL delta so feedback stays live. - this.cameraRig.update(delta, this.player.group.position, this.tuning.cameraLag); - this.shakeRig.update(delta, this.camera); - this.tweens.update(delta); -} -``` - -Recommended: 60-90ms at `0.05` scale on heavy hits only. Never call `loop.stop()` or skip `requestAnimationFrame` to freeze — the frame must keep drawing so the frozen moment is visible. Only the gameplay delta is scaled. - -## Squash-and-Stretch - -Deform on impact or jump, then overshoot back with `easeOutBack`. Preserve volume: when one axis scales by `s`, scale the other two by `1 / sqrt(s)`. - -```ts -// Impact squash (squashY < 1); jump stretch uses squashY > 1. -squash(target: THREE.Object3D, squashY = 0.85, durationSec = 0.18): void { - const startXZ = 1 / Math.sqrt(squashY); // volume-preserving counter-scale - this.tweens.tween( - durationSec, - (t) => { - const y = squashY + (1 - squashY) * t; // squashY -> 1 - const xz = startXZ + (1 - startXZ) * t; // stretch -> 1 - target.scale.set(xz, y, xz); - }, - easeOutBack, // overshoot past 1 gives the bouncy settle - ); -} -``` - -Use ~1.15 stretch on jump takeoff and ~0.9 squash on landing, both returning over ~180ms. - -## Camera Kick / FOV Punch - -An additive FOV bump reads as acceleration or shock. Decay it toward 0 with a ~200ms time constant. - -```ts -private baseFov = 48; -private fovPunch = 0; // additive degrees - -punchFov(degrees: number): void { - this.fovPunch = Math.min(10, this.fovPunch + degrees); // additive, clamped -} - -private updateFov(delta: number): void { - if (this.fovPunch <= 0.001) return; - this.fovPunch *= Math.exp(-delta / 0.2); - if (this.fovPunch < 0.001) this.fovPunch = 0; - this.camera.fov = this.baseFov + this.fovPunch; - this.camera.updateProjectionMatrix(); // REQUIRED after any fov change -} -``` - -Recommended +4..8° on boost, dash, or hit. Forgetting `updateProjectionMatrix()` leaves the FOV visually unchanged. - -## Impact Flash - -Pulse `emissiveIntensity` on the hit material and tween it back. Store the base value once; the material's `emissive` color must be non-black for the pulse to show. - -```ts -flashHit(material: THREE.MeshStandardMaterial, peak = 2.4, durationSec = 0.22): void { - const base = (material.userData.baseEmissive ??= material.emissiveIntensity); - this.tweens.tween( - durationSec, - (t) => { - material.emissiveIntensity = base + (peak - base) * (1 - t); // peak -> base - }, - easeOutCubic, - ); -} -``` - -For big events (explosion, death), add a one-frame full-screen white flash: a `position: fixed` DOM `
` with `pointer-events: none`, animated `opacity: 0.8 -> 0` over ~90-120ms via `element.animate(...)`. Cheaper than a render-target flash and it never touches the 3D pipeline. - -## Pickup Pop - -Collected items should pop, rise, and fade rather than blink out. - -```ts -playPickupPop(mesh: THREE.Mesh, material: THREE.MeshStandardMaterial): void { - const startY = mesh.position.y; - material.transparent = true; - this.tweens.tween( - 0.28, - (t) => { - mesh.scale.setScalar(1 + 0.6 * (1 - t)); // 1.6 -> 1.0 - mesh.position.y = startY + t * 1.2; // rise - material.opacity = 1 - t; // fade - }, - easeOutCubic, - () => { - mesh.visible = false; - }, - ); -} -``` - -Punch the HUD counter on the same event (add to `Hud`, reusing the scaffold's WAAPI pattern): - -```ts -punchScore(): void { - this.scoreValue.animate( - [{ transform: 'scale(1.2)' }, { transform: 'scale(1)' }], - { duration: 120, easing: 'ease-out' }, - ); -} -``` - -## Gamepad Rumble - -Feature-detect `vibrationActuator`; `playEffect` returns a promise that may reject on unsupported hardware, so swallow it. - -```ts -export function rumble(durationMs: number, strong = 0.6, weak = 0.3): void { - const pads = navigator.getGamepads?.() ?? []; - for (const pad of pads) { - const actuator = pad?.vibrationActuator; - if (!actuator) continue; // optional chaining covers older browsers - void actuator.playEffect('dual-rumble', { - duration: durationMs, - strongMagnitude: strong, - weakMagnitude: weak, - }); - } -} -``` - -Match rumble to the hit: light (180ms, 0.3) on pickups, heavy (250ms, 0.9) on death or explosion. - -## Audio Feel Coupling - -Identical repeated samples feel cheap: the ear detects the exact repeat as artificial (the "machine-gun" effect). Vary pitch per playback, and duck ambient/music while hitstop holds so the impact reads. - -```ts -// AudioSystem: pitch-vary each shot; duck holds during hitstop. -private duck = 1; - -play(buffer: AudioBuffer, rng: () => number, baseGain = 0.8): void { - if (!this.context || this.context.state !== 'running') return; - const source = this.context.createBufferSource(); - const gain = this.context.createGain(); - source.buffer = buffer; - source.playbackRate.value = 1 + (rng() - 0.5) * 0.12; // +/-6% pitch - gain.gain.value = baseGain * this.duck; - source.connect(gain).connect(this.context.destination); - source.start(); -} - -setDuck(value: number): void { - this.duck = value; // e.g. 0.6 while hitstop is active, 1 otherwise -} -``` - -Pass `this.rng` (the seeded RNG) as the `rng` argument so pitch variance stays deterministic under test. - -## Tuning Table - -Map each event to a full feedback stack. Stronger events get more layers and higher magnitudes. - -| Event | Feedback stack | -| -------------- | ------------------------------------------------------------------------------ | -| Pickup | pickup pop + HUD counter punch + pitch-varied chime + `0.15` trauma | -| Player hit | hitstop 70ms + `0.4` trauma + impact flash + rumble (180ms) + HUD pulse | -| Enemy killed | hitstop 40ms + `0.3` trauma + impact flash + pitch-varied boom | -| Boost / dash | FOV punch +6° + stretch (1.15) + whoosh + light rumble | -| Jump / land | stretch on takeoff, squash (0.9) on landing + step audio + `0.2` trauma on land | -| Explosion | hitstop 90ms + `0.7` trauma + white overlay flash + FOV punch +8° + heavy rumble | - -## Anti-Patterns - -- Constant camera shake, or shake with no decay: nauseating and it hides the play field. -- Trauma added without the `trauma²` curve or the hard cap: small events feel violent, stacked events fling the camera. -- Hitstop on every minor event: the game feels laggy instead of weighty. Reserve it for heavy contact. -- Feedback that blocks or delays input: never gate the primary verb behind an animation finishing. -- Effects driven by wall clock or fixed-timestep gameplay delta: they desync from the simulation and break during hitstop or on frame drops. Drive time-based effects from accumulated game time; drive feedback tweens/camera from the real render delta. -- Emissive flash on a material with a black `emissive` color: nothing shows. -- `Math.random` in any gameplay or effect path: it breaks the deterministic test hooks and screenshot baselines. - -## Determinism - -Route **all** randomness — pitch variance, spawn jitter, shake seeds if you seed them — through `createSeededRandom` (see `src/utils/random.ts`), never `Math.random`. Drive time-based effects (shake noise, ambient motion) from accumulated game time passed through `update(delta, elapsed)`, not `performance.now()` or `Date.now()`. This keeps the `seed()` and `setReducedMotion()` test hooks reproducible so visual baselines and bot playtests stay stable. diff --git a/.agents/skills/threejs-gameplay-systems/references/gameplay-workflows.md b/.agents/skills/threejs-gameplay-systems/references/gameplay-workflows.md deleted file mode 100644 index 76bbd4b5f6..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/gameplay-workflows.md +++ /dev/null @@ -1,207 +0,0 @@ -# Gameplay Workflows - -Use this reference for first playable slices, architecture, mechanics, entities, controls, camera, physics, audio hooks, and game-feel iteration. For broad game creation, level/arena/track/wave/hole/puzzle work, encounter design, progression, difficulty, or premium gameplay claims, also load `references/game-design-level-design.md`. - -## First Playable Slice - -The first slice must be playable, not just rendered. - -1. Inspect folder, scripts, dependencies, current renderer, app entrypoint, CSS, assets, and tests. -2. Define the design brief and core loop contract from `references/game-design-level-design.md`. -3. Define the level/encounter plan: first decision, first threat, first reward, escalation, recovery beats, and readability. -4. Implement only the mechanics needed for that loop: - - renderer and scene - - camera and resize - - update/render loop - - input intents - - player entity - - one obstacle/enemy or challenge - - one reward/progress path - - collision/trigger checks - - score/status state - - fail/retry state - - minimal HUD state - - one audio/VFX feedback hook -5. Add diagnostics when possible: - - `window.__THREE_GAME_DIAGNOSTICS__` - - renderer info - - game state snapshot - - input state - - active entity counts -6. Verify build, browser, console/page errors, screenshot, nonblank canvas, and one real input path. - -Reject a slice that cannot be controlled or restarted. Also reject a slice where the level/arena/track/wave/table/puzzle is purely decorative and does not shape the player's decisions. - -## Architecture Boundaries - -Prefer simple modules once the prototype grows beyond one file: - -- `main`: DOM bootstrap, app lifecycle, CSS imports. -- `core`: renderer, loop, resize, input, diagnostics. -- `game`: orchestration, state transitions, update order, scoring/objectives. -- `entities`: player, enemies, pickups, projectiles, obstacles. -- `systems`: camera, collision/physics, spawning, animation, audio, UI bridge, debug. -- `assets`: material libraries, procedural textures, model factories, loaders, disposal. -- `tests`: browser, visual, interaction, mobile, performance smoke checks. - -Keep update order explicit: - -```text -input -> fixed physics if any -> gameplay systems -> animation/VFX -> camera -> UI bridge -> render -``` - -Do not invent abstractions before the mechanics need them. Do extract duplicated entity, input, collision, and asset logic once multiple features share it. - -## Imported Generated 3D Assets And Animation - -When gameplay uses `threejs-3d-generator` GLB/FBX assets: - -- Load GLB assets with `GLTFLoader` from `three/addons/loaders/GLTFLoader.js`. -- Keep imported model loading in the asset layer, not inside entity update loops. -- Wrap imported scenes in game entities with explicit scale, bounds, collision proxy, and state hooks. -- Use `AnimationMixer` for rigged/animated GLBs and update mixers with `deltaSeconds`. -- Map gameplay states to clips: idle, walk/run, jump, attack/slash/shoot, hurt, fall, turn. -- Decide whether root motion is used. For arcade games, prefer in-place animation and move the entity in code. -- Keep simple collision proxies independent from the detailed imported mesh. -- Add fallback placeholders or loading states if an asset fails to load. -- Report file size, clip names, approximate triangles, and texture count after import. - -## Input And Intent - -- Convert keyboard, pointer, touch, and gamepad where relevant into game intents. -- Keep input collection separate from simulation. -- Support both desktop and mobile when the user asks for a browser game unless explicitly desktop-only. -- Handle pointer release/cancel/blur so controls do not stick. -- Keep CSS `touch-action` intentional and scoped. -- Preserve focus and restart controls after fail/pause. - -## Camera And Controls - -Tune controls and camera together. - -- Movement: acceleration, deceleration, friction, turn rate, max speed, jump/gravity/boost. -- Camera: follow lag, look-ahead, FOV, height, distance, shake, collision/framing. -- Readability: next decision visible, player centered enough, threats not hidden by UI. -- Feedback: hit pause, camera impulse, FOV kick, meter pulse, audio pitch, VFX socket. -- Accessibility: avoid excessive shake, strobe, and uncontrollable motion. - -Use `lil-gui` for live constants when repeated tuning is likely, but gate debug UI from release. - -## Collision And Physics - -Choose the lightest reliable approach: - -- Simple custom collision: arcade triggers, lanes, runners, pickups, bullets, simple arenas. -- Rapier: default robust choice for serious browser-game physics: balls, pinball, mini-golf, pool/snooker, moving platforms, sensors, rigid bodies, slopes/ramps, high-speed collisions, many contacts, and WASM-backed simulation. -- `cannon-es`: lightweight JS fallback for small/simple rigid-body scenes when avoiding WASM matters. - -When physics is in scope, also load `references/physics-engine-selection.md` before choosing an engine. - -Rules: - -- Keep collision proxies simple and visible in debug mode. -- Do not use detailed visual meshes for collision. -- Clamp delta or use fixed-step simulation for physics. -- Reconcile physics transforms and visual transforms in one place. -- Test high-speed movement against tunneling and camera loss. -- Report engine choice, package installed, timestep, body count, collider count, CCD use, sensors, and risky colliders. -- For Rapier, initialize WASM once, step with a fixed accumulator, use primitive/compound colliders, enable CCD only for fast bodies, and dispose bodies/colliders on restart. - -## Gameplay Implementation Loop - -For each mechanic: - -1. Add state/data. -2. Add simulation/update. -3. Add visual representation. -4. Add feedback: UI, audio, VFX, camera, animation. -5. Add diagnostics. -6. Verify with real input and one failing edge case. - -Examples: - -- Pickup: spawn data, collision trigger, score/meter state, collect VFX/audio, HUD pulse, respawn/cleanup. -- Hazard: telegraph, movement/update, collision proxy, damage/fail state, hit feedback, restart. -- Combo: timer/state, reward multiplier, UI badge, audio ramp, reset rules. -- Weapon/action: cooldown, projectile/hit, impact feedback, ammo/charge UI, target readability. - -## Game Feel Pass - -Run several short loops and tune one axis at a time: - -- Movement speed and acceleration. -- Camera distance, follow, and look-ahead. -- Reaction windows and obstacle spacing. -- Jump/boost/attack cooldowns. -- Pickup magnetism and reward timing. -- Hit feedback and restart speed. -- Difficulty ramp and pacing. - -Record meaningful constants changed. If the game feels worse after a pass, revert or reduce the last tuning change instead of layering compensating changes. - -## Design And Level Iteration - -When a prototype is technically playable but bland, iterate the design before adding more art: - -- Tighten the player promise and primary verb. -- Add a decision in the first 30 seconds. -- Move hazards/rewards so the player chooses between safety, speed, score, or resource gain. -- Add a learning beat before a punishing combination. -- Add one recovery beat after high pressure. -- Replace random placement with authored pacing rules or seeded patterns. -- Tune the camera to frame the next decision, not only the player object. -- Report what changed in the design brief, level plan, or difficulty curve. - -## Audio Hooks - -Use lightweight Web Audio or project audio utilities: - -- UI click/pause/retry. -- Pickup/score. -- Damage/fail. -- Boost/speed. -- Combo/milestone. -- Ambient loop or procedural drone when appropriate. - -Audio should reflect state, not play random decoration. Respect mute and reduced-motion/accessibility settings when present. - -## Diagnostics - -Expose: - -- FPS/frame time if available. -- Renderer info. -- Current state. -- Player position/velocity. -- Entity counts. -- Active collisions/hits. -- Input intents. -- Tunable constants when using debug GUI. - -Diagnostics should be easy to disable or gate for release. - -## Verification - -Minimum evidence after meaningful gameplay work: - -- `npm run build` or equivalent. -- Local browser run. -- Console/page error check. -- Nonblank canvas pixel check. -- Desktop screenshot. -- Mobile screenshot when in scope. -- Main input path tested. -- Objective progression tested. -- Fail/retry tested when relevant. - -## Common Failures - -- Static scene instead of game. -- Multiple loops fighting. -- Camera clips, points away, or hides the next decision. -- Mechanic cannot be triggered from real input. -- HUD/audio/VFX do not reflect state changes. -- Faster movement breaks collision or camera framing. -- Restart leaves stale entities, timers, listeners, or effects. -- Mobile input works visually but does not emit game intents. -- Imported model loads but has wrong scale, pivot, orientation, animation root motion, or no collision proxy. diff --git a/.agents/skills/threejs-gameplay-systems/references/physics-engine-selection.md b/.agents/skills/threejs-gameplay-systems/references/physics-engine-selection.md deleted file mode 100644 index 8a6b235eaa..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/physics-engine-selection.md +++ /dev/null @@ -1,179 +0,0 @@ -# Physics Engine Selection - -Use this reference before adding or changing physics, collision-heavy gameplay, vehicle movement, ball sports, pinball, mini-golf, rigid-body puzzles, destructible props, character controllers, sensors, or high-speed collision. - -## Current Recommendation - -Default to this ladder: - -1. Custom collision: arcade triggers, pickups, lanes, bullets, simple overlap tests, deterministic rails, or games where authored feel matters more than simulation. -2. Rapier: default robust physics choice for serious Three.js browser games that need rigid bodies, colliders, sensors, many contacts, fast objects, balls, vehicles, ramps, slopes, moving platforms, or reliable browser/mobile behavior. -3. cannon-es: lightweight JavaScript fallback for small rigid-body scenes when avoiding WASM matters and collision complexity is low. -4. Jolt: consider for advanced rigid-body projects that need its engine-specific strengths, but expect more integration complexity. -5. Ammo.js/Bullet: use only when a project already depends on it or needs an existing Ammo-specific feature/wrapper. Avoid as the default new-project choice. -6. Matter.js: 2D only; use only for 2D gameplay rendered with Three.js. - -For most new premium Three.js games with real physics, choose Rapier. - -## Why Rapier Is The Default - -Three.js is a renderer, not a physics engine. Physics uses a separate world updated at a fixed timestep, then visual meshes are synchronized from physics body transforms. - -Rapier is a Rust/WASM physics engine with official JavaScript bindings. It supports 2D and 3D worlds, rigid bodies, colliders, sensors, collision events, forces/impulses, damping, locking axes/rotations, sleeping, and continuous collision detection for fast bodies. It is a good default because it is fast, modern, typed, and strong enough for browser games with meaningful simulation. - -## Choose By Game Type - -Use custom collision: - -- Endless runners, lane dodgers, simple shooters, pickups, checkpoint gates, scripted hazards. -- Transform-driven racers where car feel is custom and barriers are simple. -- Starship dogfights with sphere/box/projectile overlap. - -Use Rapier: - -- Mini golf, pool/snooker, pinball, marble racers, physics puzzles, rolling balls. -- Platformers, moving platforms, ramps, slopes, character controllers. -- Dynamic debris, rigid-body stacks, crates, destructible props. -- High-speed bullets/balls that need CCD. -- Trigger/sensor-heavy games needing collision events. -- Vehicle-like games where wheel simulation is not required but collisions and ramps matter. - -Use cannon-es: - -- Small JS-only demos or prototypes with modest body counts. -- Simple arcade rigid bodies where package simplicity matters more than robustness. - -Use Jolt: - -- Advanced rigid-body experiments where Jolt's behavior is explicitly desired and the team can handle WASM integration details. - -Avoid detailed visual mesh collision: - -- Use primitive colliders, compound colliders, convex hulls, simplified triangle meshes only for fixed level geometry, and explicit sensor volumes. -- Imported generated GLB meshes should get separate collision proxies. - -## Rapier Setup Pattern - -Install: - -```bash -npm install @dimforge/rapier3d-compat -``` - -Initialize once before gameplay starts: - -```ts -import RAPIER from '@dimforge/rapier3d-compat'; - -await RAPIER.init(); - -const gravity = { x: 0, y: -9.81, z: 0 }; -const world = new RAPIER.World(gravity); -``` - -Step at a fixed timestep: - -```ts -const fixedDt = 1 / 60; -let accumulator = 0; - -function update(deltaSeconds: number) { - accumulator += Math.min(deltaSeconds, 0.1); - while (accumulator >= fixedDt) { - world.timestep = fixedDt; - world.step(); - accumulator -= fixedDt; - } -} -``` - -Create bodies and colliders: - -```ts -const bodyDesc = RAPIER.RigidBodyDesc.dynamic() - .setTranslation(0, 2, 0) - .setLinearDamping(0.25) - .setAngularDamping(0.5); - -const body = world.createRigidBody(bodyDesc); -const collider = RAPIER.ColliderDesc.ball(0.5) - .setRestitution(0.6) - .setFriction(0.4); -world.createCollider(collider, body); -``` - -Sync physics to Three.js in one system: - -```ts -const t = body.translation(); -const r = body.rotation(); -mesh.position.set(t.x, t.y, t.z); -mesh.quaternion.set(r.x, r.y, r.z, r.w); -``` - -For high-speed objects: - -```ts -const fastBody = world.createRigidBody( - RAPIER.RigidBodyDesc.dynamic().setCcdEnabled(true) -); -``` - -For sensors/triggers: - -```ts -const sensor = RAPIER.ColliderDesc.ball(1) - .setSensor(true) - .setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS); -``` - -## Architecture Rules - -- Put physics ownership in `systems/PhysicsWorld`, `systems/CollisionSystem`, or equivalent. -- Do not create physics bodies inside render code. -- Keep physics body handles in entities and dispose them on restart. -- Update order: input intents -> fixed physics -> game state/collisions -> VFX/camera/UI -> render. -- Keep a debug overlay or helper mode for colliders, body counts, contact pairs, and velocity. -- Use kinematic bodies for moving platforms and scripted obstacles. -- Use sensors for pickups, goals, holes, portals, checkpoints, triggers, and damage zones. -- Use CCD only for fast bodies because it costs extra. -- Use sleeping and body removal/disposal to avoid stale simulation state. - -## Tuning Rules - -- Tune in units that map cleanly to scene scale. -- Clamp frame delta before the accumulator. -- Tune friction, restitution, damping, mass/density, gravity scale, and collision groups explicitly. -- For balls, mini-golf, pool, and pinball: tune rolling friction/damping, restitution, cushion/boundary bounce, hole capture, and max velocity. -- For arcade vehicles: do not rely on raw rigid-body simulation alone; combine kinematic/control logic with collision response. -- For character controllers: prefer capsule colliders, locked rotations, and kinematic movement unless ragdoll behavior is required. - -## Verification Requirements - -For physics work, verify: - -- Build/typecheck. -- Browser run with console/page error check. -- Real input changes body state. -- Collision/trigger path works. -- Restart removes or resets physics bodies. -- High-speed movement does not tunnel. -- Mobile/low-FPS frame spikes do not break simulation. -- Physics diagnostics: engine used, body count, collider count, timestep, CCD bodies, sensors, collision groups, and risky colliders. - -## Common Failures - -- Variable-delta physics causes nondeterministic feel. -- Visual mesh and physics body drift because transforms are synced in multiple places. -- Bodies persist after restart. -- Detailed imported meshes make collision slow or wrong. -- Fast balls/projectiles tunnel because CCD is missing. -- Sensors are missing active events. -- Kinematic platforms move visually but not physically. -- Debug code exposes physics internals or API keys in release. - -## Source Basis - -- Three.js manual: physics engines run a parallel physics world, often on fixed timesteps, then synchronize mesh transforms. -- Three.js manual: cannon-es is lightweight and easy to integrate, while WASM engines such as Rapier/Jolt/Ammo offer more performance/features with more setup. -- Rapier JavaScript docs: use `@dimforge/rapier3d-compat`, initialize with `RAPIER.init()`, create rigid bodies and colliders, use forces/impulses/damping/CCD, and enable collision events on colliders. diff --git a/.agents/skills/threejs-gameplay-systems/references/prompt-templates.md b/.agents/skills/threejs-gameplay-systems/references/prompt-templates.md deleted file mode 100644 index a839042b3c..0000000000 --- a/.agents/skills/threejs-gameplay-systems/references/prompt-templates.md +++ /dev/null @@ -1,51 +0,0 @@ -# Three.js Gameplay Systems Prompt Templates - -Reusable prompt templates packaged with this skill. Use only templates relevant to the current request, and adapt placeholders to the game/project context. - ---- - -# Gameplay System Prompt - -Use `threejs-gameplay-systems` to add or modify this gameplay system: - -System: -- Player-facing behavior: -- Entities affected: -- State changes: -- Collision/physics needs: -- Audio/visual/HUD feedback: -- Edge cases: - -Constraints: -- Preserve existing controls and camera unless the task asks to change them. -- Keep update order deterministic. -- Use simple custom collision unless the mechanics justify a physics library. -- Add debug controls only when they speed tuning. -- Verify through build, local browser run, console check, screenshot, canvas-pixel check, and interaction test. - ---- - -# Game Design And Level Design Prompt - -Use `threejs-gameplay-systems` to design or improve this game's player-facing loop before implementation: - -Game: -- Target fantasy / player promise: -- Primary verb: -- Desired feeling: -- Genre: -- Target session length: -- Target devices: - -Produce and then implement: -- Compact game design brief. -- Core loop contract: verb -> objective -> pressure -> reward/progression -> fail/retry. -- Level/encounter plan: start, first decision, first threat, first reward, landmarks, escalation, recovery beats, readability. -- Difficulty curve and tuning constants. -- Fun-factor rejection tests. - -Constraints: -- Build a playable loop first. -- Do not treat a static scene as a game. -- Make the level/arena/track/wave/hole/puzzle shape player decisions. -- Verify with real input, active-play screenshot, canvas-pixel check, and fail/retry or setback path when relevant. diff --git a/.agents/skills/threejs-gameplay-systems/scripts/create_threejs_game.py b/.agents/skills/threejs-gameplay-systems/scripts/create_threejs_game.py deleted file mode 100755 index 498864d989..0000000000 --- a/.agents/skills/threejs-gameplay-systems/scripts/create_threejs_game.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python3 -"""Create a Three.js Vite game from the packaged skill scaffold.""" - -from __future__ import annotations - -import argparse -import json -import re -import shutil -import sys -from pathlib import Path - - -EXCLUDE_DIRS = { - "node_modules", - "dist", - "artifacts", - "test-results", - "playwright-report", - "coverage", - "__pycache__", -} -EXCLUDE_FILES = {".DS_Store"} - - -def skill_dir() -> Path: - return Path(__file__).resolve().parents[1] - - -def scaffold_dir() -> Path: - return skill_dir() / "assets" / "threejs-vite-game" - - -def normalized_project_name(target: Path) -> str: - name = re.sub(r"[^a-z0-9._-]+", "-", target.resolve().name.lower()).strip("-") - return name or "threejs-vite-game" - - -def ignore(_directory: str, names: list[str]) -> set[str]: - ignored: set[str] = set() - for name in names: - if name in EXCLUDE_DIRS or name in EXCLUDE_FILES: - ignored.add(name) - return ignored - - -def rewrite_json_name(path: Path, name: str) -> None: - if not path.exists(): - return - data = json.loads(path.read_text(encoding="utf-8")) - data["name"] = name - if isinstance(data.get("packages"), dict) and "" in data["packages"]: - data["packages"][""]["name"] = name - path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") - - -def create_game(target: Path, force: bool) -> None: - source = scaffold_dir() - if not source.is_dir(): - raise SystemExit(f"Scaffold not found: {source}") - - if target.exists() and any(target.iterdir()) and not force: - raise SystemExit(f"Target is not empty: {target}\nUse --force to copy into it anyway.") - - target.mkdir(parents=True, exist_ok=True) - shutil.copytree(source, target, dirs_exist_ok=True, ignore=ignore) - - project_name = normalized_project_name(target) - rewrite_json_name(target / "package.json", project_name) - rewrite_json_name(target / "package-lock.json", project_name) - - print(f"Created Three.js game scaffold at {target.resolve()}") - print(f"Next: cd {target} && npm install && npm run dev") - - -def main(argv: list[str]) -> int: - parser = argparse.ArgumentParser(description="Create a Vite + TypeScript + Three.js browser game scaffold.") - parser.add_argument("target", help="Target directory to create or populate.") - parser.add_argument("--force", action="store_true", help="Copy into a non-empty target directory.") - args = parser.parse_args(argv) - - create_game(Path(args.target), args.force) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main(sys.argv[1:])) diff --git a/.agents/skills/threejs-gltf-loading/SKILL.md b/.agents/skills/threejs-gltf-loading/SKILL.md deleted file mode 100644 index 50aaddacab..0000000000 --- a/.agents/skills/threejs-gltf-loading/SKILL.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -name: threejs-gltf-loading -description: > - Load glTF/GLB models in three.js with GLTFLoader and play their skinned - animations with AnimationMixer, including DRACO/Meshopt-compressed meshes and - KTX2 textures. Use when importing 3D models into three.js — when the user - mentions glTF, GLB, GLTFLoader, AnimationMixer, animation clips, DRACOLoader, or - "load a 3D model". For scene/camera/renderer setup use threejs-scene-setup; for - materials and lights use threejs-materials-lighting. -license: Apache-2.0 -compatibility: three.js r165+ (verified against r184; GLTFLoader from three/addons) -metadata: - engine: threejs - category: web-engines - difficulty: intermediate ---- - -# three.js glTF Loading - -Load `.gltf`/`.glb` models and play their animations in three.js, including -compressed geometry (DRACO/Meshopt) and textures (KTX2). Patterns target -**r165+**, verified against **r184**. - -## When to use - -- Use to import a 3D model, add it to the scene, inspect its node hierarchy, and - play baked/skinned animation clips with an `AnimationMixer`. -- Use when files are `.gltf`/`.glb`, or code imports `GLTFLoader` / - `DRACOLoader` / `KTX2Loader` from `three/addons/loaders/...`. - -**When *not* to use:** creating the renderer/camera/loop → `threejs-scene-setup`. -Tuning surface look, lights, or shadows on the loaded model → -`threejs-materials-lighting`. Authoring/exporting the model itself (Blender) is out -of scope; prefer glTF over OBJ/FBX for runtime. - -## Core workflow - -1. **Why glTF.** It's a transmission format: binary vertex data, PBR materials, and - animations are ready to render with minimal parsing. Prefer it over OBJ (no scene - graph, no animation) and FBX (heavy) for the web. -2. **Load with `GLTFLoader`.** `loader.load(url, onLoad, onProgress, onError)`. The - result `gltf` has `gltf.scene` (the `Object3D` root), `gltf.animations` - (`AnimationClip[]`), `gltf.cameras`, and `gltf.asset`. -3. **Add `gltf.scene` to your scene** and frame it. Inspect the hierarchy with - `traverse` / `getObjectByName` to find the parts you'll control. -4. **Play animations with an `AnimationMixer`.** One mixer per animated root; - `mixer.clipAction(clip).play()`; advance with `mixer.update(delta)` every frame. -5. **Decode compressed assets.** Attach a `DRACOLoader` (and/or `KTX2Loader` + - Meshopt) so DRACO meshes and KTX2 textures load; point the decoders at their - files. -6. **Verify what loaded** — log the scene graph and `gltf.animations`, and confirm - the model is visible (right scale, lit) and the clip actually plays. - -## Patterns - -### 1. Load a model and frame it - -```js -import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; - -const loader = new GLTFLoader(); -loader.load( - 'assets/robot.glb', - (gltf) => { - const root = gltf.scene; - scene.add(root); - // Inspect: gltf.animations is an array of AnimationClip. - console.log('clips:', gltf.animations.map((c) => c.name)); - }, - (event) => console.log(`${(event.loaded / event.total) * 100}% loaded`), - (error) => console.error('glTF load failed:', error) -); -``` - -### 2. Play a skinned animation with AnimationMixer - -```js -import * as THREE from 'three'; -import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; - -let mixer; // declare outside so the loop can see it -const clock = new THREE.Clock(); - -new GLTFLoader().load('assets/character.glb', (gltf) => { - scene.add(gltf.scene); - mixer = new THREE.AnimationMixer(gltf.scene); // one mixer per animated root - const clip = THREE.AnimationClip.findByName(gltf.animations, 'Run') - ?? gltf.animations[0]; - mixer.clipAction(clip).play(); -}); - -renderer.setAnimationLoop(() => { - const dt = clock.getDelta(); - if (mixer) mixer.update(dt); // advance the animation by real seconds - renderer.render(scene, camera); -}); -``` - -### 3. Cross-fade between two clips - -```js -const actions = {}; -mixer = new THREE.AnimationMixer(gltf.scene); -for (const clip of gltf.animations) { - actions[clip.name] = mixer.clipAction(clip); -} -actions['Idle'].play(); - -function transitionTo(name, duration = 0.3) { - const next = actions[name]; - next.reset().play(); - for (const [n, action] of Object.entries(actions)) { - if (n !== name) action.crossFadeTo(next, duration, false); - } -} -``` - -### 4. DRACO-compressed geometry - -```js -import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; -import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js'; - -const draco = new DRACOLoader(); -// Point at the decoder files you ship (or a pinned CDN copy of the same version). -draco.setDecoderPath('https://cdn.jsdelivr.net/npm/three@0.184.0/examples/jsm/libs/draco/'); - -const loader = new GLTFLoader(); -loader.setDRACOLoader(draco); -loader.load('assets/city-draco.glb', (gltf) => scene.add(gltf.scene)); -``` - -### 5. Find and animate a named part - -```js -new GLTFLoader().load('assets/car.glb', (gltf) => { - scene.add(gltf.scene); - const wheels = []; - gltf.scene.traverse((node) => { - if (node.name.startsWith('Wheel')) wheels.push(node); - }); - renderer.setAnimationLoop(() => { - const dt = clock.getDelta(); - for (const w of wheels) w.rotation.x += dt * 4; - renderer.render(scene, camera); - }); -}); -``` - -## Pitfalls - -- **Model loads but is invisible** → it has lit (PBR) materials and the scene has no - light or environment. Add a light or `scene.environment` (see - `threejs-materials-lighting`), and check scale — glTF is in metres, so a 0.01-scaled - asset is tiny. -- **`load` is async** → `gltf` only exists inside the callback; declare `mixer`/refs - outside and assign them in the callback, or use `await loader.loadAsync(url)`. -- **Animation never moves** → you didn't call `mixer.update(delta)` each frame, or you - passed milliseconds instead of seconds (use `clock.getDelta()`), or you forgot - `action.play()`. -- **DRACO/KTX2 model fails** → the decoder/transcoder path is wrong or version- - mismatched. `setDecoderPath`/`setTranscoderPath` must point at files matching your - three.js version. -- **Multiple mixers fighting** → use **one** `AnimationMixer` per animated root and - create all actions from it; don't make a new mixer per clip. -- **Baked-in transforms surprise you** → exporters sometimes bake scale/rotation onto - child nodes. Dump the hierarchy (names + position/rotation/scale) before relying on - a node's local transform; re-export from the source if the rig is unusable. -- **Origins are off** → re-parent a part under a fresh `Object3D` to give it a clean - pivot rather than fighting baked offsets. - -## References - -- For the full decode/transcode setup (DRACO + Meshopt + KTX2 together), `loadAsync` - + a `LoadingManager` progress bar, reusing models with `SkeletonUtils.clone`, and - exporter guidance (apply transforms, one clean root), read - `references/loaders-and-animation.md`. - -## Related skills - -- `threejs-scene-setup` — the renderer, camera, and loop this model renders into. -- `threejs-materials-lighting` — lighting/environment so PBR models look right. -- `fps-shooter` — a 3D genre that composes three.js skills. diff --git a/.agents/skills/threejs-gltf-loading/references/loaders-and-animation.md b/.agents/skills/threejs-gltf-loading/references/loaders-and-animation.md deleted file mode 100644 index 8504a69bad..0000000000 --- a/.agents/skills/threejs-gltf-loading/references/loaders-and-animation.md +++ /dev/null @@ -1,113 +0,0 @@ -# three.js glTF: loaders, compression & animation detail (r150+) - -Depth behind the glTF skill: combining decoders, async loading with progress, -cloning skinned meshes, and exporter hygiene. - -## Compression: DRACO, Meshopt, KTX2 - -A production glTF pipeline often compresses geometry (DRACO or Meshopt) and -textures (KTX2/Basis). Attach the matching loaders to `GLTFLoader`: - -```js -import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; -import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js'; -import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js'; -import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js'; - -const VERSION = '0.184.0'; -const base = `https://cdn.jsdelivr.net/npm/three@${VERSION}/examples/jsm/libs/`; - -const draco = new DRACOLoader().setDecoderPath(`${base}draco/`); -const ktx2 = new KTX2Loader().setTranscoderPath(`${base}basis/`).detectSupport(renderer); - -const loader = new GLTFLoader() - .setDRACOLoader(draco) - .setKTX2Loader(ktx2) - .setMeshoptDecoder(MeshoptDecoder); - -loader.load('assets/scene.glb', (gltf) => scene.add(gltf.scene)); -``` - -Notes: - -- The decoder/transcoder files must match your three.js version. Ship them with - your app or pin a CDN copy to the same version; a mismatch throws at load time. -- `ktx2.detectSupport(renderer)` requires the renderer to exist first. -- Compression shrinks downloads but adds CPU/Worker decode time; measure both. - -## Async loading with a progress bar - -```js -import { LoadingManager } from 'three'; - -const manager = new LoadingManager(); -manager.onProgress = (url, loaded, total) => { - setBarWidth(`${(loaded / total) * 100}%`); -}; -manager.onLoad = () => hideLoadingScreen(); - -const loader = new GLTFLoader(manager); - -// Promise form — clean with async/await and Promise.all for many assets. -const [hero, level] = await Promise.all([ - loader.loadAsync('assets/hero.glb'), - loader.loadAsync('assets/level.glb'), -]); -scene.add(hero.scene, level.scene); -``` - -A `LoadingManager` aggregates progress across every loader that shares it, so one -bar can cover models, textures, and audio. - -## Reusing a model many times - -Adding the same `gltf.scene` to the scene twice does not duplicate it — it moves -it. To place many instances of an animated character, clone with `SkeletonUtils` -so the skinned mesh and its skeleton are cloned correctly (a plain `.clone()` does -not duplicate the skeleton): - -```js -import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js'; - -const base = (await loader.loadAsync('assets/enemy.glb')).scene; -for (let i = 0; i < 10; i++) { - const instance = skeletonClone(base); - instance.position.x = i * 2; - scene.add(instance); - const mixer = new THREE.AnimationMixer(instance); // each clone needs its own mixer - mixer.clipAction(baseClips[0]).play(); - mixers.push(mixer); // update all in the loop -} -``` - -For static (non-skinned) meshes, prefer `InstancedMesh` for thousands of copies — -it draws them in one call. - -## AnimationMixer detail - -- One `AnimationMixer` per animated root object; create every `AnimationAction` - from that mixer (`mixer.clipAction(clip)`). -- `action.play()` starts it; `action.stop()`/`action.reset()` rewind it. -- Looping: `action.setLoop(THREE.LoopRepeat)` (default) or `THREE.LoopOnce` with - `action.clampWhenFinished = true` to hold the final pose. -- `action.timeScale` speeds/slows a clip; `action.weight` blends two playing - clips (e.g. walk↔run by speed). -- Blend transitions with `from.crossFadeTo(to, duration, warp)` or - `to.crossFadeFrom(from, duration, warp)`. -- Listen for completion: `mixer.addEventListener('finished', (e) => {...})`. - -Always advance with real time: `mixer.update(clock.getDelta())` inside the loop. - -## Exporter hygiene (Blender → glTF) - -Most "model looks wrong" issues are authoring problems, not loader bugs: - -- **Apply transforms** before export (Object → Apply → All Transforms) so nodes have - identity position/rotation/scale; otherwise baked offsets fight runtime control. -- **One clean root.** Aim for a single root `Object3D` with no transform and - meaningful child names, so you can re-parent parts to the scene cheaply. -- **Author in metres**, real-world scale. Avoid scaling parents. -- **Name your nodes and clips** — you'll look them up by name (`getObjectByName`, - `AnimationClip.findByName`). -- Prefer `.glb` (single binary file) for the web; it bundles geometry, textures, - and animation into one request. diff --git a/.agents/skills/threejs-materials-lighting/SKILL.md b/.agents/skills/threejs-materials-lighting/SKILL.md deleted file mode 100644 index 44fc962563..0000000000 --- a/.agents/skills/threejs-materials-lighting/SKILL.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -name: threejs-materials-lighting -description: > - Light and shade a three.js scene: choose materials (MeshStandardMaterial PBR vs - unlit MeshBasicMaterial), add ambient/hemisphere/directional/point/spot lights, - turn on shadow maps, and use an environment map (IBL) for realistic reflections. - Use when a three.js model looks black, flat, or wrong — when the user mentions - three.js materials, MeshStandardMaterial, lights, shadows, envMap, or PBR. For - renderer/loop setup use threejs-scene-setup; for loading models use - threejs-gltf-loading. -license: Apache-2.0 -compatibility: three.js r165+ (verified against r184; physically based lighting) -metadata: - engine: threejs - category: web-engines - difficulty: intermediate ---- - -# three.js Materials & Lighting - -Make three.js surfaces look right: pick the correct material, light the scene, -enable shadows, and add image-based lighting. Patterns target **r165+**, verified -against **r184** (lighting is physically based by default since r155). - -## When to use - -- Use when a mesh renders black or flat, when choosing a material, adding lights, - enabling shadows, or setting up environment-map reflections (IBL). -- Use when code constructs `MeshStandardMaterial`, `DirectionalLight`, etc., or sets - `renderer.shadowMap.enabled` or `scene.environment`. - -**When *not* to use:** the renderer/camera/loop → `threejs-scene-setup`. Loading -models (whose PBR materials this complements) → `threejs-gltf-loading`. Custom -GLSL/`ShaderMaterial` is its own topic; for the portable concept see -`shader-programming`. - -## Core workflow - -1. **Pick a material by need.** `MeshStandardMaterial` (PBR: `roughness`, - `metalness`, reacts to lights/IBL) for realism; `MeshPhysicalMaterial` for - clearcoat/transmission; `MeshBasicMaterial` (unlit, ignores lights) for UI/flat; - `MeshNormalMaterial`/`MeshDepthMaterial` for debugging. -2. **Add light, or nothing shows.** Lit materials need a light source and/or - `scene.environment`. Combine a soft fill (`AmbientLight`/`HemisphereLight`) with a - key `DirectionalLight`. -3. **Mind light intensity.** Since r155, lighting is physically based; modern - intensities are higher than old tutorials (a key `DirectionalLight` ≈ 1–3). -4. **Enable shadows in three places.** `renderer.shadowMap.enabled = true`, the - light's `castShadow = true`, and each mesh's `castShadow`/`receiveShadow`. Then - fit the light's shadow camera to the scene. -5. **Use an environment map for grounded reflections.** Assign an equirectangular or - PMREM-processed texture to `scene.environment`; PBR materials pick it up - automatically. -6. **Verify under real lighting** — confirm the surface responds to the key light - (highlights move), shadows land where expected, and reflections look plausible. - -## Patterns - -### 1. PBR material under a 3-light rig - -```js -import * as THREE from 'three'; - -const material = new THREE.MeshStandardMaterial({ - color: 0xcc4444, - roughness: 0.5, // 0 = mirror, 1 = fully matte - metalness: 0.0, // 0 = dielectric (plastic/wood), 1 = metal -}); -const mesh = new THREE.Mesh(new THREE.SphereGeometry(1, 32, 16), material); -scene.add(mesh); - -// Soft sky/ground fill + a directional key light. -scene.add(new THREE.HemisphereLight(0xbbddff, 0x443322, 1.0)); // sky, ground, intensity -const key = new THREE.DirectionalLight(0xffffff, 2.5); -key.position.set(5, 10, 7); -scene.add(key); -``` - -### 2. Unlit material (no light needed) - -```js -// MeshBasicMaterial ignores lights — for flat color, UI, or sprites/labels. -const flat = new THREE.MeshBasicMaterial({ color: 0x44aa88 }); -// A textured color map should be tagged sRGB so colors aren't washed out: -const tex = new THREE.TextureLoader().load('assets/logo.png'); -tex.colorSpace = THREE.SRGBColorSpace; -const logo = new THREE.MeshBasicMaterial({ map: tex, transparent: true }); -``` - -### 3. Shadows (the three required switches + camera fit) - -```js -renderer.shadowMap.enabled = true; -renderer.shadowMap.type = THREE.PCFSoftShadowMap; // softer edges - -const sun = new THREE.DirectionalLight(0xffffff, 3); -sun.position.set(8, 12, 6); -sun.castShadow = true; -sun.shadow.mapSize.set(2048, 2048); // default 512; raise for crisp -// DirectionalLight uses an OrthographicCamera — fit it tightly to the scene: -const cam = sun.shadow.camera; -cam.near = 1; cam.far = 40; -cam.left = -15; cam.right = 15; cam.top = 15; cam.bottom = -15; -scene.add(sun); - -mesh.castShadow = true; -ground.receiveShadow = true; // a plane to catch the shadow -``` - -### 4. PBR textures on a material - -```js -const loader = new THREE.TextureLoader(); -const colorMap = loader.load('assets/brick_color.jpg'); -colorMap.colorSpace = THREE.SRGBColorSpace; // color maps are sRGB -const normalMap = loader.load('assets/brick_normal.jpg'); // data maps stay linear -const roughMap = loader.load('assets/brick_rough.jpg'); - -const brick = new THREE.MeshStandardMaterial({ - map: colorMap, - normalMap, - roughnessMap: roughMap, - metalness: 0, -}); -``` - -### 5. Image-based lighting from an HDR environment - -```js -import { RGBELoader } from 'three/addons/loaders/RGBELoader.js'; - -new RGBELoader().load('assets/studio.hdr', (hdr) => { - hdr.mapping = THREE.EquirectangularReflectionMapping; - scene.environment = hdr; // lights + reflects all PBR materials - scene.background = hdr; // optional: show it as the backdrop -}); -// Optional cinematic tone curve: -renderer.toneMapping = THREE.ACESFilmicToneMapping; -renderer.toneMappingExposure = 1.0; -``` - -## Pitfalls - -- **Mesh is pure black** → a lit material with no light and no `scene.environment`. - Add a light or an environment map; to confirm geometry, temporarily swap to - `MeshBasicMaterial`/`MeshNormalMaterial`. -- **Scene too dark even with lights** → old tutorial intensities. r155+ is physically - based; raise intensities (key light ≈ 2–3) or add an environment map. -- **Shadows don't appear** → you missed one of the three switches - (`renderer.shadowMap.enabled`, `light.castShadow`, mesh `castShadow`/ - `receiveShadow`). -- **Shadows are cut off or blocky** → the `DirectionalLight`'s orthographic - `shadow.camera` frustum is too big/small or doesn't cover the scene; tighten - `left/right/top/bottom/near/far` and raise `shadow.mapSize`. Visualise it with - `new THREE.CameraHelper(light.shadow.camera)`. -- **Shadow acne / peter-panning** → adjust `light.shadow.bias` (small negative) and - `light.shadow.normalBias`. -- **Colors look washed out / too bright** → color (albedo) textures need - `texture.colorSpace = THREE.SRGBColorSpace`; normal/roughness/metalness maps must - stay linear (leave them as `NoColorSpace`). -- **PointLight shadows tank performance** → a point light renders the scene 6 times - (cube map). Prefer one shadow-casting `DirectionalLight`; use cheaper fakes - elsewhere. - -## References - -- For the material cheat-sheet (which `Mesh*Material` for which look), light types - and their parameters/units, transparency vs `alphaTest` ordering, and the - `PMREMGenerator`/`RoomEnvironment` route to IBL without an HDR file, read - `references/materials-lights-table.md`. - -## Related skills - -- `threejs-scene-setup` — renderer, camera, and loop (set `shadowMap`, tone mapping). -- `threejs-gltf-loading` — models arrive with PBR materials this skill tunes. -- `shader-programming` — custom shader effects (engine-agnostic concept). diff --git a/.agents/skills/threejs-materials-lighting/references/materials-lights-table.md b/.agents/skills/threejs-materials-lighting/references/materials-lights-table.md deleted file mode 100644 index 326ccc9456..0000000000 --- a/.agents/skills/threejs-materials-lighting/references/materials-lights-table.md +++ /dev/null @@ -1,93 +0,0 @@ -# three.js materials, lights & IBL reference (r155+) - -Lookup tables and detail behind the materials & lighting skill. - -## Material cheat-sheet - -| Material | Lit? | Use for | Key params | -|----------|:----:|---------|-----------| -| `MeshBasicMaterial` | no | UI, flat color, billboards, debug | `color`, `map`, `wireframe` | -| `MeshStandardMaterial` | yes (PBR) | most realistic surfaces | `roughness`, `metalness`, `map`, `normalMap`, `roughnessMap`, `metalnessMap`, `aoMap`, `emissive` | -| `MeshPhysicalMaterial` | yes (PBR+) | car paint, glass, coatings | adds `clearcoat`, `transmission`, `ior`, `sheen` | -| `MeshPhongMaterial` | yes (legacy) | cheap shiny look, older tutorials | `shininess`, `specular` | -| `MeshLambertMaterial` | yes (legacy) | cheap matte | `color`, `map` | -| `MeshNormalMaterial` | no | debug orientation (no light needed) | — | -| `MeshDepthMaterial` | no | debug depth / custom depth | — | -| `MeshToonMaterial` | yes | cel-shaded look | `gradientMap` | - -Default to `MeshStandardMaterial`. It responds to lights **and** `scene.environment`, -matches glTF's PBR model, and is the safe choice for imported assets. - -### Common PBR intuition - -- `metalness`: 0 for non-metals (plastic, wood, skin), 1 for bare metal. Avoid - in-between values except for transitions (rust, wear). -- `roughness`: 0 = sharp mirror reflection, 1 = fully diffuse. Most real surfaces - sit 0.3–0.8. -- Metals get their color from the albedo (`color`/`map`); dielectrics reflect the - environment near-white. - -## Light types - -| Light | Direction/shape | Casts shadows | Notes | -|-------|-----------------|:-------------:|-------| -| `AmbientLight(color, intensity)` | uniform, everywhere | no | flat fill; no form | -| `HemisphereLight(sky, ground, intensity)` | sky-to-ground gradient | no | great cheap outdoor fill | -| `DirectionalLight(color, intensity)` | parallel rays (sun) | yes (orthographic) | the usual key/shadow light | -| `PointLight(color, intensity, distance, decay)` | omni from a point | yes (6× cost) | bulbs, torches | -| `SpotLight(color, intensity, distance, angle, penumbra, decay)` | cone | yes (perspective) | flashlights, stage | -| `RectAreaLight(color, intensity, w, h)` | soft rectangle | no | softboxes, screens (needs init helper) | - -Since r155 lighting is physically based and the old `physicallyCorrectLights` -toggle was removed. Practical starting intensities: key `DirectionalLight` 2–3, -`HemisphereLight`/`AmbientLight` fill ≈ 0.5–1.5. `PointLight`/`SpotLight` use -inverse-square `decay` (default 2), so they fall off fast — increase intensity or -reduce `decay` if a lamp seems too dim. - -### Shadow camera by light type - -- `DirectionalLight` → `OrthographicCamera`; you set `left/right/top/bottom/near/far`. - Fit it tightly; oversized frustums waste shadow-map resolution. -- `SpotLight` → `PerspectiveCamera`; `fov` follows the spot `angle`, aspect is - automatic. -- `PointLight` → 6 renders (cube faces); only `near`/`far` matter, and it's the - most expensive shadow. - -Tuning knobs: `light.shadow.mapSize` (default 512×512; raise to 1024/2048 for -crisper edges at memory cost), `light.shadow.bias` (small negative to fix acne), -`light.shadow.normalBias`, and `renderer.shadowMap.type` (`BasicShadowMap`, -`PCFShadowMap`, `PCFSoftShadowMap`, `VSMShadowMap`). Visualise the frustum with -`new THREE.CameraHelper(light.shadow.camera)`. - -## Transparency & sorting - -- Set `material.transparent = true` and `material.opacity` for blended transparency; - three.js sorts transparent objects back-to-front, which can still mis-order - intersecting geometry. -- For binary cutouts (foliage, chain-link), prefer `material.alphaTest = 0.5` with - `transparent = false` — it writes depth and avoids sort artifacts. -- `material.side` = `FrontSide` (default), `BackSide` (interiors/skyboxes), or - `DoubleSide` (planes, leaves). -- `depthWrite = false` on overlapping additive/transparent effects (particles) so - they don't occlude each other. - -## IBL without an HDR file: PMREM + RoomEnvironment - -When you don't have an `.hdr`, generate a neutral studio environment procedurally: - -```js -import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; - -const pmrem = new THREE.PMREMGenerator(renderer); -scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; -// dispose pmrem when done if you only need it once: pmrem.dispose(); -``` - -`PMREMGenerator` pre-filters any environment (HDR, RoomEnvironment, or a rendered -scene) into the mip-mapped format PBR materials sample for reflections at varying -roughness. Assigning the result to `scene.environment` lights every -`MeshStandardMaterial`/`MeshPhysicalMaterial` without adding explicit lights. - -Pair IBL with tone mapping for a filmic result: -`renderer.toneMapping = THREE.ACESFilmicToneMapping` and adjust -`renderer.toneMappingExposure`. diff --git a/.agents/skills/threejs-scene-setup/SKILL.md b/.agents/skills/threejs-scene-setup/SKILL.md deleted file mode 100644 index 17255e9913..0000000000 --- a/.agents/skills/threejs-scene-setup/SKILL.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -name: threejs-scene-setup -description: > - Stand up a three.js scene: import maps and the three/addons path, the - Scene/PerspectiveCamera/WebGLRenderer trio, the setAnimationLoop render loop, - responsive resize, and OrbitControls. Use when starting or debugging a three.js - app — when the user mentions three.js, THREE.Scene, WebGLRenderer, - PerspectiveCamera, the render loop, resizing, or OrbitControls. For models use - threejs-gltf-loading; for materials/lights use threejs-materials-lighting. -license: Apache-2.0 -compatibility: three.js r165+ (verified against r184; ES modules + import maps) -metadata: - engine: threejs - category: web-engines - difficulty: beginner ---- - -# three.js Scene Setup - -Create the foundation of a three.js app: module loading, the -scene/camera/renderer trio, the render loop, responsive resizing, and camera -controls. Patterns target **r165+** and are verified against **r184**. - -## When to use - -- Use when bootstrapping a three.js scene, fixing a blank/black canvas, making the - canvas responsive, setting up the animation loop, or adding `OrbitControls`. -- Use when `package.json` depends on `three` and code does `import * as THREE from - 'three'`. - -**When *not* to use:** loading `.gltf`/`.glb` models or skinned animation → -`threejs-gltf-loading`. Materials, lights, shadows, environment maps → -`threejs-materials-lighting`. 2D rendering → `pixijs-rendering`. - -## Core workflow - -1. **Load three.js as an ES module with an import map.** Since r147 the bare - specifier `'three'` and `'three/addons/'` must be mapped (in HTML or by a - bundler). Addons (controls, loaders) live under `three/addons/...`. -2. **Create the trio.** A `Scene` (root of the graph), a `PerspectiveCamera(fov, - aspect, near, far)` moved back from the origin, and a `WebGLRenderer` whose - `domElement` is in the DOM. Set size and `pixelRatio`. -3. **Add a mesh.** `new Mesh(geometry, material)` and `scene.add(mesh)`. With a - lit material you also need a light (see `threejs-materials-lighting`). -4. **Drive a render loop with `renderer.setAnimationLoop(fn)`.** It's the modern, - WebXR-/WebGPU-safe replacement for hand-rolled `requestAnimationFrame`. Use a - `Clock` for delta time. -5. **Handle resize** so the camera aspect and renderer match the canvas; update - `camera.aspect`, call `updateProjectionMatrix()`, and `renderer.setSize(...)`. -6. **Add `OrbitControls`** for orbit/pan/zoom while developing. Confirm something - actually renders (a lit cube, the controls responding) before assuming success. - -## Patterns - -### 1. HTML import map + module entry (no bundler) - -```html - - - -``` - -With a bundler (Vite/webpack), skip the import map and just -`npm i three`; the same `import` statements resolve. - -### 2. Scene + camera + renderer - -```js -// main.js -import * as THREE from 'three'; - -const canvas = document.querySelector('#c'); -const renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); -renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // cap for perf -renderer.setSize(window.innerWidth, window.innerHeight); - -const scene = new THREE.Scene(); -scene.background = new THREE.Color(0x101018); - -const camera = new THREE.PerspectiveCamera( - 60, // vertical field of view (degrees) - window.innerWidth / window.innerHeight, // aspect - 0.1, // near - 100 // far -); -camera.position.set(3, 2, 5); -camera.lookAt(0, 0, 0); - -const cube = new THREE.Mesh( - new THREE.BoxGeometry(1, 1, 1), - new THREE.MeshNormalMaterial() // unlit; shows orientation without a light -); -scene.add(cube); -``` - -### 3. The render loop (setAnimationLoop + Clock) - -```js -const clock = new THREE.Clock(); - -renderer.setAnimationLoop(() => { - const dt = clock.getDelta(); // seconds since last frame - cube.rotation.x += dt; // frame-rate independent - cube.rotation.y += dt * 0.7; - renderer.render(scene, camera); -}); -// renderer.setAnimationLoop(null); // stop the loop -``` - -### 4. Responsive resize - -```js -function onResize() { - const w = window.innerWidth, h = window.innerHeight; - camera.aspect = w / h; - camera.updateProjectionMatrix(); // required after changing aspect - renderer.setSize(w, h); -} -window.addEventListener('resize', onResize); -``` - -### 5. OrbitControls (orbit / pan / zoom) - -```js -import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; - -const controls = new OrbitControls(camera, renderer.domElement); -controls.enableDamping = true; // inertial feel -controls.target.set(0, 0, 0); - -renderer.setAnimationLoop(() => { - controls.update(); // needed every frame when damping is on - renderer.render(scene, camera); -}); -``` - -## Pitfalls - -- **`Failed to resolve module specifier "three"`** → missing import map (or bundler - config). Map both `"three"` and `"three/addons/"`; addon paths must end with `/`. -- **Black canvas, no errors** → camera is at the origin (inside/behind the object), - or you used a lit material (`MeshStandardMaterial`) with no light. Move the camera - back; use `MeshNormalMaterial`/`MeshBasicMaterial` to verify geometry first. -- **Nothing animates** → you never called `renderer.render` inside the loop, or you - call `setAnimationLoop` but render outside it. -- **Stretched / squashed view on resize** → you resized the renderer but didn't - update `camera.aspect` + `updateProjectionMatrix()`. -- **Blurry or jagged on HiDPI** → set `renderer.setPixelRatio(...)`; cap it (≈2) so - 4K/retina screens don't tank performance. -- **OrbitControls feel dead** → with `enableDamping = true` you must call - `controls.update()` every frame. -- **Old tutorials use `