77 game-dev skills for AI coding agents — Godot, Unity, Unreal, Phaser, PixiJS, three.js, Bevy, pygame, LÖVE, Roblox. Portable SKILL.md Agent Skills (the format Anthropic launched as Claude Skills), with a router that loads the right skill for your engine and task. Runs in Claude Code, Cursor, Kiro, Codex, Copilot, Gemini CLI and more.
Python agent-skillsai-agentsantigravityawesome-listclaude-codeclinecodexcursorgame-devgame-developmentgamedevgemini-cligithub-copilotgodotkirooh-my-piskillsunityunrealwindsurf
feat(web-engines): add Phaser 3, PixiJS v8, and three.js skills
AbhishekBarali15c96c31e0618
diff --git a/skills/web-engines/phaser-arcade-physics/SKILL.md b/skills/web-engines/phaser-arcade-physics/SKILL.mdnew file mode 100644index 0000000..7d85412--- /dev/null+++ b/skills/web-engines/phaser-arcade-physics/SKILL.md@@ -0,0 +1,180 @@+---+name: phaser-arcade-physics+description: >+ Use Phaser 3 Arcade Physics: enable the world, give sprites bodies, set+ velocity/acceleration/gravity, and resolve collisions with colliders, overlaps,+ groups, and world bounds. Use when a Phaser game needs movement or collisions —+ when the user mentions Arcade Physics, this.physics, setVelocity, collider,+ overlap, gravity, onFloor, or a platformer/top-down controller. For game config,+ scenes, and the loader use phaser-core.+license: Apache-2.0+compatibility: Phaser 3.90 (Arcade Physics; JavaScript/TypeScript)+metadata:+ engine: phaser+ category: web-engines+ difficulty: intermediate+---++# Phaser 3 Arcade Physics++Add movement and collision to a Phaser 3 game with the lightweight **Arcade+Physics** engine (AABB rectangles and circles only). Targets **Phaser 3.90**.++## When to use++- Use for top-down or platformer movement, velocity/acceleration/gravity, bouncing,+ world bounds, and collision/overlap resolution between sprites, groups, and tiles.+- Use when the scene enables `physics: { default: 'arcade' }` and code calls+ `this.physics.add.*`, `body.setVelocity`, or `this.physics.add.collider`.++**When *not* to use:** the `Game` config, scene structure, asset loading, or+cameras → use `phaser-core`. Hinges, springs, complex polygons, or stacking+rigid bodies → use Matter physics (a different engine; Arcade and Matter bodies+do not interact). For engine-agnostic feel tuning see `physics-tuning`.++## Core workflow++1. **Enable the world.** Set `physics: { default: 'arcade', arcade: { gravity:+ {...}, debug: true } }` in the game or scene config. Turn `debug` on while+ building to see body outlines and velocity vectors.+2. **Give a sprite a body.** Create it with `this.physics.add.sprite(...)` (dynamic)+ or `this.physics.add.staticImage(...)` (static), or attach to an existing object+ with `this.physics.add.existing(obj)`.+3. **Drive it through the body, not by setting `x`/`y`.** Use `setVelocity`,+ `setAcceleration`, gravity, `setBounce`, and `setCollideWorldBounds`. The engine+ integrates position from velocity each step (already frame-rate independent).+4. **Resolve interactions.** `this.physics.add.collider(a, b)` separates bodies;+ `this.physics.add.overlap(a, b, cb)` detects without separating (pickups,+ triggers). Pass a callback to react.+5. **Group many objects.** Use `this.physics.add.group()` (dynamic) or+ `staticGroup()` (platforms) so one collider call handles all members.+6. **Check ground contact** with `body.onFloor()` / `body.blocked.down` before+ jumping. Run with `debug: true` and confirm bodies, contacts, and bounds.++## Patterns++### 1. Enable Arcade Physics (game config)++```js+const config = {+ type: Phaser.AUTO,+ width: 800, height: 600,+ physics: {+ default: 'arcade',+ arcade: {+ gravity: { x: 0, y: 600 }, // top-down? use { x: 0, y: 0 }+ debug: false // true to draw bodies + velocity while building+ }+ },+ scene: [PlayScene]+};+new Phaser.Game(config);+```++### 2. Top-down movement (velocity from input)++```js+create() {+ this.player = this.physics.add.sprite(400, 300, 'player');+ this.player.setCollideWorldBounds(true);+ this.cursors = this.input.keyboard.createCursorKeys();+}++update() {+ const speed = 220;+ const body = this.player.body;+ body.setVelocity(0); // reset each frame+ if (this.cursors.left.isDown) body.setVelocityX(-speed);+ if (this.cursors.right.isDown) body.setVelocityX(speed);+ if (this.cursors.up.isDown) body.setVelocityY(-speed);+ if (this.cursors.down.isDown) body.setVelocityY(speed);+ body.velocity.normalize().scale(speed); // keep diagonals same speed+}+```++### 3. Platformer jump (gravity + ground check)++```js+create() {+ this.player = this.physics.add.sprite(100, 450, 'player');+ this.player.setCollideWorldBounds(true);++ // Static platforms: one body each, never moved by collisions.+ this.platforms = this.physics.add.staticGroup();+ this.platforms.create(400, 568, 'ground');+ this.physics.add.collider(this.player, this.platforms);++ this.cursors = this.input.keyboard.createCursorKeys();+}++update() {+ const onGround = this.player.body.blocked.down; // or this.player.body.onFloor()+ if (this.cursors.left.isDown) this.player.setVelocityX(-160);+ else if (this.cursors.right.isDown) this.player.setVelocityX(160);+ else this.player.setVelocityX(0);++ if (this.cursors.up.isDown && onGround) this.player.setVelocityY(-450);+}+```++### 4. Colliders vs overlaps (separate vs detect)++```js+// Push apart and react: player vs enemies.+this.physics.add.collider(this.player, this.enemies, (player, enemy) => {+ this.handleHit(player, enemy);+});++// Detect without pushing: collect coins. The 4th arg is an optional+// process callback returning a boolean to filter pairs before the main callback.+this.physics.add.overlap(this.player, this.coins, (player, coin) => {+ coin.disableBody(true, true); // deactivate + hide+ this.registry.inc('score', 10);+});+```++### 5. A group of moving objects++```js+this.bullets = this.physics.add.group({+ defaultKey: 'bullet',+ maxSize: 30 // pool size; reuse instead of allocating+});++fire(x, y) {+ const bullet = this.bullets.get(x, y); // reuses a dead bullet if available+ if (!bullet) return;+ bullet.enableBody(true, x, y, true, true);+ bullet.setVelocityY(-500);+}+```++## Pitfalls++- **Sprite ignores physics** → it was added with `this.add.sprite` instead of+ `this.physics.add.sprite` (or `this.physics.add.existing(obj)`), so it has no body.+- **Setting `sprite.x` directly fights the engine** → move dynamic bodies with+ `setVelocity`/`setAcceleration`. Direct position writes can tunnel through colliders.+- **Diagonal movement is faster** → independent X and Y velocities add up; normalise+ the velocity vector and rescale to the intended speed.+- **Platforms get pushed by the player** → use a `staticGroup`, or set+ `body.setImmovable(true)` on a dynamic platform.+- **`onFloor()` is always false** → the body needs something to collide with; add the+ `collider` against the ground/platforms before checking, and ensure gravity is on.+- **Moved a static body but collisions are stale** → static bodies don't auto-sync;+ call `body.updateFromGameObject()` (or `refreshBody()` on the game object).+- **Collider added every frame** → register `collider`/`overlap` once in `create`,+ not in `update`.++## References++- For body anatomy and tuning (drag, bounce, max velocity, custom `setSize`/+ `setCircle`/`setOffset` hitboxes, collision categories/masks, and `worldbounds`+ events), read `references/bodies-and-collision.md`.++## Related skills++- `phaser-core` — game config, scenes, loader, cameras (the prerequisite setup).+- `physics-tuning` — engine-agnostic feel (fixed timestep, tunneling, jitter).+- `platformer` / `tower-defense` — genres that compose this skill.+- `level-design` — laying out tile/platform geometry these bodies collide with.diff --git a/skills/web-engines/phaser-arcade-physics/references/bodies-and-collision.md b/skills/web-engines/phaser-arcade-physics/references/bodies-and-collision.mdnew file mode 100644index 0000000..bc58df7--- /dev/null+++ b/skills/web-engines/phaser-arcade-physics/references/bodies-and-collision.md@@ -0,0 +1,123 @@+# Arcade body anatomy & collision detail (Phaser 3.90)++Depth on the Arcade `Body` and the collision system. The `SKILL.md` covers the+common path; reach for this when tuning feel, shaping hitboxes, or filtering+collisions.++## Dynamic vs static bodies++- **Dynamic** (`this.physics.add.sprite`, `image`, `group`): moved by velocity,+ acceleration, drag, and gravity; pushed by collisions.+- **Static** (`staticImage`, `staticSprite`, `staticGroup`): never moves, never+ pushed. Cheaper. Use for ground, walls, platforms. After moving its parent game+ object, call `body.updateFromGameObject()` (or `gameObject.refreshBody()`) so the+ body re-syncs — static bodies do **not** track their parent automatically.++Make a dynamic body behave like a wall with `body.setImmovable(true)`; it still+exists in the simulation but won't be displaced by collisions.++## Movement properties++| Property | Setter | Notes |+|----------|--------|-------|+| velocity | `setVelocity(x, y)` / `setVelocityX/Y` | pixels per second |+| acceleration | `setAcceleration(x, y)` | pixels/sec²; accumulates into velocity |+| gravity | `setGravity(x, y)` | added on top of world gravity |+| drag | `setDrag(x, y)` | velocity lost per second (or per-frame if `useDamping`) |+| max velocity | `setMaxVelocity(x, y)` | clamp speed |+| bounce | `setBounce(x, y)` | 0 = stop on hit, 1 = full rebound |+| friction | `setFriction(x, y)` | share of motion passed to a riding body |++`body.stop()` zeroes velocity, acceleration, and speed in one call.+`body.reset(x, y)` teleports the body and clears motion.++Total gravity on a body = `world.gravity + body.gravity`. Disable world gravity+for a single body with `body.setAllowGravity(false)` (useful for flying enemies).++## Custom hitboxes++The body defaults to the sprite's frame size. Tighten it to the art:++```js+sprite.body.setSize(20, 36, true); // width, height, center on the frame+sprite.body.setOffset(6, 4); // nudge the box within the frame+sprite.body.setCircle(16); // circular body of radius 16+```++`setSize`'s third argument re-centers the body; pass `false` to keep the offset at+`(0, 0)` and position it yourself with `setOffset`.++## Colliders, overlaps, and callbacks++```js+const collider = this.physics.add.collider(+ objectsA, objectsB,+ collideCallback, // (objA, objB) => {} runs after separation+ processCallback, // (objA, objB) => boolean return false to skip this pair+ this // callback context+);++collider.active = false; // temporarily disable+this.physics.world.removeCollider(collider); // remove entirely+```++`overlap(...)` has the same signature but never separates the bodies — use it for+pickups, hurt-boxes, and triggers. A `processCallback` that returns `false`+discards the pair before the main callback (e.g. ignore collisions with allied+units).++`objectsA`/`objectsB` may each be a single game object, an array, or a physics+group, so one call can wire up "all bullets vs all enemies".++## Contact state++After the physics step, each body exposes which sides are touching:++```js+body.blocked.down // touching a tile or world boundary below+body.touching.left // touching another body on the left this step+body.onFloor() // shorthand for blocked.down+body.onWall() // blocked.left || blocked.right+body.wasTouching // touching state from the previous step (edge detection)+```++`blocked` is contact with the world bounds or tiles; `touching` is contact with+another body. Compare `touching` against `wasTouching` to detect the first frame+of a hit (e.g. play a sound once on landing).++## World bounds++```js+this.physics.world.setBounds(0, 0, 1600, 1200); // simulation bounds+body.setCollideWorldBounds(true); // clamp this body+body.onWorldBounds = true; // emit events at edges+this.physics.world.on('worldbounds', (b, up, down, left, right) => { /* ... */ });+```++## Collision categories & masks++By default every body collides with every other. To control which bodies interact,+use a bitmask (each category a unique power of two):++```js+const PLAYER = 1 << 0, ENEMY = 1 << 1, PICKUP = 1 << 2;+player.body.setCollisionCategory(PLAYER);+player.body.setCollidesWith([ENEMY, PICKUP]); // ignore other players+enemy.body.setCollisionCategory(ENEMY);+enemy.body.setCollidesWith([PLAYER]);+```++Call `body.resetCollisionCategory()` to return a body to the default+"collides with everything" behaviour.++## Debugging++While building, enable `arcade.debug: true` to render body rectangles, static-body+outlines, and velocity vectors. Per-body overrides:++```js+this.physics.world.defaults.debugShowVelocity = true;+gameObject.setDebug(true, true, 0x00ff00); // showBody, showVelocity, color+```++Turn debug off for release builds; the overlay has a real per-frame cost.diff --git a/skills/web-engines/phaser-core/SKILL.md b/skills/web-engines/phaser-core/SKILL.mdnew file mode 100644index 0000000..31239c9--- /dev/null+++ b/skills/web-engines/phaser-core/SKILL.md@@ -0,0 +1,175 @@+---+name: phaser-core+description: >+ Set up and debug a Phaser 3 game: the Game config, the Scene lifecycle+ (init/preload/create/update), the asset loader, cameras, and cross-scene+ communication. Use when building or debugging a Phaser 3 game — when the user+ mentions Phaser, Phaser.Game, Phaser.Scene, preload/create/update, this.load,+ this.add, or scene transitions. For Arcade Physics movement/collisions use+ phaser-arcade-physics.+license: Apache-2.0+compatibility: Phaser 3.90 (JavaScript/TypeScript, ES modules or script tag)+metadata:+ engine: phaser+ category: web-engines+ difficulty: beginner+---++# Phaser 3 Core++Set up the foundation of a Phaser 3 game: the `Game` config, the `Scene`+lifecycle, asset loading, cameras, and passing data between scenes. Targets+**Phaser 3.90**.++## When to use++- Use when starting a Phaser 3 game, wiring the `Phaser.Game` config, structuring+ `Scene`s, loading assets in `preload`, or fixing scene transitions and shared+ state.+- Use when the project has `phaser` in `package.json` or `import Phaser from 'phaser'`,+ and code uses `preload()`/`create()`/`update()`.++**When *not* to use:** movement, velocity, colliders, gravity, or overlap → use+`phaser-arcade-physics`. Complex rigid-body simulation uses Matter physics (a+separate concern). For cross-engine save/load patterns use `save-systems`.++## Core workflow++1. **Create the game from a config.** `new Phaser.Game(config)` with `type:+ Phaser.AUTO` (WebGL with Canvas fallback), a `width`/`height`, and a `scene`+ array. The first scene (and any with `active: true`) starts automatically.+2. **Model each screen as a `Scene`.** Subclass `Phaser.Scene`, pass a unique+ `key` to `super`, and implement the lifecycle: `init(data)` → `preload()` →+ `create(data)` → `update(time, delta)`.+3. **Load assets in `preload`, use them in `create`.** Queued assets are not+ available until `create`. The loader is per-scene; the cache it fills is global.+4. **Reset per-run state in `init()`, not the constructor.** A scene instance is+ reused across restarts, so constructor-set fields keep stale values.+5. **Move between screens** with `this.scene.start/launch/switch/sleep/wake`.+ Share data through `this.registry` (global) or a sibling scene's event emitter.+6. **Run and observe.** Serve the page, open it, and confirm assets load (watch the+ Network tab and console) and scenes switch as expected before assuming success.++## Patterns++### 1. Game config + boot (ES module)++```js+// main.js — one Game owns the renderer, loop, cache, and Scene Manager.+import Phaser from 'phaser';+import BootScene from './scenes/BootScene.js';+import PlayScene from './scenes/PlayScene.js';++const config = {+ type: Phaser.AUTO, // WebGL if available, else Canvas+ width: 800,+ height: 600,+ backgroundColor: '#1d1d28',+ scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },+ scene: [BootScene, PlayScene] // BootScene starts first+};++new Phaser.Game(config);+```++### 2. A Scene with the full lifecycle++```js+// scenes/PlayScene.js+import Phaser from 'phaser';++export default class PlayScene extends Phaser.Scene {+ constructor() {+ super('play'); // unique scene key+ }++ init(data) {+ // Reset run-specific state HERE so restarts start clean.+ this.score = 0;+ this.level = data.level ?? 1;+ }++ preload() {+ // Queue downloads. Not usable until create().+ this.load.image('player', 'assets/player.png');+ this.load.spritesheet('coin', 'assets/coin.png', { frameWidth: 16, frameHeight: 16 });+ }++ create() {+ this.player = this.add.sprite(400, 300, 'player');+ this.scoreText = this.add.text(10, 10, 'Score: 0', { fontSize: '20px', color: '#fff' });+ this.cursors = this.input.keyboard.createCursorKeys();+ }++ update(time, delta) {+ // delta is milliseconds since last frame; divide by 1000 for seconds.+ const speed = 200 * (delta / 1000);+ if (this.cursors.left.isDown) this.player.x -= speed;+ if (this.cursors.right.isDown) this.player.x += speed;+ }+}+```++### 3. Cross-scene data + events++```js+// The registry is a global DataManager shared by every scene.+this.registry.set('coins', 0); // in any scene+const coins = this.registry.get('coins'); // read anywhere++// React to registry changes (e.g. a HUD scene listening to gameplay):+this.registry.events.on('changedata-coins', (parent, value) => {+ this.coinText.setText(`Coins: ${value}`);+});++// Talk directly to another running scene via its event emitter:+const ui = this.scene.get('hud');+ui.events.emit('show-message', 'Level cleared!');+```++### 4. Scene transitions (pick the right verb)++```js+this.scene.start('gameover', { score: this.score }); // stop this scene, start target+this.scene.launch('hud'); // run a second scene in parallel (overlay HUD)+this.scene.switch('menu'); // sleep this scene, start/wake target+this.scene.pause(); // freeze updates but keep rendering (modal)+this.scene.sleep(); // stop updating AND rendering, keep state for wake+```++### 5. A camera that follows the player++```js+this.cameras.main.setBounds(0, 0, 1600, 1200); // world size+this.cameras.main.startFollow(this.player, true, 0.1, 0.1); // smooth lerp follow+this.cameras.main.setZoom(1.5);+```++## Pitfalls++- **Assets are `undefined` in `create`/`update`** → you forgot to queue them in+ `preload`, or used the wrong key. The loader runs between `preload` and `create`.+- **State leaks across a restart** → you set fields in the constructor. The Scene+ instance is reused; reset run state in `init()` and clear arrays on `shutdown`.+- **`this.scene.start` vs `this.scene.launch`** → `start` stops the calling scene;+ `launch` runs the target alongside it. Using `start` for a HUD hides the game.+- **`this` is wrong in a callback** → arrow functions keep the Scene's `this`; plain+ `function` callbacks need a context argument or `.bind(this)`.+- **Phaser 2 tutorials don't work** → "States" were renamed to "Scenes" in Phaser 3,+ and each Scene owns its own systems (input, cameras, tweens) rather than a global+ Game World.+- **Nothing renders / black screen** → confirm the canvas mounted, `width`/`height`+ are set, and a scene actually started (check `game.scene.dump()` output).++## References++- For the full scene state machine (pause/resume vs sleep/wake vs stop/start, the+ restart-state bug, and removing/replacing scenes), read+ `references/scene-flow.md`.++## Related skills++- `phaser-arcade-physics` — velocity, gravity, colliders, overlap, and groups.+- `input-systems` — rebindable, multi-device input architecture (engine-agnostic).+- `pixijs-rendering` / `threejs-scene-setup` — other browser rendering stacks.+- `platformer` / `puzzle` — genre templates that compose Phaser skills.diff --git a/skills/web-engines/phaser-core/references/scene-flow.md b/skills/web-engines/phaser-core/references/scene-flow.mdnew file mode 100644index 0000000..f90fbd3--- /dev/null+++ b/skills/web-engines/phaser-core/references/scene-flow.md@@ -0,0 +1,108 @@+# Phaser 3 scene flow (Phaser 3.90)++The Scene Manager runs every scene through a small state machine. Knowing which+transition verb does what prevents the most common Phaser bugs: hidden scenes,+stale state after a restart, and duplicate event listeners.++## Lifecycle order++A scene is **booted once** (status `INIT`) and can be **started any number of+times**. On each start it runs:++```+start → (loading, if preload queued anything) → create → running+```++- `init(data)` — runs first on every start. **Reset run-specific state here.**+- `preload()` — queue asset downloads. Optional.+- `create(data)` — build game objects; assets queued in `preload` are now ready.+- `update(time, delta)` — called every frame while the scene is `running`.++The same `data` object is passed to `init` and `create`, coming from+`scene.start(key, data)` / `scene.launch(key, data)`.++## Transition verbs++| Method | Effect on target | Effect on caller |+|--------|------------------|------------------|+| `start(key, data)` | start (or restart) | **stop** the caller |+| `launch(key, data)` | start in parallel | caller keeps running |+| `switch(key)` | start or wake | **sleep** the caller |+| `pause(key?)` | stop updating, keep rendering | — |+| `resume(key?)` | resume updating | — |+| `sleep(key?)` | stop updating AND rendering, keep state | — |+| `wake(key?)` | resume a sleeping scene | — |+| `stop(key?)` | shutdown (frees objects) | — |++Rules of thumb:++- **HUD/overlay** → `launch` it once; it renders on top because later scenes draw+ later. Toggle with `setVisible()` or `sleep`/`wake`, not `start`.+- **Modal pause menu** → `pause` the gameplay scene and `launch` the menu; `resume`+ on close.+- **Title ⇄ gameplay you revisit** → prefer `sleep`/`wake` (state preserved, starts+ only once) over `stop`/`start` (fresh each time) when re-initialisation is costly.++## The restart-state bug++A Scene is a long-lived instance. Fields set in the constructor are set **once**,+so they keep their last value after a restart:++```js+// WRONG — gameOver stays true forever after the first game over.+export default class Play extends Phaser.Scene {+ constructor() {+ super('play');+ this.gameOver = false; // runs once, never again+ }+}++// RIGHT — init() runs on every (re)start.+export default class Play extends Phaser.Scene {+ constructor() { super('play'); }+ init() { this.gameOver = false; }+}+```++The same applies to module-level arrays that collect game objects: clear them on+`shutdown`, or they will hold destroyed objects from the previous run.++```js+create() {+ this.enemies = [];+ // Clean up when the scene stops so the next run starts empty.+ this.events.once('shutdown', () => { this.enemies.length = 0; });+}+```++## Duplicate listeners++Listeners added in `create` on a **global** emitter (the registry, the input+manager, another scene) survive scene restarts and stack up. Either:++- add them with `.once(...)`, or+- remove them on `shutdown`:++```js+create() {+ const onChange = (p, v) => this.refresh(v);+ this.registry.events.on('changedata-coins', onChange);+ this.events.once('shutdown', () => {+ this.registry.events.off('changedata-coins', onChange);+ });+}+```++## Removing or replacing a scene++You cannot reuse a scene key until the original is destroyed. To swap an instance+under the same key, remove it after it finishes shutting down:++```js+this.scene.remove('level'); // remove by key+// then later+this.scene.add('level', NewLevelScene, true); // true = autostart+```++A handy alternative to juggling keys is to store the active level key in the+registry and add/remove by that value.diff --git a/skills/web-engines/pixijs-rendering/SKILL.md b/skills/web-engines/pixijs-rendering/SKILL.mdnew file mode 100644index 0000000..013b58e--- /dev/null+++ b/skills/web-engines/pixijs-rendering/SKILL.md@@ -0,0 +1,186 @@+---+name: pixijs-rendering+description: >+ Build a PixiJS v8 render layer: create the async Application, load textures with+ Assets, compose the scene graph with Container and Sprite, drive the ticker loop,+ wire pointer events, and group draws with render groups. Use when building or+ debugging PixiJS v8 — when the user mentions PixiJS, Pixi, Application, app.stage,+ Container, Sprite, Assets.load, app.ticker, or eventMode. Pins the v8 async+ init() API.+license: Apache-2.0+compatibility: PixiJS v8 (npm pixi.js@8; Node 20+; WebGL/WebGPU)+metadata:+ engine: pixijs+ category: web-engines+ difficulty: intermediate+---++# PixiJS v8 Rendering++Set up and structure a PixiJS **v8** application: the async `Application`, asset+loading via `Assets`, the `Container`/`Sprite` scene graph, the ticker loop,+pointer events, and render groups. Pins the v8 API (async `init`, unified+`Assets`, `eventMode`).++## When to use++- Use when starting a PixiJS v8 project, fixing a blank canvas, structuring the+ display list, loading textures, animating via the ticker, or handling pointer+ input.+- Use when `package.json` depends on `pixi.js` (v8) and code does+ `import { Application } from 'pixi.js'`.++**When *not* to use:** Phaser's scene/loader model → `phaser-core`. 3D scenes →+`threejs-scene-setup`. PixiJS v7-and-earlier code (synchronous `new+Application({...})`, `Loader`, `interactive = true`) needs the v8 migration first;+this skill targets v8 only.++## Core workflow++1. **Create and `await` the Application.** In v8, `new Application()` is empty;+ configuration happens in `await app.init({...})`. Append `app.canvas` (not+ `app.view`) to the DOM. Wrap top-level `await` in an async function for bundlers.+2. **Load assets with `Assets`.** `await Assets.load(url)` returns a `Texture`. For+ many assets, register a manifest/bundle and load by name. There is no v7 `Loader`.+3. **Build the scene graph.** Everything descends from `app.stage` (a `Container`).+ Group related objects in `Container`s; child transforms are relative to the+ parent. Draw order = insertion order (later = on top).+4. **Animate with the ticker.** `app.ticker.add((ticker) => {...})`. Scale motion by+ `ticker.deltaTime` (frames, ~1 at 60fps) or `ticker.deltaMS` (milliseconds) so+ speed is frame-rate independent.+5. **Enable events per object** by setting `eventMode = 'static'` (or `'dynamic'`),+ then `obj.on('pointerdown', ...)`. Federated pointer events cover mouse/touch/pen.+6. **Promote big static subtrees to render groups** (`isRenderGroup: true`) so the+ GPU caches their transforms. Profile before and after; confirm pixels on screen.++## Patterns++### 1. Async Application boot (the v8 entry point)++```js+import { Application, Assets, Sprite } from 'pixi.js';++(async () => {+ // v8: construct empty, then await init(). Config does NOT go in the constructor.+ const app = new Application();+ await app.init({+ background: '#1099bb',+ resizeTo: window, // track the window size+ antialias: true,+ // preference: 'webgpu', // opt into WebGPU; default 'webgl'+ });++ document.body.appendChild(app.canvas); // v8 uses app.canvas, not app.view++ const texture = await Assets.load('https://pixijs.com/assets/bunny.png');+ const bunny = new Sprite(texture);+ bunny.anchor.set(0.5);+ bunny.position.set(app.screen.width / 2, app.screen.height / 2);+ app.stage.addChild(bunny);+})();+```++### 2. Containers for a relative-transform scene graph++```js+import { Container, Sprite } from 'pixi.js';++const world = new Container();+app.stage.addChild(world);++// Children are positioned relative to `world`; move/scale/rotate the whole group+// by transforming the parent.+for (let i = 0; i < 10; i++) {+ const coin = new Sprite(coinTexture);+ coin.x = i * 40;+ world.addChild(coin);+}+world.position.set(100, 100);+world.scale.set(2); // every coin scales with the container+```++### 3. The ticker loop (frame-rate independent)++```js+let elapsed = 0;+app.ticker.add((ticker) => {+ // deltaTime ≈ 1 at 60fps; deltaMS is milliseconds since last frame.+ elapsed += ticker.deltaMS;+ bunny.rotation += 0.05 * ticker.deltaTime; // smooth at any frame rate+ bunny.y = app.screen.height / 2 + Math.sin(elapsed / 500) * 50;+});+```++### 4. Pointer events (federated)++```js+bunny.eventMode = 'static'; // 'static' = interactive, doesn't move on its own+bunny.cursor = 'pointer';+bunny.on('pointerdown', (event) => {+ bunny.tint = 0xff0000;+ // event.global is the pointer position in stage space.+});+bunny.on('pointerover', () => bunny.scale.set(1.1));+bunny.on('pointerout', () => bunny.scale.set(1.0));+```++### 5. Loading many assets by name (bundles)++```js+import { Assets } from 'pixi.js';++await Assets.init({+ manifest: {+ bundles: [{+ name: 'level-1',+ assets: [+ { alias: 'hero', src: 'assets/hero.png' },+ { alias: 'tiles', src: 'assets/tiles.png' },+ ],+ }],+ },+});++const bundle = await Assets.loadBundle('level-1'); // { hero: Texture, tiles: Texture }+const hero = new Sprite(bundle.hero);+```++### 6. Render groups for large static layers++```js+// A big, rarely-changing background subtree: let the GPU cache its transforms.+const background = new Container({ isRenderGroup: true });+app.stage.addChild(background);+// Add hundreds of static tiles to `background`. Moving `background` itself stays+// cheap; constantly re-adding/removing children negates the benefit.+```++## Pitfalls++- **Blank canvas / "app.stage is undefined"** → you didn't `await app.init()`, or you+ configured the constructor. In v8 the constructor is empty; all options go to+ `init()`.+- **`app.view` is undefined** → v8 renamed it to `app.canvas`.+- **v7 code throwing** → `interactive = true` → `eventMode = 'static'`; `Loader`/+ `loader.add` → `Assets.load`; synchronous `new Application({...})` → async `init`.+- **Top-level await build error (Vite ≤6)** → wrap boot in `(async () => { ... })()`.+- **Speed varies with frame rate** → multiply movement by `ticker.deltaTime` (or use+ `deltaMS`); never assume 60fps.+- **Clicks do nothing** → the object's `eventMode` is still `'none'` (the default);+ set it to `'static'` or `'dynamic'`.+- **Textures look blurry on pixel art** → set+ `texture.source.scaleMode = 'nearest'` (or pass it when loading).+- **Memory grows** → `removeChild` does not free GPU memory; call+ `sprite.destroy()` and `Assets.unload(url)` for assets you're done with.++## References++- For the texture/asset pipeline (sprite sheets/atlases, `Assets.add`, background+ loading, unloading) and Graphics/Text/`TilingSprite`/`ParticleContainer` plus+ filters, read `references/assets-and-display.md`.++## Related skills++- `phaser-core` — a batteries-included 2D framework (scenes, physics, input).+- `threejs-scene-setup` — 3D in the browser with three.js.+- `prototype-fast` — greybox a playable slice quickly (often cites PixiJS).diff --git a/skills/web-engines/pixijs-rendering/references/assets-and-display.md b/skills/web-engines/pixijs-rendering/references/assets-and-display.mdnew file mode 100644index 0000000..ef30866--- /dev/null+++ b/skills/web-engines/pixijs-rendering/references/assets-and-display.md@@ -0,0 +1,128 @@+# PixiJS v8 assets & display objects++Depth on the v8 asset pipeline and the display-object types beyond `Sprite`. The+`SKILL.md` covers the boot path and scene graph; this file fills in textures and+the other things you draw.++## The `Assets` system (v8)++`Assets` replaces the v7 `Loader`. It caches by URL/alias, so calling+`Assets.load` twice for the same source resolves immediately the second time.++```js+import { Assets } from 'pixi.js';++// Single asset.+const tex = await Assets.load('assets/hero.png');++// Register aliases up front, load later by name.+Assets.add({ alias: 'hero', src: 'assets/hero.png' });+const hero = await Assets.load('hero');++// Load several at once (object form keeps results keyed).+const sheet = await Assets.load([ 'a.png', 'b.png' ]);++// Background-load without blocking, then `load` resolves instantly when needed.+Assets.backgroundLoad(['level-2-bg.png']);++// Free GPU + CPU memory when a screen is done.+await Assets.unload('hero');+```++Supported source types include images, sprite-sheet JSON (atlases), bitmap fonts,+web fonts, and audio (with the right loader installed). Atlases load as a+`Spritesheet`; access frames by name:++```js+const sheet = await Assets.load('assets/characters.json'); // TexturePacker JSON+const idle = new Sprite(sheet.textures['hero_idle.png']);+const runFrames = sheet.animations['hero_run']; // Texture[] for animation+```++## Texture settings++```js+import { Texture } from 'pixi.js';++texture.source.scaleMode = 'nearest'; // crisp pixel art ('linear' is the default)+const sub = new Texture({ source: texture.source, frame: new Rectangle(0, 0, 16, 16) });+```++`Texture` is a view into a `TextureSource` (the GPU resource). Many `Texture`s can+share one source — that's how atlases avoid extra uploads.++## Display object types++### AnimatedSprite++```js+import { AnimatedSprite } from 'pixi.js';+const anim = new AnimatedSprite(sheet.animations['hero_run']);+anim.animationSpeed = 0.2; // fraction of a frame per ticker tick+anim.play();+app.stage.addChild(anim);+```++### Graphics (vector drawing)++v8 uses a fluent, retained API: define the shape, then call a fill/stroke.++```js+import { Graphics } from 'pixi.js';+const g = new Graphics()+ .roundRect(0, 0, 120, 60, 12)+ .fill(0x4488ff)+ .stroke({ width: 2, color: 0xffffff });+app.stage.addChild(g);+```++(In v7 the order was `beginFill` → draw → `endFill`; v8 draws the shape first, then+fills/strokes it.)++### Text & BitmapText++```js+import { Text, TextStyle } from 'pixi.js';+const score = new Text({+ text: 'Score: 0',+ style: new TextStyle({ fontFamily: 'Arial', fontSize: 24, fill: '#ffffff' }),+});+```++Use `BitmapText` for frequently changing strings (HUD counters): it re-uses glyph+textures instead of rasterising new ones each change.++### TilingSprite (scrolling backgrounds)++```js+import { TilingSprite } from 'pixi.js';+const bg = new TilingSprite({ texture: skyTexture, width: app.screen.width, height: app.screen.height });+app.ticker.add((t) => { bg.tilePosition.x -= 0.5 * t.deltaTime; });+```++### ParticleContainer (many simple sprites)++For thousands of cheap, same-texture sprites (bullets, particles), a+`ParticleContainer` trades per-child features for throughput. Keep dynamic+properties (position/rotation/etc.) explicit and avoid features it doesn't support.++## Filters++Filters are GPU post-process effects applied to a display object and its children:++```js+import { BlurFilter } from 'pixi.js';+container.filters = [new BlurFilter({ strength: 4 })];+```++Filters render the subtree to a temporary texture, so they cost memory and fill+rate — apply sparingly and remove (`obj.filters = null`) when not needed.++## Cleanup++- `removeChild(child)` detaches but does **not** free GPU memory.+- `child.destroy()` frees the display object; pass options to also destroy its+ texture: `sprite.destroy({ texture: true, textureSource: true })`.+- `Assets.unload(urlOrAlias)` frees a loaded asset's GPU/CPU memory.+- On WebGL/WebGPU context loss, textures are restored from their sources; keep the+ source (or be ready to reload) for anything generated at runtime.diff --git a/skills/web-engines/threejs-gltf-loading/SKILL.md b/skills/web-engines/threejs-gltf-loading/SKILL.mdnew file mode 100644index 0000000..fa4ccf4--- /dev/null+++ b/skills/web-engines/threejs-gltf-loading/SKILL.md@@ -0,0 +1,183 @@+---+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 r150+ (verified 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+**r150+**, 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/[email protected]/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/skills/web-engines/threejs-gltf-loading/references/loaders-and-animation.md b/skills/web-engines/threejs-gltf-loading/references/loaders-and-animation.mdnew file mode 100644index 0000000..8504a69--- /dev/null+++ b/skills/web-engines/threejs-gltf-loading/references/loaders-and-animation.md@@ -0,0 +1,113 @@+# 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/skills/web-engines/threejs-materials-lighting/SKILL.md b/skills/web-engines/threejs-materials-lighting/SKILL.mdnew file mode 100644index 0000000..85d7262--- /dev/null+++ b/skills/web-engines/threejs-materials-lighting/SKILL.md@@ -0,0 +1,176 @@+---+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 r155+ (verified r184; physically based lighting default)+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 **r155+** (lighting+is physically based by default), verified against **r184**.++## 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/skills/web-engines/threejs-materials-lighting/references/materials-lights-table.md b/skills/web-engines/threejs-materials-lighting/references/materials-lights-table.mdnew file mode 100644index 0000000..326ccc9--- /dev/null+++ b/skills/web-engines/threejs-materials-lighting/references/materials-lights-table.md@@ -0,0 +1,93 @@+# 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/skills/web-engines/threejs-scene-setup/SKILL.md b/skills/web-engines/threejs-scene-setup/SKILL.mdnew file mode 100644index 0000000..3e8436c--- /dev/null+++ b/skills/web-engines/threejs-scene-setup/SKILL.md@@ -0,0 +1,173 @@+---+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 r150+ (verified 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 **r150+** 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+<canvas id="c"></canvas>+<script type="importmap">+{+ "imports": {+ "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",+ "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"+ }+}+</script>+<script type="module" src="./main.js"></script>+```++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 `<script src="three.min.js">`** → since r147 three.js ships+ ES modules only; use `type="module"` + import maps.++## References++- For coordinate conventions, the scene-graph (`Group`, parent/child transforms,+ `Object3D` add/remove), `OrthographicCamera` for 2.5D, and disposing of+ geometries/materials/textures to avoid leaks, read `references/scene-graph.md`.++## Related skills++- `threejs-materials-lighting` — give surfaces a lit look (lights, shadows, PBR).+- `threejs-gltf-loading` — load 3D models and play their animations.+- `pixijs-rendering` — 2D rendering in the browser.+- `fps-shooter` — a 3D genre template that composes three.js skills.diff --git a/skills/web-engines/threejs-scene-setup/references/scene-graph.md b/skills/web-engines/threejs-scene-setup/references/scene-graph.mdnew file mode 100644index 0000000..b28563d--- /dev/null+++ b/skills/web-engines/threejs-scene-setup/references/scene-graph.md@@ -0,0 +1,112 @@+# three.js scene graph, cameras & cleanup (r150+)++Depth behind the scene-setup skill: coordinate conventions, the `Object3D`+hierarchy, the orthographic camera, and resource disposal.++## Coordinates & conventions++- Right-handed coordinate system: **+X right, +Y up, +Z toward the viewer**. A fresh+ `PerspectiveCamera` looks down **-Z**.+- Rotations are in **radians** (except `PerspectiveCamera`'s `fov`, which is degrees).+ Use `THREE.MathUtils.degToRad(deg)` when you think in degrees.+- Units are arbitrary but be consistent. glTF models are authored in metres; pick a+ scale and stick to it across the project.++## The Object3D hierarchy++Every visual thing (`Mesh`, `Group`, `Camera`, `Light`) extends `Object3D` and has+`position`, `rotation`, `quaternion`, and `scale`. Children inherit their parent's+transform.++```js+import * as THREE from 'three';++const turret = new THREE.Group(); // empty transform node+turret.add(barrelMesh); // child, positioned relative to turret+scene.add(turret);+turret.rotation.y = Math.PI / 4; // rotates the whole group++barrelMesh.removeFromParent(); // detach (r129+)+scene.add(barrelMesh); // re-parent to the scene root+```++Useful traversal/lookup helpers:++```js+scene.getObjectByName('Player'); // first descendant with that .name+root.traverse((obj) => { /* visit every descendant */ });+obj.getWorldPosition(new THREE.Vector3()); // world-space position+```++Avoid scaling parents of physics/gameplay objects: non-unit parent scale compounds+through children and makes world-space math (raycasts, distances) error-prone.++## PerspectiveCamera vs OrthographicCamera++- **PerspectiveCamera(fov, aspect, near, far)** — objects shrink with distance.+ Default for 3D. Keep `near`/`far` as tight as the scene allows; a huge far/near+ ratio wrecks depth precision (z-fighting).+- **OrthographicCamera(left, right, top, bottom, near, far)** — no perspective;+ ideal for 2.5D, isometric, or CAD-like views. Size the frustum to the aspect:++```js+const aspect = window.innerWidth / window.innerHeight;+const d = 5;+const cam = new THREE.OrthographicCamera(-d * aspect, d * aspect, d, -d, 0.1, 100);+// On resize, recompute left/right from the new aspect, then updateProjectionMatrix().+```++After changing any projection property (`aspect`, `fov`, frustum extents, `zoom`)+call `camera.updateProjectionMatrix()`.++## Disposing of resources (avoiding leaks)++three.js cannot garbage-collect GPU memory for you. Removing an object from the+scene frees nothing on the GPU; you must dispose geometries, materials, and+textures explicitly.++```js+function disposeObject(obj) {+ obj.traverse((node) => {+ if (node.geometry) node.geometry.dispose();+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ for (const mat of materials) {+ if (!mat) continue;+ for (const key of Object.keys(mat)) {+ const value = mat[key];+ if (value && value.isTexture) value.dispose(); // map, normalMap, etc.+ }+ mat.dispose();+ }+ });+ obj.removeFromParent();+}+```++Also dispose render targets (`renderTarget.dispose()`) and, on full teardown, the+renderer (`renderer.dispose()`). When swapping levels, dispose the old level's+subtree before loading the next, or memory grows every transition.++## Stopping and restarting the loop++`renderer.setAnimationLoop(fn)` starts the loop; `setAnimationLoop(null)` stops it+(e.g. when the tab is hidden via the Page Visibility API, or a menu is open). This+is also the loop required by WebXR — `requestAnimationFrame` does not drive XR+frames.++## Render-on-demand++For static scenes or editors, you don't need a continuous loop. Render only when+something changes (input, controls' `change` event, a tween step):++```js+let needsRender = true;+controls.addEventListener('change', () => { needsRender = true; });+renderer.setAnimationLoop(() => {+ if (!needsRender) return;+ needsRender = false;+ renderer.render(scene, camera);+});+```++This cuts GPU/battery use dramatically for non-animated content.