From d966af3f8f1169c91548d72a257ac8860608220b Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Sun, 1 Nov 2026 20:15:27 +0100 Subject: [PATCH] added pixlJS official skills and the prototype document --- .agents/skills/pixijs-accessibility/SKILL.md | 224 +++++++ .agents/skills/pixijs-application/SKILL.md | 293 +++++++++ .../references/application-options.md | 314 ++++++++++ .agents/skills/pixijs-assets/SKILL.md | 303 +++++++++ .../pixijs-assets/references/background.md | 137 +++++ .../pixijs-assets/references/bundles.md | 122 ++++ .../pixijs-assets/references/caching.md | 143 +++++ .../references/compressed-textures.md | 120 ++++ .../skills/pixijs-assets/references/fonts.md | 205 +++++++ .../skills/pixijs-assets/references/gif.md | 171 ++++++ .../pixijs-assets/references/manifests.md | 175 ++++++ .../pixijs-assets/references/progress.md | 142 +++++ .../pixijs-assets/references/resolution.md | 142 +++++ .../pixijs-assets/references/spritesheet.md | 119 ++++ .../skills/pixijs-assets/references/svg.md | 132 ++++ .../skills/pixijs-assets/references/video.md | 158 +++++ .agents/skills/pixijs-blend-modes/SKILL.md | 215 +++++++ .agents/skills/pixijs-color/SKILL.md | 299 +++++++++ .agents/skills/pixijs-core-concepts/SKILL.md | 132 ++++ .../references/render-loop.md | 216 +++++++ .../references/renderers.md | 287 +++++++++ .agents/skills/pixijs-create/SKILL.md | 276 +++++++++ .../skills/pixijs-custom-rendering/SKILL.md | 405 ++++++++++++ .../references/advanced-gpu.md | 244 ++++++++ .../references/uniform-types.md | 95 +++ .agents/skills/pixijs-environments/SKILL.md | 243 ++++++++ .agents/skills/pixijs-events/SKILL.md | 387 ++++++++++++ .agents/skills/pixijs-filters/SKILL.md | 300 +++++++++ .agents/skills/pixijs-html-source/SKILL.md | 228 +++++++ .agents/skills/pixijs-math/SKILL.md | 489 +++++++++++++++ .agents/skills/pixijs-migration-v8/SKILL.md | 415 +++++++++++++ .agents/skills/pixijs-performance/SKILL.md | 489 +++++++++++++++ .../skills/pixijs-scene-container/SKILL.md | 345 +++++++++++ .../pixijs-scene-core-concepts/SKILL.md | 243 ++++++++ .../references/constructor-options.md | 155 +++++ .../references/container-hierarchy.md | 232 +++++++ .../references/layers.md | 145 +++++ .../references/masking.md | 129 ++++ .../references/render-groups.md | 140 +++++ .../references/scene-management.md | 169 +++++ .../references/transforms.md | 198 ++++++ .../pixijs-scene-dom-container/SKILL.md | 193 ++++++ .agents/skills/pixijs-scene-gif/SKILL.md | 233 +++++++ .agents/skills/pixijs-scene-graphics/SKILL.md | 576 ++++++++++++++++++ .agents/skills/pixijs-scene-mesh/SKILL.md | 141 +++++ .../references/mesh-perspective.md | 189 ++++++ .../references/mesh-plane.md | 159 +++++ .../pixijs-scene-mesh/references/mesh-rope.md | 176 ++++++ .../references/mesh-simple.md | 144 +++++ .../pixijs-scene-mesh/references/mesh.md | 213 +++++++ .../pixijs-scene-particle-container/SKILL.md | 323 ++++++++++ .agents/skills/pixijs-scene-sprite/SKILL.md | 120 ++++ .../references/animated-sprite.md | 262 ++++++++ .../references/nineslice-sprite.md | 202 ++++++ .../pixijs-scene-sprite/references/sprite.md | 181 ++++++ .../references/tiling-sprite.md | 216 +++++++ .agents/skills/pixijs-scene-text/SKILL.md | 136 +++++ .../references/bitmap-text.md | 232 +++++++ .../pixijs-scene-text/references/html-text.md | 192 ++++++ .../references/split-bitmap-text.md | 187 ++++++ .../references/split-text.md | 168 +++++ .../pixijs-scene-text/references/text.md | 311 ++++++++++ .agents/skills/pixijs-ticker/SKILL.md | 292 +++++++++ .agents/skills/pixijs/SKILL.md | 66 ++ .agents/skills/pixijs/references/index.md | 136 +++++ .claude/skills/pixijs | 1 + .claude/skills/pixijs-accessibility | 1 + .claude/skills/pixijs-application | 1 + .claude/skills/pixijs-assets | 1 + .claude/skills/pixijs-blend-modes | 1 + .claude/skills/pixijs-color | 1 + .claude/skills/pixijs-core-concepts | 1 + .claude/skills/pixijs-create | 1 + .claude/skills/pixijs-custom-rendering | 1 + .claude/skills/pixijs-environments | 1 + .claude/skills/pixijs-events | 1 + .claude/skills/pixijs-filters | 1 + .claude/skills/pixijs-html-source | 1 + .claude/skills/pixijs-math | 1 + .claude/skills/pixijs-migration-v8 | 1 + .claude/skills/pixijs-performance | 1 + .claude/skills/pixijs-scene-container | 1 + .claude/skills/pixijs-scene-core-concepts | 1 + .claude/skills/pixijs-scene-dom-container | 1 + .claude/skills/pixijs-scene-gif | 1 + .claude/skills/pixijs-scene-graphics | 1 + .claude/skills/pixijs-scene-mesh | 1 + .../skills/pixijs-scene-particle-container | 1 + .claude/skills/pixijs-scene-sprite | 1 + .claude/skills/pixijs-scene-text | 1 + .claude/skills/pixijs-ticker | 1 + docs/prototype.md | 70 +++ skills-lock.json | 161 +++++ 93 files changed, 14681 insertions(+) create mode 100644 .agents/skills/pixijs-accessibility/SKILL.md create mode 100644 .agents/skills/pixijs-application/SKILL.md create mode 100644 .agents/skills/pixijs-application/references/application-options.md create mode 100644 .agents/skills/pixijs-assets/SKILL.md create mode 100644 .agents/skills/pixijs-assets/references/background.md create mode 100644 .agents/skills/pixijs-assets/references/bundles.md create mode 100644 .agents/skills/pixijs-assets/references/caching.md create mode 100644 .agents/skills/pixijs-assets/references/compressed-textures.md create mode 100644 .agents/skills/pixijs-assets/references/fonts.md create mode 100644 .agents/skills/pixijs-assets/references/gif.md create mode 100644 .agents/skills/pixijs-assets/references/manifests.md create mode 100644 .agents/skills/pixijs-assets/references/progress.md create mode 100644 .agents/skills/pixijs-assets/references/resolution.md create mode 100644 .agents/skills/pixijs-assets/references/spritesheet.md create mode 100644 .agents/skills/pixijs-assets/references/svg.md create mode 100644 .agents/skills/pixijs-assets/references/video.md create mode 100644 .agents/skills/pixijs-blend-modes/SKILL.md create mode 100644 .agents/skills/pixijs-color/SKILL.md create mode 100644 .agents/skills/pixijs-core-concepts/SKILL.md create mode 100644 .agents/skills/pixijs-core-concepts/references/render-loop.md create mode 100644 .agents/skills/pixijs-core-concepts/references/renderers.md create mode 100644 .agents/skills/pixijs-create/SKILL.md create mode 100644 .agents/skills/pixijs-custom-rendering/SKILL.md create mode 100644 .agents/skills/pixijs-custom-rendering/references/advanced-gpu.md create mode 100644 .agents/skills/pixijs-custom-rendering/references/uniform-types.md create mode 100644 .agents/skills/pixijs-environments/SKILL.md create mode 100644 .agents/skills/pixijs-events/SKILL.md create mode 100644 .agents/skills/pixijs-filters/SKILL.md create mode 100644 .agents/skills/pixijs-html-source/SKILL.md create mode 100644 .agents/skills/pixijs-math/SKILL.md create mode 100644 .agents/skills/pixijs-migration-v8/SKILL.md create mode 100644 .agents/skills/pixijs-performance/SKILL.md create mode 100644 .agents/skills/pixijs-scene-container/SKILL.md create mode 100644 .agents/skills/pixijs-scene-core-concepts/SKILL.md create mode 100644 .agents/skills/pixijs-scene-core-concepts/references/constructor-options.md create mode 100644 .agents/skills/pixijs-scene-core-concepts/references/container-hierarchy.md create mode 100644 .agents/skills/pixijs-scene-core-concepts/references/layers.md create mode 100644 .agents/skills/pixijs-scene-core-concepts/references/masking.md create mode 100644 .agents/skills/pixijs-scene-core-concepts/references/render-groups.md create mode 100644 .agents/skills/pixijs-scene-core-concepts/references/scene-management.md create mode 100644 .agents/skills/pixijs-scene-core-concepts/references/transforms.md create mode 100644 .agents/skills/pixijs-scene-dom-container/SKILL.md create mode 100644 .agents/skills/pixijs-scene-gif/SKILL.md create mode 100644 .agents/skills/pixijs-scene-graphics/SKILL.md create mode 100644 .agents/skills/pixijs-scene-mesh/SKILL.md create mode 100644 .agents/skills/pixijs-scene-mesh/references/mesh-perspective.md create mode 100644 .agents/skills/pixijs-scene-mesh/references/mesh-plane.md create mode 100644 .agents/skills/pixijs-scene-mesh/references/mesh-rope.md create mode 100644 .agents/skills/pixijs-scene-mesh/references/mesh-simple.md create mode 100644 .agents/skills/pixijs-scene-mesh/references/mesh.md create mode 100644 .agents/skills/pixijs-scene-particle-container/SKILL.md create mode 100644 .agents/skills/pixijs-scene-sprite/SKILL.md create mode 100644 .agents/skills/pixijs-scene-sprite/references/animated-sprite.md create mode 100644 .agents/skills/pixijs-scene-sprite/references/nineslice-sprite.md create mode 100644 .agents/skills/pixijs-scene-sprite/references/sprite.md create mode 100644 .agents/skills/pixijs-scene-sprite/references/tiling-sprite.md create mode 100644 .agents/skills/pixijs-scene-text/SKILL.md create mode 100644 .agents/skills/pixijs-scene-text/references/bitmap-text.md create mode 100644 .agents/skills/pixijs-scene-text/references/html-text.md create mode 100644 .agents/skills/pixijs-scene-text/references/split-bitmap-text.md create mode 100644 .agents/skills/pixijs-scene-text/references/split-text.md create mode 100644 .agents/skills/pixijs-scene-text/references/text.md create mode 100644 .agents/skills/pixijs-ticker/SKILL.md create mode 100644 .agents/skills/pixijs/SKILL.md create mode 100644 .agents/skills/pixijs/references/index.md create mode 120000 .claude/skills/pixijs create mode 120000 .claude/skills/pixijs-accessibility create mode 120000 .claude/skills/pixijs-application create mode 120000 .claude/skills/pixijs-assets create mode 120000 .claude/skills/pixijs-blend-modes create mode 120000 .claude/skills/pixijs-color create mode 120000 .claude/skills/pixijs-core-concepts create mode 120000 .claude/skills/pixijs-create create mode 120000 .claude/skills/pixijs-custom-rendering create mode 120000 .claude/skills/pixijs-environments create mode 120000 .claude/skills/pixijs-events create mode 120000 .claude/skills/pixijs-filters create mode 120000 .claude/skills/pixijs-html-source create mode 120000 .claude/skills/pixijs-math create mode 120000 .claude/skills/pixijs-migration-v8 create mode 120000 .claude/skills/pixijs-performance create mode 120000 .claude/skills/pixijs-scene-container create mode 120000 .claude/skills/pixijs-scene-core-concepts create mode 120000 .claude/skills/pixijs-scene-dom-container create mode 120000 .claude/skills/pixijs-scene-gif create mode 120000 .claude/skills/pixijs-scene-graphics create mode 120000 .claude/skills/pixijs-scene-mesh create mode 120000 .claude/skills/pixijs-scene-particle-container create mode 120000 .claude/skills/pixijs-scene-sprite create mode 120000 .claude/skills/pixijs-scene-text create mode 120000 .claude/skills/pixijs-ticker create mode 100644 docs/prototype.md create mode 100644 skills-lock.json diff --git a/.agents/skills/pixijs-accessibility/SKILL.md b/.agents/skills/pixijs-accessibility/SKILL.md new file mode 100644 index 0000000..5b3219f --- /dev/null +++ b/.agents/skills/pixijs-accessibility/SKILL.md @@ -0,0 +1,224 @@ +--- +name: pixijs-accessibility +description: "Use this skill when adding screen reader and keyboard navigation to PixiJS v8 apps. Covers AccessibilitySystem options (enabledByDefault, debug, activateOnTab, deactivateOnMouseMove), per-container accessibility properties, shadow DOM overlay, mobile touch-hook activation. Triggers on: accessibility, a11y, screen reader, ARIA, keyboard navigation, tab order, AccessibilitySystem, accessibleTitle, accessibleHint, tabIndex, accessibleChildren." +license: MIT +--- + +Enable screen reader and keyboard navigation via PixiJS's AccessibilitySystem. The system creates an invisible shadow DOM overlay positioned over accessible containers so assistive technology can discover and activate them. + +## Quick Start + +```ts +const button = new Sprite(await Assets.load("button.png")); +button.accessible = true; +button.accessibleTitle = "Play game"; +button.accessibleHint = "Starts a new game session"; +button.eventMode = "static"; +button.tabIndex = 0; +app.stage.addChild(button); + +app.renderer.accessibility.setAccessibilityEnabled(true); + +button.on("pointertap", () => startGame()); +``` + +**Related skills:** `pixijs-events` (pointer/tap handlers), `pixijs-scene-dom-container` (HTML elements on canvas), `pixijs-application` (init options). + +**Key points:** + +- By default the system activates only after the user presses Tab. Set `enabledByDefault: true` in Application init for immediate activation. +- On mobile, the system creates a hidden touch hook; screen-reader focus activates accessibility for the whole session. +- The AccessibilitySystem requires the main thread; it is not available in a Web Worker. + +## Core Patterns + +### Container accessible properties + +```ts +import { Container, Sprite } from "pixi.js"; + +const container = new Container(); +container.accessible = true; +container.accessibleTitle = "Navigation menu"; +container.accessibleHint = "Contains links to other pages"; +container.eventMode = "static"; // required for custom tabIndex to apply +container.tabIndex = 0; +container.accessibleType = "div"; // defaults to 'button' + +const sprite = new Sprite(); +sprite.accessible = true; +sprite.accessibleTitle = "Close dialog"; +sprite.accessibleText = "X"; // text content of the shadow div +sprite.eventMode = "static"; +sprite.tabIndex = 1; +``` + +Available properties on any Container: + +- `accessible` (boolean) - enables the accessible overlay div +- `accessibleTitle` (string) - sets the `title` attribute on the shadow div +- `accessibleHint` (string) - sets the `aria-label` attribute +- `accessibleText` (string) - sets inner text content of the shadow div +- `accessibleType` (string) - HTML tag for the shadow element, defaults to `'button'` +- `tabIndex` (number) - tab order for keyboard navigation (only applied when `interactive` is true / `eventMode` is `'static'` or `'dynamic'`) +- `accessibleChildren` (boolean, default `true`) - when `false`, prevents child containers from being accessible +- `accessiblePointerEvents` (string) - CSS `pointer-events` value on the shadow div + +### Custom tab order + +Give each accessible container a `tabIndex` to control the order assistive tech walks through them. Higher numbers come later; equal numbers fall back to scene-graph order. + +```ts +menuButton.accessible = true; +menuButton.eventMode = "static"; +menuButton.tabIndex = 1; + +playButton.accessible = true; +playButton.eventMode = "static"; +playButton.tabIndex = 2; + +settingsButton.accessible = true; +settingsButton.eventMode = "static"; +settingsButton.tabIndex = 3; +``` + +`tabIndex` is only forwarded to the shadow div when the container is `interactive` (`eventMode` is `'static'` or `'dynamic'`). Without that, the system clamps the div's tabIndex back to `0`, and the order you set is ignored. + +### Programmatic control + +```ts +import { Application } from "pixi.js"; + +const app = new Application(); +await app.init({ width: 800, height: 600 }); + +// Enable accessibility at runtime +app.renderer.accessibility.setAccessibilityEnabled(true); + +// Check current state +console.log(app.renderer.accessibility.isActive); +console.log(app.renderer.accessibility.isMobileAccessibility); + +// Full init options: +await app.init({ + accessibilityOptions: { + enabledByDefault: true, // activate immediately (default: false) + debug: true, // makes overlay divs visible (default: false) + activateOnTab: true, // Tab key activates system (default: true) + deactivateOnMouseMove: false, // stay active when mouse moves (default: true) + }, +}); +``` + +The system can also be configured via static defaults before creating the Application: + +```ts +import { AccessibilitySystem, Application } from "pixi.js"; + +AccessibilitySystem.defaultOptions.enabledByDefault = true; +AccessibilitySystem.defaultOptions.deactivateOnMouseMove = false; + +const app = new Application(); +await app.init(); +``` + +### Handling accessible interactions + +```ts +import { Sprite } from "pixi.js"; + +const button = new Sprite(); +button.eventMode = "static"; +button.accessible = true; +button.accessibleTitle = "Submit form"; +button.tabIndex = 0; + +// Screen readers trigger click/tap events through the shadow DOM element +button.on("pointertap", () => { + submitForm(); +}); +``` + +When accessibility is active and a user activates a shadow div (via Enter/Space key or screen reader action), the system dispatches `click`, `pointertap`, and `tap` FederatedEvents to the corresponding container. Focus on the shadow div dispatches `mouseover`, and focus-out dispatches `mouseout`. Both `eventMode` and `accessible` should be set for full keyboard + pointer support. + +## Common Mistakes + +### [MEDIUM] Expecting accessibility to be active without Tab key press + +The AccessibilitySystem does not create its DOM overlay until the user presses Tab (or, on mobile, focuses the touch hook). If your application needs accessibility immediately: + +```ts +const app = new Application(); +await app.init({ + accessibilityOptions: { + enabledByDefault: true, + }, +}); +``` + +Or at runtime: + +```ts +app.renderer.accessibility.setAccessibilityEnabled(true); +``` + +Without one of these, automated accessibility testing tools will not find the overlay elements. + + +### [MEDIUM] Setting accessible without accessibleTitle + +Wrong: + +```ts +const sprite = new Sprite(); +sprite.accessible = true; +// no title or hint set +``` + +Correct: + +```ts +const sprite = new Sprite(); +sprite.accessible = true; +sprite.accessibleTitle = "Play button"; +sprite.accessibleHint = "Click to start the game"; +``` + +A container with `accessible = true` but no `accessibleTitle` or `accessibleHint` gets a fallback title of `"container {tabIndex}"`. Screen readers will announce this generic label with no useful context. Always provide at least `accessibleTitle`. + + +### [MEDIUM] Accessibility deactivates when moving mouse + +By default, `deactivateOnMouseMove` is `true`. Any mouse movement after Tab-activation will deactivate the overlay. This is by design (assumes keyboard-only users don't use a mouse), but it makes testing with a mouse frustrating. + +```ts +await app.init({ + accessibilityOptions: { + deactivateOnMouseMove: false, + }, +}); +``` + + +### [MEDIUM] Not importing accessibility extension in custom builds + +When using `skipExtensionImports: true` for a custom build, the accessibility extension is not automatically registered. You must import it explicitly: + +```ts +import "pixi.js/accessibility"; +import { Application } from "pixi.js"; + +const app = new Application(); +await app.init({ skipExtensionImports: true }); +``` + +Without this import, `app.renderer.accessibility` will be undefined and no shadow DOM layer will be created. + + +## API Reference + +- [AccessibilitySystem](https://pixijs.download/release/docs/accessibility.AccessibilitySystem.html.md) +- [AccessibilitySystemOptions](https://pixijs.download/release/docs/accessibility.AccessibilitySystemOptions.html.md) +- [AccessibilityOptions](https://pixijs.download/release/docs/accessibility.AccessibilityOptions.html.md) +- [AccessibleOptions](https://pixijs.download/release/docs/accessibility.AccessibleOptions.html.md) +- [PointerEvents](https://pixijs.download/release/docs/accessibility.PointerEvents.html.md) diff --git a/.agents/skills/pixijs-application/SKILL.md b/.agents/skills/pixijs-application/SKILL.md new file mode 100644 index 0000000..16adff1 --- /dev/null +++ b/.agents/skills/pixijs-application/SKILL.md @@ -0,0 +1,293 @@ +--- +name: pixijs-application +description: "Use this skill when creating and configuring a PixiJS v8 Application. Covers new Application() + async app.init() options (width, height, background, antialias, resolution, autoDensity, preference, resizeTo, autoStart, sharedTicker, canvas, useBackBuffer, powerPreference, eventFeatures, accessibilityOptions, gcActive, bezierSmoothness, webgl/webgpu/canvasOptions per-renderer overrides), app.stage/renderer/canvas/screen/domContainerRoot access, ResizePlugin, TickerPlugin, CullerPlugin (cullable, cullArea), custom ApplicationPlugin via ExtensionType.Application, start/stop lifecycle, and app.destroy() with releaseGlobalResources. Triggers on: Application, app.init, app.stage, app.renderer, app.canvas, app.screen, app.domContainerRoot, ApplicationOptions, ApplicationPlugin, ExtensionType.Application, resizeTo, sharedTicker, skipExtensionImports, preferWebGLVersion, preserveDrawingBuffer, cullable, CullerPlugin, app.start, app.stop, app.destroy, releaseGlobalResources." +license: MIT +--- + +`Application` is the convenience wrapper that owns a renderer, a root `stage` Container, a canvas, and the Ticker/Resize plugins. In v8 the constructor takes no arguments; all configuration is passed to the async `app.init()` call which instantiates the renderer via `autoDetectRenderer`. + +## Quick Start + +```ts +import { Application } from "pixi.js"; + +const app = new Application(); + +await app.init({ + resizeTo: window, + background: "#1099bb", + antialias: true, + preference: "webgl", + autoDensity: true, + resolution: window.devicePixelRatio, +}); + +document.body.appendChild(app.canvas); +``` + +**Related skills:** `pixijs-core-concepts` (renderers, render pipeline), `pixijs-ticker` (render loop detail), `pixijs-scene-container` (working with `app.stage`), `pixijs-environments` (non-browser setups). + +## Core Patterns + +### Lifecycle: construct, init, render, destroy + +```ts +import { Application } from "pixi.js"; + +const app = new Application(); + +await app.init({ width: 800, height: 600 }); +document.body.appendChild(app.canvas); + +// ... run scene, ticker drives app.render() automatically ... + +app.destroy( + { removeView: true, releaseGlobalResources: true }, + { children: true, texture: true, textureSource: true }, +); +``` + +- `new Application()` allocates the instance but creates nothing. Options passed here are ignored with a v8 deprecation warning. +- `app.init(options)` is async. It builds the renderer, wires up plugins, and must complete before you can use `app.canvas`, `app.renderer`, or `app.screen`. +- The TickerPlugin calls `app.render()` every frame once init resolves (unless `autoStart: false`). +- `app.destroy(rendererDestroyOptions, stageDestroyOptions)` — the first argument forwards to `renderer.destroy()`. Pass `true` or `{ removeView: true }` to remove the canvas from the DOM. Add `releaseGlobalResources: true` to drain global pools (batches, texture caches) when tearing down and re-creating an app in the same tab; omitting it is the usual cause of flickering and stale textures after a re-init (see `pixijs-performance`). + +### Key init options + +```ts +await app.init({ + width: 800, + height: 600, + background: 0x1099bb, + backgroundAlpha: 1, + + antialias: true, + resolution: window.devicePixelRatio, + autoDensity: true, + + preference: "webgpu", + + autoStart: true, + sharedTicker: false, + + resizeTo: window, + + canvas: document.querySelector("#game-canvas") as HTMLCanvasElement, +}); +``` + +For every option — view/canvas, background, renderer preference (including the array form), ticker, resize, culler, events, accessibility, WebGL/WebGPU context flags, Graphics bezier smoothness, GC, and per-renderer overrides (`webgl` / `webgpu` / `canvasOptions`) — see [references/application-options.md](references/application-options.md). + +### Application properties + +```ts +app.stage; // root Container; add all display objects here +app.renderer; // the WebGL/WebGPU/Canvas renderer instance +app.canvas; // the HTMLCanvasElement (insert it into the DOM yourself) +app.screen; // Rectangle describing the visible area in CSS pixels +app.domContainerRoot; // HTMLDivElement that holds DOMContainer overlays +``` + +`app.stage` is a plain `Container`. For scene graph detail (transforms, addChild, destroy) see `pixijs-scene-container`. For renderer-level operations (extract, generateTexture, custom systems) see `pixijs-core-concepts` and `pixijs-custom-rendering`. `app.domContainerRoot` is the `
` that the renderer uses to host `DOMContainer` overlays; append it next to `app.canvas` when you need DOM elements pinned to scene nodes (see `pixijs-scene-dom-container`). + +### ResizePlugin + +Set `resizeTo` at init (or reassign `app.resizeTo` later) to have the plugin listen for the `resize` event and call `renderer.resize()` with the target element's client size. Combine with `autoDensity: true` and `resolution: window.devicePixelRatio` for high-DPI output. + +```ts +await app.init({ resizeTo: window }); + +app.resizeTo = document.querySelector("#game-container") as HTMLElement; + +app.resize(); // immediate resize to the target's current size +app.queueResize(); // defer the resize to the next animation frame +app.cancelResize(); // drop a pending queueResize +``` + +The plugin keeps the canvas matched to the target. `app.screen` and `app.canvas.width/height` update in response; read them after the resize to place UI. + +- `app.resize()` — immediate synchronous resize. +- `app.queueResize()` — coalesces rapid calls by deferring to the next frame; internally used by the `window.resize` listener to avoid redundant work. +- `app.cancelResize()` — cancels a queued resize. Call this before tearing down your own layout code that triggered `queueResize`. + +### Ticker basics + +The TickerPlugin creates `app.ticker` and registers `app.render()` on it at `UPDATE_PRIORITY.LOW`. Control the loop with `app.start()`/`app.stop()` and add callbacks with `app.ticker.add` / `app.ticker.addOnce`: + +```ts +app.ticker.add((ticker) => { + sprite.rotation += 0.01 * ticker.deltaTime; +}); + +app.ticker.addOnce(() => { + console.log("runs once on the next frame, then removes itself"); +}); + +app.stop(); // pause the render loop (e.g. tab hidden) +app.start(); // resume +``` + +The callback receives the `Ticker` instance; read `ticker.deltaTime` for a frame-rate-independent multiplier (~1.0 at 60fps), `ticker.deltaMS` for real milliseconds, or `ticker.FPS` for the current frame rate. See `pixijs-ticker` for priorities, FPS capping, `onRender`, shared vs private tickers, and the v8 callback signature change. + +### Manual render loop + +```ts +await app.init({ autoStart: false, width: 800, height: 600 }); +document.body.appendChild(app.canvas); + +function frame() { + updateScene(); + app.render(); + requestAnimationFrame(frame); +} +frame(); +``` + +`autoStart: false` prevents the TickerPlugin from starting the ticker automatically. Call `app.render()` yourself (or `app.renderer.render({ container: app.stage })` for the same effect). If you still want registered ticker callbacks to fire, call `app.ticker.update()` inside your loop before `app.render()`. + +### CullerPlugin (opt-in) + +The CullerPlugin skips rendering containers that fall outside `app.renderer.screen`. It isn't registered by default; add it before creating your app: + +```ts +import { + Application, + Container, + Sprite, + extensions, + CullerPlugin, + Rectangle, +} from "pixi.js"; + +extensions.add(CullerPlugin); + +const app = new Application(); +await app.init({ width: 800, height: 600 }); + +const world = new Container(); +world.cullable = true; // this container is culled when its bounds leave the screen +world.cullableChildren = true; // default; set `false` to skip recursing into children + +const tile = Sprite.from("tile.png"); +tile.cullable = true; +world.addChild(tile); +app.stage.addChild(world); +``` + +Containers are not culled unless `cullable` is set. Override the default bounds check with `container.cullArea = new Rectangle(x, y, w, h)` when child bounds are expensive to compute. The plugin wraps `app.render()` so `Culler.shared.cull(app.stage, app.renderer.screen)` runs before every frame. See `pixijs-performance` for when culling pays off. + +### Custom Application plugins + +Extend `Application` by registering a class with `static init`, `static destroy`, and `static extension = ExtensionType.Application`. Both methods are called with `this` bound to the Application instance, so `this.renderer` and `this.stage` are available. + +```ts +import { + Application, + ExtensionType, + extensions, + type ApplicationOptions, +} from "pixi.js"; + +class FpsOverlay { + public static extension = ExtensionType.Application; + + public static init(this: Application, options: Partial) { + // runs inside app.init() after the renderer is created + // attach props/methods to `this` to expose them on the app + } + + public static destroy(this: Application) { + // runs inside app.destroy() — tear down anything you attached + } +} + +extensions.add(FpsOverlay); +``` + +Plugins initialize in registration order and destroy in reverse. To add typed options for your plugin, extend `PixiMixins.ApplicationOptions`: + +```ts +declare global { + namespace PixiMixins { + interface ApplicationOptions { + fpsOverlay?: { visible?: boolean }; + } + } +} + +await app.init({ fpsOverlay: { visible: true } }); +``` + +The built-in `ResizePlugin`, `TickerPlugin`, and opt-in `CullerPlugin` all use this same contract. If you set `skipExtensionImports: true`, register the built-ins you need yourself (`extensions.add(ResizePlugin, TickerPlugin)`). + +## Common Mistakes + +### [CRITICAL] Passing options to the constructor + +Wrong: + +```ts +const app = new Application({ width: 800, height: 600 }); +document.body.appendChild(app.canvas); +``` + +Correct: + +```ts +const app = new Application(); +await app.init({ width: 800, height: 600 }); +document.body.appendChild(app.canvas); +``` + +In v8 the `Application` constructor takes no arguments. Options passed there are ignored and log a deprecation warning; the renderer is only created inside the async `init()` call. + + +### [HIGH] Using app.view instead of app.canvas + +Wrong: + +```ts +document.body.appendChild(app.view); +``` + +Correct: + +```ts +document.body.appendChild(app.canvas); +``` + +`app.view` was renamed to `app.canvas` in v8. The old getter still works but emits a deprecation warning. + + +### [MEDIUM] Touching app.canvas or app.renderer before init resolves + +Wrong: + +```ts +const app = new Application(); +document.body.appendChild(app.canvas); +app.init({ width: 800, height: 600 }); +``` + +Correct: + +```ts +const app = new Application(); +await app.init({ width: 800, height: 600 }); +document.body.appendChild(app.canvas); +``` + +`app.renderer`, `app.canvas`, and `app.screen` are only populated once the `init()` promise resolves. Accessing them earlier returns `undefined`. + + +## API Reference + +- [Application](https://pixijs.download/release/docs/app.Application.html.md) +- [ApplicationOptions](https://pixijs.download/release/docs/app.ApplicationOptions.html.md) +- [ApplicationPlugin](https://pixijs.download/release/docs/app.ApplicationPlugin.html.md) +- [ResizePlugin](https://pixijs.download/release/docs/app.ResizePlugin.html.md) +- [ResizePluginOptions](https://pixijs.download/release/docs/app.ResizePluginOptions.html.md) +- [TickerPlugin](https://pixijs.download/release/docs/app.TickerPlugin.html.md) +- [TickerPluginOptions](https://pixijs.download/release/docs/app.TickerPluginOptions.html.md) +- [CullerPlugin](https://pixijs.download/release/docs/app.CullerPlugin.html.md) +- [autoDetectRenderer](https://pixijs.download/release/docs/rendering.autoDetectRenderer.html.md) diff --git a/.agents/skills/pixijs-application/references/application-options.md b/.agents/skills/pixijs-application/references/application-options.md new file mode 100644 index 0000000..1eb109b --- /dev/null +++ b/.agents/skills/pixijs-application/references/application-options.md @@ -0,0 +1,314 @@ +# ApplicationOptions reference + +Every option accepted by `app.init(options)`. Options come from three type sources merged into a single interface: + +- `AutoDetectOptions` → base renderer options (width/height/resolution/etc.) +- `PixiMixins.ApplicationOptions` → plugin options (`resizeTo`, `autoStart`, `sharedTicker`, `culler`) +- System defaults → each renderer system (background, view, hello, GC, context, backbuffer, events, graphics) contributes its own options + +Options with no default are unset unless you pass them. `Partial` means everything is optional. + + +## View / canvas + +Configures the main canvas and how it maps to CSS pixels. + +| Option | Type | Default | Description | +| ------------- | --------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `width` | `number` | `800` | Initial width in CSS pixels. | +| `height` | `number` | `600` | Initial height in CSS pixels. | +| `canvas` | `ICanvas` | — | Existing `HTMLCanvasElement` (or `OffscreenCanvas`) to render into instead of creating one. | +| `view` | `ICanvas` | — | **Deprecated since 8.0.0.** Alias for `canvas`. | +| `resolution` | `number` | `1` | Device pixel ratio. Set to `window.devicePixelRatio` for HiDPI. | +| `autoDensity` | `boolean` | `false` | Scale CSS dimensions of the canvas so `width`/`height` stay in CSS pixels while the backing store matches `resolution`. Only honored on `HTMLCanvasElement` (ignored on `OffscreenCanvas`). | +| `antialias` | `boolean` | `false` | GPU MSAA where supported. On WebGL, this only affects the main context — use `useBackBuffer: true` if you need antialiased filtering. | +| `depth` | `boolean` | — | Allocate a depth buffer for the main view. Always on for WebGL; needed for z-ordered rendering. | +| `transient` | `boolean` | `false` | WebGPU only, with `antialias`. Discard the canvas's multisample depth/stencil buffer at the end of each pass, and its colour buffer on GPUs that aren't tile-based (tile-based GPUs already discard colour). Only for apps that never reopen the canvas pass while still needing depth or stencil: no filters or masks popping back onto it, no render with `clear: false`. | + +```ts +await app.init({ + width: 1280, + height: 720, + resolution: window.devicePixelRatio, + autoDensity: true, + antialias: true, +}); +``` + +## Background + +Controls the clear color applied each frame. + +| Option | Type | Default | Description | +| ------------------- | ------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `backgroundColor` | `ColorSource` | `0x000000` | Canvas clear color. Accepts hex, CSS string, `[r, g, b, a]`, or any `ColorSource`. | +| `background` | `ColorSource` | — | Alias for `backgroundColor`. If both are set, `background` wins. | +| `backgroundAlpha` | `number` | `1` | Clear alpha, `0`–`1`. **Cannot be changed after init** — the backing canvas is allocated with or without alpha support based on this value. Set `< 1` now if you may ever need transparency. | +| `clearBeforeRender` | `boolean` | `true` | Clear the target before each frame. Disable only if you're drawing a full-frame background yourself (e.g. a full-screen sprite). | + +```ts +await app.init({ + backgroundColor: 0x1099bb, + backgroundAlpha: 1, +}); +``` + +## Renderer preference + +Picks which renderer gets created. + +| Option | Type | Default | Description | +| --------------- | --------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `preference` | `'webgl' \| 'webgpu' \| 'canvas' \| RendererPreference[]` | `'webgl'` | Pick a preferred renderer. String = try first, then fall back through the default priority (`webgl` → `webgpu` → `canvas`). Array = try only the listed renderers, in order (acts as a blocklist too — anything not listed is excluded). See ["Array form"](#preference-array-form) below. | +| `webgl` | `Partial` | — | Options applied **only** when the WebGL renderer is selected. Merged over the top-level options. | +| `webgpu` | `Partial` | — | Options applied **only** when the WebGPU renderer is selected. | +| `canvasOptions` | `Partial` | — | Options applied **only** when the Canvas2D renderer is selected. | + +### preference: array form + +Passing an array to `preference` restricts `autoDetectRenderer` to exactly the listed renderers, in the given order. Any renderer not in the array is **excluded entirely** — the array doubles as a blocklist. + +```ts +// Try WebGPU first, then fall back to WebGL. Never use Canvas2D. +await app.init({ preference: ["webgpu", "webgl"] }); + +// Only ever use Canvas2D (e.g. in a WebGL-disabled environment). +await app.init({ preference: ["canvas"] }); + +// Skip WebGPU entirely while keeping the default webgl → canvas fallback order. +await app.init({ preference: ["webgl", "canvas"] }); +``` + +Contrast with the string form, which falls through the **full** default priority if the first choice fails: + +```ts +// Tries webgpu, then webgl, then canvas — all three are candidates. +await app.init({ preference: "webgpu" }); +``` + +Use the array when you need to guarantee a renderer is never picked (e.g. WebGPU is broken on a target device, or you want to forbid Canvas2D's feature subset). + + +## Shared rendering + +Apply to every renderer type. + +| Option | Type | Default | Description | +| ------------------------------ | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `roundPixels` | `boolean` | `false` | Round vertex positions to whole pixels at shader time. Eliminates subpixel shimmer for pixel-art but blurs smooth motion. | +| `skipExtensionImports` | `boolean` | `false` | Disable automatic import of default extensions. With `true`, import the subsystems you need manually (`import 'pixi.js/accessibility'`, `'pixi.js/app'`, `'pixi.js/events'`, …). Renderer loader extensions (`WebGLLoader`/`WebGPULoader`/`CanvasLoader`) are skipped too, so import any backend-specific plugin modules yourself. Used for custom tree-shaken builds. | +| `hello` | `boolean` | `false` | Log the PixiJS version and renderer type banner to the console on init. | +| `failIfMajorPerformanceCaveat` | `boolean` | `false` | Fail WebGL context creation if the browser reports major performance issues (blocklisted GPU, software fallback). Set `true` for high-performance apps that should refuse slow paths. | + +```ts +await app.init({ + roundPixels: true, + hello: true, +}); +``` + +## Graphics + +Graphics rendering options. + +| Option | Type | Default | Description | +| ------------------ | -------- | ------- | ------------------------------------------------------------------------------------------ | +| `bezierSmoothness` | `number` | `0.5` | Controls curve tessellation for Graphics bezier paths. Higher = smoother (more triangles). | + +```ts +await app.init({ + bezierSmoothness: 0.75, +}); +``` + +## Ticker (TickerPluginOptions) + +Controls the built-in render loop. + +| Option | Type | Default | Description | +| -------------- | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `autoStart` | `boolean` | `true` | Start the render loop automatically after `init()` resolves. Setting `false` disables `app.render()` being called each frame, but **does not** stop `Ticker.shared` if you've opted into `sharedTicker: true`. | +| `sharedTicker` | `boolean` | `false` | Use `Ticker.shared` instead of creating a per-Application ticker. Useful for syncing multiple apps; loses per-app control over start/stop. | + +See `pixijs-ticker` for the ticker API itself. + +```ts +await app.init({ + autoStart: false, + sharedTicker: false, +}); + +function loop() { + app.renderer.render(app.stage); + requestAnimationFrame(loop); +} +loop(); +``` + +## Resize (ResizePluginOptions) + +| Option | Type | Default | Description | +| ---------- | ----------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `resizeTo` | `Window \| HTMLElement` | `null` | Element the renderer should auto-resize to match. `window` resizes to the viewport; an element uses `clientWidth`/`clientHeight`. Leave `null` to opt out of auto-resize. | + +The plugin listens for `resize` events on `window` and calls `renderer.resize()`. You can reassign `app.resizeTo` at runtime, and call `app.resize()`, `app.queueResize()`, or `app.cancelResize()` from user code. + +```ts +await app.init({ + resizeTo: window, +}); +``` + +## Culler (CullerPluginOptions) + +Opt-in plugin (must `extensions.add(CullerPlugin)` to activate). + +| Option | Type | Default | Description | +| ------------------------ | --------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `culler.updateTransform` | `boolean` | `false` (effectively) | Must be explicitly set to `true` to run transform updates before culling. Otherwise PixiJS skips transform updates, and cull bounds may lag one frame for moving objects. | + +```ts +import { CullerPlugin, extensions } from "pixi.js"; + +extensions.add(CullerPlugin); + +await app.init({ + culler: { updateTransform: true }, +}); +``` + +## Events + +| Option | Type | Default | Description | +| -------------------------- | -------------------------------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `eventMode` | `'none' \| 'passive' \| 'auto' \| 'static' \| 'dynamic'` | `'passive'` | Default interaction mode for every container. See `pixijs-events`. | +| `eventFeatures.move` | `boolean` | `true` | Fire `pointermove`/`mousemove`/`touchmove` + `pointerover`/`pointerout`. | +| `eventFeatures.globalMove` | `boolean` | `true` | Fire `globalpointermove`/`globalmousemove`/`globaltouchmove` regardless of hit target. Expensive; turn off if you don't need it. | +| `eventFeatures.click` | `boolean` | `true` | Fire `pointerdown`/`pointerup`/`click`/`tap`. | +| `eventFeatures.wheel` | `boolean` | `true` | Fire `wheel`. | + +```ts +await app.init({ + eventMode: "static", + eventFeatures: { + move: true, + globalMove: false, + click: true, + wheel: true, + }, +}); +``` + +## Accessibility + +Accessibility options. Pass these on the top-level init options. + +| Option | Type | Default | Description | +| -------------------------------------------- | --------- | ------- | ----------------------------------------------------------------------------- | +| `accessibilityOptions.enabledByDefault` | `boolean` | `false` | Enable accessibility overlays immediately instead of waiting for the Tab key. | +| `accessibilityOptions.debug` | `boolean` | `false` | Show the accessibility overlay divs visibly for debugging. | +| `accessibilityOptions.activateOnTab` | `boolean` | `true` | Activate overlays when the user presses Tab. | +| `accessibilityOptions.deactivateOnMouseMove` | `boolean` | `true` | Deactivate overlays when the mouse moves. | + +See `pixijs-accessibility` for the full accessibility API. + +```ts +await app.init({ + accessibilityOptions: { + enabledByDefault: true, + activateOnTab: true, + deactivateOnMouseMove: true, + }, +}); +``` + +## WebGL-only options + +Applied when the WebGL renderer is selected. + +| Option | Type | Default | Description | +| ----------------------- | ----------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `context` | `WebGL2RenderingContext \| null` | `null` | Use this existing WebGL context instead of creating one. Useful for hand-managing the context or integrating with other renderers. | +| `powerPreference` | `'high-performance' \| 'low-power'` | `undefined` | Hint the browser which GPU to pick on multi-GPU systems. If omitted, PixiJS internally passes `'default'` to the GPU context; `'default'` is not settable from user code. | +| `premultipliedAlpha` | `boolean` | `true` | Tell the compositor the drawing buffer contains premultiplied-alpha colors. Changing this affects blending math. | +| `preserveDrawingBuffer` | `boolean` | `false` | Keep the drawing buffer between frames. Required if you need `canvas.toDataURL()` or `canvas.toBlob()` to capture arbitrary frames. | +| `preferWebGLVersion` | `1 \| 2` | `2` | Preferred WebGL version. PixiJS v8 was designed for WebGL2 — WebGL1 is a legacy fallback. | +| `multiView` | `boolean` | `false` | Enable rendering to multiple canvases from one renderer. | +| `useBackBuffer` | `boolean` | `false` | Render to an intermediate texture instead of directly to the canvas. Required for advanced blend modes and filters that sample the backdrop. Enables `antialias` on the back buffer independently from the main context. | + +```ts +await app.init({ + preference: "webgl", + webgl: { + preferWebGLVersion: 2, + useBackBuffer: true, + powerPreference: "high-performance", + }, +}); +``` + +## WebGPU-only options + +| Option | Type | Default | Description | +| ---------------------- | ----------------------------------- | ----------- | ----------------------------------------------------------------------------------------------- | +| `powerPreference` | `'high-performance' \| 'low-power'` | `undefined` | Hint for `requestAdapter()`. | +| `forceFallbackAdapter` | `boolean` | `false` | Force the software/fallback adapter. For testing only. | +| `gpu` | `{ adapter, device }` | — | Use a pre-created `GPUAdapter` + `GPUDevice` pair. Useful for sharing a device between engines. | + +```ts +await app.init({ + preference: ["webgpu", "webgl"], + webgpu: { + powerPreference: "high-performance", + }, +}); +``` + +## Garbage collection + +All time values are milliseconds. + +| Option | Type | Default | Description | +| ----------------- | --------- | ------- | ------------------------------------------------------------ | +| `gcActive` | `boolean` | `true` | Enable the unified renderer garbage collector. | +| `gcMaxUnusedTime` | `number` | `60000` | How long a resource can go unused before the GC collects it. | +| `gcFrequency` | `number` | `30000` | How often the GC sweep runs. | + +### Deprecated (GC — prefer the unified options above) + +`TextureGCSystem` and `RenderableGCSystem` still accept these, but they've been deprecated since 8.15.0 in favor of `gcActive`/`gcMaxUnusedTime`/`gcFrequency`. Passing them still works for the deprecation window but logs warnings. + +| Option | Deprecated since | Replacement | +| --------------------------- | ---------------- | ----------------------------------------------------------- | +| `textureGCActive` | 8.15.0 | `gcActive` | +| `textureGCMaxIdle` | 8.15.0 | `gcMaxUnusedTime` (note: this is frames; the new API is ms) | +| `textureGCCheckCountMax` | 8.15.0 | `gcFrequency` (frames → ms) | +| `textureGCAMaxIdle` | 8.3.0 | `textureGCMaxIdle` (typo fix) → now `gcMaxUnusedTime` | +| `renderableGCActive` | 8.15.0 | `gcActive` | +| `renderableGCMaxUnusedTime` | 8.15.0 | `gcMaxUnusedTime` | +| `renderableGCFrequency` | 8.15.0 | `gcFrequency` | + +```ts +await app.init({ + gcActive: true, + gcMaxUnusedTime: 60_000, + gcFrequency: 30_000, +}); +``` + +## Per-renderer overrides + +`webgl`, `webgpu`, and `canvasOptions` are merged over the top-level options once the selected renderer is known: + +```ts +await app.init({ + antialias: false, + webgl: { antialias: true, useBackBuffer: true }, + webgpu: { antialias: true }, + canvasOptions: { + /* canvas-specific */ + }, +}); +``` + +If WebGL wins, the renderer sees `antialias: true` + `useBackBuffer: true`. If WebGPU wins, just `antialias: true`. The three sub-keys are stripped before the options reach the renderer. diff --git a/.agents/skills/pixijs-assets/SKILL.md b/.agents/skills/pixijs-assets/SKILL.md new file mode 100644 index 0000000..004e641 --- /dev/null +++ b/.agents/skills/pixijs-assets/SKILL.md @@ -0,0 +1,303 @@ +--- +name: pixijs-assets +description: "Use this skill when loading and managing resources in PixiJS v8. Covers Assets.init, Assets.load/add/unload, bundles, manifests, background loading, onProgress, caching, spritesheets, video textures, web fonts, bitmap fonts, animated GIFs, compressed textures, SVG as texture or Graphics, resolution detection, per-asset data options, and forcing a specific loader with the parser field (for extension-less URLs). Triggers on: Assets, Assets.load, Assets.init, loadBundle, manifest, backgroundLoad, Spritesheet, Cache, LoadOptions, unload, parser, loadParser, loadWebFont, loadBitmapFont, loadVideoTextures, GifSource, VideoSourceOptions." +license: MIT +--- + +The `Assets` API is PixiJS's asset loader, resolver, and cache in one singleton. Use it to load textures, video, spritesheets, fonts, JSON, and other resources with format detection, resolution switching, bundle grouping, progress tracking, and GPU cleanup. + +## Quick Start + +```ts +await Assets.init({ basePath: "/static/" }); + +const texture = await Assets.load("bunny.png"); +const sprite = new Sprite(texture); +app.stage.addChild(sprite); + +const [hero, enemy] = await Assets.load(["hero.png", "enemy.png"]); + +await Assets.load({ + alias: "logo", + src: "logo.webp", +}); + +const logo = new Sprite(Assets.get("logo")); +``` + +`Assets.init()` is optional but recommended for setting `basePath`, `texturePreference`, or a manifest. After init, call `Assets.load()` with a URL, alias, array, or `UnresolvedAsset`; resolved assets are cached and re-resolved by `Assets.get()`. + +## Supported file types + +| Type | Extensions | Parser ID | Loader | +| ------------------- | ---------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| Textures | `.png`, `.jpg`, `.jpeg`, `.webp`, `.avif` | `texture` | `loadTextures` | +| SVG | `.svg` | `svg` | `loadSvg` (see `references/svg.md`) | +| Video textures | `.mp4`, `.m4v`, `.webm`, `.ogg`, `.ogv`, `.h264`, `.avi`, `.mov` | `video` | `loadVideoTextures` (see `references/video.md`) | +| Sprite sheets | `.json` (Spritesheet format) | `spritesheet` | `spritesheetAsset` (see `references/spritesheet.md`) | +| Bitmap fonts | `.fnt`, `.xml` | `bitmap-font` | `loadBitmapFont` (loading works by default; rendering `BitmapText` requires `'pixi.js/text-bitmap'`; see `references/fonts.md`) | +| Web fonts | `.ttf`, `.otf`, `.woff`, `.woff2` | `web-font` | `loadWebFont` (see `references/fonts.md`) | +| JSON | `.json` | `json` | `loadJson` | +| Text | `.txt` | `text` | `loadTxt` | +| Compressed textures | `.basis`, `.dds`, `.ktx`, `.ktx2` | `basis`, `dds`, `ktx`, `ktx2` | See `references/compressed-textures.md` | +| Animated GIFs | `.gif` | `gif` | Requires `'pixi.js/gif'`; returns `GifSource` (see `references/gif.md`) | + +The **Parser ID** column is the value you pass to the top-level `parser` field on an asset descriptor to force a specific loader. See "Forcing a parser" below. + +## Forcing a parser with `parser` + +By default, PixiJS picks a loader by matching the file extension or MIME type. When your URL lacks an extension (CDN signed URLs, blob URLs, API endpoints, content-hashed paths), the resolver can't tell the loader what to do. Set the top-level `parser` field on the asset descriptor to force a specific loader: + +```ts +// Signed CDN URL with no extension +const texture = await Assets.load({ + src: "https://cdn.example.com/signed/abc123?token=xyz", + parser: "texture", +}); + +// API endpoint that returns JSON +const data = await Assets.load({ + alias: "config", + src: "https://api.example.com/v1/config", + parser: "json", +}); + +// Extension-less font URL with explicit family +await Assets.load({ + src: "https://cdn.example.com/fonts/hero-v2", + parser: "web-font", + data: { family: "Hero", weights: ["400", "700"] }, +}); + +// Video stream without a file extension +const clipTexture = await Assets.load({ + src: "https://cdn.example.com/stream/xyz", + parser: "video", + data: { mime: "video/mp4", muted: true, playsinline: true }, +}); +``` + +The `parser` field goes at the top level of the asset descriptor (alongside `src` and `data`), not inside `data`. It takes any parser ID from the "Supported file types" table above: + +- `'texture'`, `'svg'`, `'video'`: image, SVG, and video textures +- `'json'`, `'text'`: JSON and plain text +- `'web-font'`, `'bitmap-font'`: web and bitmap fonts +- `'spritesheet'`: texture atlas JSON +- `'gif'`: animated GIFs (requires `'pixi.js/gif'`) +- `'basis'`, `'dds'`, `'ktx'`, `'ktx2'`: compressed textures (each requires its side-effect import) + +### When you need it + +- **Signed CDN URLs**: `https://cdn.example.com/get?id=abc123` has no extension the loader can test against. +- **Blob or ObjectURL**: `URL.createObjectURL(blob)` produces `blob:...` URLs with no extension. +- **Custom routing**: `/api/assets/hero-v2` where the server decides the content type. +- **Content-hashed paths without suffix**: some build pipelines produce names like `/static/abc123def` instead of `/static/abc123def.png`. + +If the URL _does_ have an extension, you don't need `parser`; let auto-detection do its job. Only set `parser` when detection can't work. + +### `loadParser` is deprecated + +The v7 `loadParser` field still works but emits a deprecation warning. Use `parser` for new code. + +```ts +// Old (deprecated) +await Assets.load({ src: "...", loadParser: "loadTextures" }); + +// New +await Assets.load({ src: "...", parser: "texture" }); +``` + +## Topics + +Every asset workflow is covered in a reference file. Pick the one that matches the question: + +| Topic | Reference | When | +| ------------------------------ | ---------------------------------------------------------------------- | ------------------------------------------- | +| Texture atlases and animations | [references/spritesheet.md](references/spritesheet.md) | Loading sprite sheets with `AnimatedSprite` | +| Video textures | [references/video.md](references/video.md) | `.mp4`, `.webm`, autoplay, looping, mobile | +| Web and bitmap fonts | [references/fonts.md](references/fonts.md) | `.woff2`, `.fnt`, font families, SDF fonts | +| Animated GIFs | [references/gif.md](references/gif.md) | `.gif`, `GifSprite`, playback control | +| Grouping assets by feature | [references/bundles.md](references/bundles.md) | `addBundle`, `loadBundle`, `unloadBundle` | +| Declaring everything upfront | [references/manifests.md](references/manifests.md) | `Assets.init({ manifest })` workflows | +| Cache lookups and cleanup | [references/caching.md](references/caching.md) | `Assets.get`, `Assets.unload`, `Cache` | +| Priming future assets | [references/background.md](references/background.md) | `backgroundLoad`, `backgroundLoadBundle` | +| Loading screens | [references/progress.md](references/progress.md) | `onProgress`, LoadOptions progress | +| GPU-compressed formats | [references/compressed-textures.md](references/compressed-textures.md) | `.ktx2`, `.basis`, `.dds`, `.ktx` | +| Vector vs raster SVG | [references/svg.md](references/svg.md) | `parseAsGraphicsContext`, texture mode | +| Retina + format detection | [references/resolution.md](references/resolution.md) | `@{1,2}x`, `format` preferences | + +## Decision guide + +- **Need to load a single image?** Use `Assets.load(url)`. No setup required. +- **Loading many assets grouped by level/scene?** Use a bundle. See `references/bundles.md`. +- **Know all assets at build time?** Use a manifest in `Assets.init`. See `references/manifests.md`. +- **Need a loading bar?** Pass a progress callback to `Assets.load`. See `references/progress.md`. +- **Smooth transitions between levels?** Background-load the next level. See `references/background.md`. +- **Memory budget matters?** Use compressed textures and `Assets.unload` between screens. See `references/compressed-textures.md` and `references/caching.md`. +- **Need crisp SVG icons at any size?** Load as Graphics, not texture. See `references/svg.md`. +- **Retina + WebP/AVIF?** Configure `texturePreference` and use format patterns. See `references/resolution.md`. + +## Load options and error handling + +There are two separate "options" concepts when loading assets: + +1. **`LoadOptions`**: the second argument to `Assets.load`/`loadBundle`. Controls error recovery, retries, progress, and completion callbacks across a whole load. +2. **`data`**: a field on each asset descriptor. Forwards parser-specific options (scale mode, resolution, font family, autoplay flags, etc.) to the specific loader for that asset. + +### LoadOptions (per call) + +```ts +await Assets.load(["hero.png", "enemy.png"], { + onProgress: (p) => updateBar(p), + onError: (err, url) => { + const src = typeof url === "string" ? url : url.src; + console.warn("failed:", src, err); + }, + strategy: "retry", + retryCount: 3, + retryDelay: 250, +}); +``` + +- `onProgress(progress)`: `[0, 1]` as assets in the call complete. +- `onError(error, url)`: `url` is `string | ResolvedAsset`. Guard before reading `.src`; when `url` is a string, `.src` is undefined. +- `strategy: 'throw' | 'skip' | 'retry'` — default `'throw'`. `'skip'` resolves with any successful assets; `'retry'` reattempts the failed ones. +- `retryCount` — default `3`, retries per asset when `strategy` is `'retry'`. +- `retryDelay` — default `250` ms between retries. + +Global defaults live on `Loader.defaultOptions`, or pass `loadOptions` to `Assets.init()`. + +### `data` options (per asset) + +Each loader parser reads its own options from the `data` field on the asset descriptor. Use the table below to pick the right options for each asset type: + +| Asset type | `data` shape | Key options | Reference | +| ------------------ | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | +| Texture (image) | `TextureSourceOptions` | `resolution`, `scaleMode`, `alphaMode`, `autoGenerateMipmaps`, `antialias`, `addressMode` | `references/resolution.md` | +| SVG | `{ parseAsGraphicsContext?, resolution? }` | `parseAsGraphicsContext` for Graphics mode; `resolution` for sharper raster | `references/svg.md` | +| Video | `VideoSourceOptions` | `autoPlay`, `loop`, `muted`, `playsinline`, `preload`, `updateFPS`, `crossorigin`, `mime` | `references/video.md` | +| Web font | `LoadFontData` | `family`, `weights`, `style`, `display`, `unicodeRange`, `featureSettings` | `references/fonts.md` | +| Bitmap font | (none; auto-configured) | Distance-field detection sets scale mode and mipmaps | `references/fonts.md` | +| Spritesheet | `{ texture?, imageFilename?, ignoreMultiPack?, textureOptions?, cachePrefix? }` | `textureOptions` forwards `TextureSourceOptions` (e.g. `scaleMode`) to the atlas image; `texture` to skip image load; `imageFilename` to override the referenced image; `ignoreMultiPack` to skip multi-pack follow-ups; `cachePrefix` to namespace frames | `references/spritesheet.md` | +| GIF | `GifBufferOptions` | `fps`, `scaleMode`, `resolution`, `autoGenerateMipmaps` | `references/gif.md` | +| Compressed texture | `TextureSourceOptions` | `scaleMode`, `addressMode`, `autoGenerateMipmaps` | `references/compressed-textures.md` | +| JSON / Text | (none) | Returned as-is | — | + +Example combining `LoadOptions` and `data`: + +```ts +await Assets.load( + { + alias: "hero", + src: "hero.png", + data: { scaleMode: "nearest", resolution: 2 }, + }, + { strategy: "retry", retryCount: 3 }, +); +``` + +Inside a manifest or bundle, every entry can carry its own `data`: + +```ts +await Assets.init({ + manifest: { + bundles: [ + { + name: "level1", + assets: [ + { alias: "tiles", src: "tiles.png", data: { scaleMode: "nearest" } }, + { alias: "font", src: "hero.woff2", data: { family: "Hero" } }, + { + alias: "clip", + src: "intro.mp4", + data: { autoPlay: false, muted: true }, + }, + ], + }, + ], + }, +}); +``` + +## Runtime configuration + +`Assets.init(options)` accepts, alongside `basePath` and `manifest`: + +- `defaultSearchParams` — string or `Record` appended to every resolved URL. Useful for cache busting. +- `skipDetections: boolean` — bypass browser format detection for faster init. Requires explicit `texturePreference.format`. +- `bundleIdentifier: BundleIdentifierOptions` — customize how bundle keys resolve so the same alias can live in multiple bundles. +- `loadOptions: Partial` — set the default `strategy`, `retryCount`, `retryDelay`, and callbacks for every subsequent `Assets.load` call. +- `preferences: Partial` — `crossOrigin`, `preferWorkers`, `preferCreateImageBitmap`, `parseAsGraphicsContext`. + +After init, preferences can still be tuned: + +```ts +Assets.setPreferences({ + crossOrigin: "anonymous", + preferCreateImageBitmap: false, +}); + +for (const detection of Assets.detections) { + console.log(detection.extension); +} + +Assets.reset(); +``` + +- `Assets.setPreferences(preferences)` — push new preferences to every parser that supports them. +- `Assets.detections` — getter exposing the registered `FormatDetectionParser` list; use when inspecting what formats the current environment advertises. +- `Assets.reset()` — internal full reset (resolver + loader + cache). Intended for tests so a fresh `Assets.init` can run. + +## Common Mistakes + +### [CRITICAL] Using `Texture.from(url)` to load + +Wrong: + +```ts +const texture = Texture.from("https://example.com/image.png"); +``` + +Correct: + +```ts +const texture = await Assets.load("https://example.com/image.png"); +``` + +In v8, `Texture.from()` only reads the cache. It does not fetch from a URL. Use `Assets.load()` first; the return value is the texture itself. + + +### [HIGH] Using positional `Assets.add` signature + +Wrong: + +```ts +Assets.add("bunny", "bunny.png"); +``` + +Correct: + +```ts +Assets.add({ alias: "bunny", src: "bunny.png" }); +``` + +The positional `Assets.add(key, url)` form was removed in v8. Use the options object with `alias` and `src` properties. + + +### [HIGH] Not unloading textures between levels + +`Assets.load()` caches textures indefinitely. For level-based games or screens with distinct asset sets, call `Assets.unloadBundle()` when transitioning to release GPU memory. + + +## API Reference + +- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md) +- [Loader](https://pixijs.download/release/docs/assets.Loader.html.md) +- [Resolver](https://pixijs.download/release/docs/assets.Resolver.html.md) +- [Cache](https://pixijs.download/release/docs/assets.Cache.html.md) +- [LoadOptions](https://pixijs.download/release/docs/assets.LoadOptions.html.md) +- [AssetInitOptions](https://pixijs.download/release/docs/assets.AssetInitOptions.html.md) +- [AssetsManifest](https://pixijs.download/release/docs/assets.AssetsManifest.html.md) +- [AssetsBundle](https://pixijs.download/release/docs/assets.AssetsBundle.html.md) +- [BackgroundLoader](https://pixijs.download/release/docs/assets.BackgroundLoader.html.md) +- [Spritesheet](https://pixijs.download/release/docs/assets.Spritesheet.html.md) diff --git a/.agents/skills/pixijs-assets/references/background.md b/.agents/skills/pixijs-assets/references/background.md new file mode 100644 index 0000000..8cb7a36 --- /dev/null +++ b/.agents/skills/pixijs-assets/references/background.md @@ -0,0 +1,137 @@ +# Background Loading + +Background loading lets PixiJS fetch and prepare assets passively while other work happens. Use it to prime the next level while the current one is playing, preload assets during a splash screen, or prepare UI assets during initial load. `backgroundLoad` and `backgroundLoadBundle` are non-blocking and return immediately. + +## Quick Start + +```ts +await Assets.loadBundle("menu"); +showMenu(); + +Assets.backgroundLoadBundle("level1"); + +playerClicksStart(() => { + Assets.loadBundle("level1").then(() => startLevel()); +}); +``` + +The `backgroundLoadBundle` call starts loading `level1` immediately without blocking. The later `loadBundle` call resolves quickly if background loading finished in the meantime. + +## Core Patterns + +### Background-loading a single asset + +```ts +Assets.backgroundLoad("images/level2-assets.png"); + +// later, when we need it: +const texture = await Assets.load("images/level2-assets.png"); +``` + +Fire-and-forget. Background loading happens one asset at a time to avoid blocking the main thread. When your code later calls `Assets.load(url)` for the same asset, it either resolves immediately (if background work finished) or waits for the already-in-progress load. + +### Background-loading an array + +```ts +Assets.backgroundLoad([ + "images/sprite1.png", + "images/sprite2.png", + "images/background.png", +]); +``` + +Queues multiple assets for background loading. They're processed sequentially. + +### Background-loading a bundle + +```ts +await Assets.init({ + manifest: { + bundles: [ + { name: "home", assets: [{ alias: "bg", src: "home-bg.png" }] }, + { name: "level-1", assets: [{ alias: "map", src: "level1-map.json" }] }, + ], + }, +}); + +await Assets.loadBundle("home"); +showHome(); + +Assets.backgroundLoadBundle("level-1"); + +onPlayClicked(async () => { + await Assets.loadBundle("level-1"); + startLevel(); +}); +``` + +Same idea for bundles. Bundle assets are queued one at a time. Requires the bundle to exist via the manifest or `addBundle`. + +### Interrupting background loading + +```ts +Assets.backgroundLoadBundle("level-2"); + +onPlayerDecidedLevel3(async () => { + await Assets.loadBundle("level-3"); +}); +``` + +Calling `Assets.load()` or `Assets.loadBundle()` interrupts background loading safely. The current background asset finishes, then the explicit load takes priority. Your explicit load resolves normally. + +### Combining with a progress bar + +Background loading has no progress callback; it runs silently. To show a loading bar, use `Assets.loadBundle(name, onProgress)` in the foreground instead. Typical pattern: use background loading for nice-to-have preloads and foreground loading for the bundles you're actually waiting on. + +## Common Mistakes + +### [HIGH] Expecting progress from background loading + +Wrong: + +```ts +Assets.backgroundLoadBundle("level2", (p) => updateBar(p)); +``` + +Correct: + +```ts +Assets.backgroundLoadBundle("level2"); +// show a spinner or no UI while it runs +``` + +`backgroundLoad` and `backgroundLoadBundle` don't accept progress callbacks. They're silent. For visible progress, use the foreground `Assets.load` / `Assets.loadBundle` with an `onProgress` argument. + + +### [MEDIUM] Assuming background load completes before next foreground load + +Wrong: + +```ts +Assets.backgroundLoadBundle("level-2"); +setTimeout(() => startLevel2(), 0); +``` + +Correct: + +```ts +Assets.backgroundLoadBundle("level-2"); + +onStart(async () => { + await Assets.loadBundle("level-2"); + startLevel2(); +}); +``` + +Background loading is best-effort. If the player hits Start before it finishes, the foreground `loadBundle` still needs to await the remaining work. Always `await` the real load before using the assets. + + +### [MEDIUM] Background-loading assets that are never used + +Each queued background load consumes bandwidth and GPU memory. If the player never visits level 2, you've wasted that bandwidth. Background-load only what you're confident will be needed soon. + + +## API Reference + +- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md) +- [BackgroundLoader](https://pixijs.download/release/docs/assets.BackgroundLoader.html.md) diff --git a/.agents/skills/pixijs-assets/references/bundles.md b/.agents/skills/pixijs-assets/references/bundles.md new file mode 100644 index 0000000..39ae384 --- /dev/null +++ b/.agents/skills/pixijs-assets/references/bundles.md @@ -0,0 +1,122 @@ +# Bundles + +A bundle is a named group of assets you can load or unload as a unit. Use bundles to batch assets per game level, UI screen, or feature so that a single `loadBundle(name)` call resolves everything needed for that context. Bundles play well with background loading and manifest-based workflows. + +## Quick Start + +```ts +Assets.addBundle("level1", [ + { alias: "bg", src: "level1/background.png" }, + { alias: "tileset", src: "level1/tiles.json" }, + { alias: "theme", src: "level1/music.mp3" }, +]); + +const resources = await Assets.loadBundle("level1"); +const bg = Sprite.from("bg"); +``` + +`loadBundle(name)` returns a `Record`. Each alias is also available via `Assets.get(alias)` after the bundle resolves. + +## Core Patterns + +### Programmatic bundles + +```ts +Assets.addBundle("ui", [ + { alias: "button", src: "ui/button.png" }, + { alias: "panel", src: "ui/panel.png" }, + { alias: "cursor", src: "ui/cursor.png" }, +]); + +await Assets.loadBundle("ui"); +``` + +`addBundle(name, assets)` registers a bundle at runtime. The assets array uses the same `{ alias, src, data? }` shape as `Assets.add()`. + +### Loading multiple bundles at once + +```ts +await Assets.loadBundle(["ui", "level1", "sounds"]); +``` + +Pass an array of bundle names to load them in parallel. The returned object is keyed by bundle name: `{ ui: {...}, level1: {...}, sounds: {...} }`. + +### Progress across a bundle + +```ts +await Assets.loadBundle("level1", (progress) => { + loadingBar.width = progress * maxBarWidth; +}); +``` + +The second argument is a `ProgressCallback` that fires as each asset in the bundle completes. Progress is normalized `[0, 1]` across the entire bundle. + +### Unloading a bundle + +```ts +await Assets.unloadBundle("level1"); +``` + +Tears down every asset in the bundle, releases GPU memory, and removes cached entries. Remove any Sprites or Text that reference the bundle's textures before unloading. + +### Sharing assets between bundles + +```ts +Assets.addBundle("main", [{ alias: "hero", src: "hero.png" }]); +Assets.addBundle("bossArea", [{ alias: "hero", src: "hero.png" }]); +``` + +If two bundles declare the same alias with the same `src`, the underlying texture is loaded once and shared. There is no reference counting: unloading either bundle destroys the shared texture, and the other bundle's alias stays broken until you reload it. + +### Bundle IDs + +```ts +const resources = await Assets.loadBundle("level1"); +const bg = resources["bg"]; + +const fromCache = Assets.get("bg"); + +const fromNamespaced = Assets.get("level1-bg"); +``` + +Inside the resolver, bundle assets are stored under a combined key like `'level1-bg'` by default. The plain `'bg'` alias still resolves thanks to resolver shortcuts. If you need to override the format, pass `bundleIdentifier` to `Assets.init()`. + +## Common Mistakes + +### [HIGH] Unloading while assets are still in use + +Wrong: + +```ts +await Assets.unloadBundle("level1"); +// level1 sprites still on the stage; they now reference destroyed textures +``` + +Correct: + +```ts +level1Container.destroy({ children: true }); +await Assets.unloadBundle("level1"); +``` + +Always destroy (or detach from the scene) any display objects that reference the bundle's textures before unloading. Otherwise the renderer hits freed GPU memory and errors. + + +### [MEDIUM] Confusing `addBundle` and `init` manifests + +Wrong: + +```ts +await Assets.init(); +Assets.addBundle('ui', [...]); +await Assets.loadBundle('ui'); +``` + +Both work; this is not actually wrong; but a manifest passed to `Assets.init({ manifest: {...} })` registers all bundles at init time in one place. Prefer manifests when you know all bundles upfront; prefer `addBundle` when bundles are discovered dynamically at runtime. + + +## API Reference + +- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md) +- [AssetsBundle](https://pixijs.download/release/docs/assets.AssetsBundle.html.md) +- [Resolver](https://pixijs.download/release/docs/assets.Resolver.html.md) diff --git a/.agents/skills/pixijs-assets/references/caching.md b/.agents/skills/pixijs-assets/references/caching.md new file mode 100644 index 0000000..6785a58 --- /dev/null +++ b/.agents/skills/pixijs-assets/references/caching.md @@ -0,0 +1,143 @@ +# Caching + +Every asset loaded through `Assets` is cached until you explicitly unload it. The cache is a global singleton keyed by the resolved URL, alias, and any bundle identifier. Use the cache to avoid double-loading, retrieve loaded assets synchronously, and reclaim GPU memory when an asset is no longer needed. + +## Quick Start + +```ts +await Assets.load("hero.png"); + +const cached = Assets.get("hero.png"); +const sprite = new Sprite(cached); + +await Assets.unload("hero.png"); +``` + +`Assets.load` adds the asset to the cache; `Assets.get` retrieves it synchronously; `Assets.unload` removes it and releases the underlying GPU resource. + +## Core Patterns + +### Synchronous access to already-loaded assets + +```ts +await Assets.load(["hero.png", "enemy.png"]); + +const hero = Assets.get("hero"); +const enemy = Assets.get("enemy"); + +if (hero) { + app.stage.addChild(new Sprite(hero)); +} +``` + +`Assets.get(alias)` returns `undefined` if the asset has not been loaded yet. It is synchronous; use it in tight loops or anywhere `await` would be awkward. + +### Multiple keys at once + +```ts +await Assets.load(["hero", "enemy", "boss"]); + +const all = Assets.get(["hero", "enemy", "boss"]); +const heroTex = all["hero"]; +``` + +Passing an array returns an object keyed by alias. Useful for retrieving all the assets a scene needs in one call. + +### Deduping load calls + +```ts +const tex1 = await Assets.load("hero.png"); +const tex2 = await Assets.load("hero.png"); +console.log(tex1 === tex2); // true +``` + +Calling `Assets.load` with the same key multiple times returns the same cached result immediately on subsequent calls. Safe to call from multiple async functions concurrently. + +### Unloading + +```ts +sprite.destroy(); +await Assets.unload("hero.png"); +``` + +`Assets.unload(id)` removes the asset from the cache, calls `destroy()` on the texture (releasing GPU memory), and removes any loader-specific wrappers. Always destroy or detach display objects that reference the asset before unloading, or you'll hit freed GPU memory. + +### Unloading a bundle + +```ts +level1Container.destroy({ children: true }); +await Assets.unloadBundle("level1"); +``` + +Prefer `unloadBundle` over manually iterating. It has no reference counting: every asset in the bundle is removed from the cache and destroyed, even if another bundle declares the same `src`, and that bundle's alias stays broken until you reload it. Detach anything on the scene that still uses those assets first. + +### Inspecting the cache + +```ts +import { Cache } from "pixi.js"; + +const key = "hero.png"; +if (Cache.has(key)) { + const texture = Cache.get(key); +} +``` + +The low-level `Cache` class backs `Assets.get`. It exposes `has(key)`, `get(key)`, `set(key, value)`, and `remove(key)`. Most code should go through `Assets.get/unload` instead, but direct `Cache` access is useful for diagnostics or custom loader plugins. + +## Common Mistakes + +### [CRITICAL] Using `Assets.get` before `Assets.load` + +Wrong: + +```ts +const texture = Assets.get("hero.png"); +const sprite = new Sprite(texture); // texture is undefined +``` + +Correct: + +```ts +await Assets.load("hero.png"); +const texture = Assets.get("hero.png"); +const sprite = new Sprite(texture); +``` + +`Assets.get` is synchronous and returns `undefined` if the asset hasn't been loaded yet. Always await `Assets.load` first, or use the return value of `Assets.load` directly. + + +### [HIGH] Not unloading between levels + +Textures stay in the cache indefinitely. A game that loads level after level without calling `Assets.unload` or `Assets.unloadBundle` slowly accumulates GPU memory until it hits browser limits. + +```ts +await Assets.unloadBundle("level1"); +await Assets.loadBundle("level2"); +``` + + +### [MEDIUM] Using sprites after unload + +Wrong: + +```ts +const sprite = new Sprite(texture); +await Assets.unload("hero.png"); +// sprite still references the destroyed texture +``` + +Correct: + +```ts +sprite.destroy(); +await Assets.unload("hero.png"); +``` + +`Assets.unload` destroys the underlying texture. Any sprite still referencing it will render Texture.EMPTY or crash depending on the backend. Destroy the leaf (or reassign its texture) before unloading. + + +## API Reference + +- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md) +- [Cache](https://pixijs.download/release/docs/assets.Cache.html.md) +- [Texture](https://pixijs.download/release/docs/rendering.Texture.html.md) diff --git a/.agents/skills/pixijs-assets/references/compressed-textures.md b/.agents/skills/pixijs-assets/references/compressed-textures.md new file mode 100644 index 0000000..2dd5edd --- /dev/null +++ b/.agents/skills/pixijs-assets/references/compressed-textures.md @@ -0,0 +1,120 @@ +# Compressed Textures + +GPU-compressed texture formats (DDS, KTX, KTX2, Basis) use 4–8x less GPU memory than PNG/JPEG and skip runtime decoding. Use them for large textures, high-asset-count games, and anywhere memory budget matters. Each format requires a side-effect import to register its loader. + +## Quick Start + +```ts +import "pixi.js/ktx2"; +import { Assets, Sprite } from "pixi.js"; + +const texture = await Assets.load("background.ktx2"); + +const bg = new Sprite(texture); +app.stage.addChild(bg); +``` + +Without the side-effect import, the loader won't know how to parse the file and will skip it silently. + +## Core Patterns + +### Format imports + +```ts +import "pixi.js/dds"; // DirectDraw Surface (.dds) +import "pixi.js/ktx"; // KTX (Khronos Texture) v1 +import "pixi.js/ktx2"; // KTX v2 (with Basis Universal support) +import "pixi.js/basis"; // Basis Universal (.basis) +``` + +Each import registers a `LoaderParser` that can decode the matching file extension. Import only the formats you use; the loaders include decoder runtime that adds to your bundle size. + +### Format selection matrix + +| Format | Platforms | Notes | +| ------ | --------- | --------------------------------------------------------------------------------------------------------------- | +| DDS | All | Legacy desktop formats (DXT, BC). Fast decoder; wide support. | +| KTX | All | Older Khronos container. Prefer KTX2 for new projects. | +| KTX2 | All | Newer container; typically used with Basis Universal. GPU-native when available. | +| Basis | All | Supercompressed; transcodes to the GPU-native format at load time. Best for "one file, any platform" workflows. | + +Use KTX2 + Basis for new projects unless you have a specific need for one of the others. + +### With the resolver + +```ts +import "pixi.js/ktx2"; +import { Assets } from "pixi.js"; + +Assets.add({ + alias: "background", + src: "background.{ktx2,webp,png}", +}); + +const texture = await Assets.load("background"); +``` + +List compressed textures as first-preference format in the resolver. On browsers or hardware that can't sample the compressed format, the resolver falls back to WebP or PNG automatically. + +### Async decoding + +```ts +import "pixi.js/basis"; +import { Assets } from "pixi.js"; + +const texture = await Assets.load("hero.basis"); +``` + +Basis Universal decodes asynchronously on a worker thread (where supported). You don't need to await anything beyond the normal `Assets.load`; the loader handles decoding. + +### Multiple compressed formats at once + +```ts +import "pixi.js/ktx2"; +import "pixi.js/basis"; +import "pixi.js/dds"; +``` + +Multiple format imports can coexist. Each registers an extension for its own file type. If you only use one format, import only that one to keep the bundle smaller. + +## Common Mistakes + +### [CRITICAL] Missing the format import + +Wrong: + +```ts +import { Assets } from "pixi.js"; +await Assets.load("background.ktx2"); +``` + +Correct: + +```ts +import "pixi.js/ktx2"; +import { Assets } from "pixi.js"; +await Assets.load("background.ktx2"); +``` + +Without the side-effect import, no loader parser is registered for `.ktx2` files. The load silently does nothing (or errors) and you get `undefined` back. + + +### [HIGH] Relying on mipmaps from compressed textures in Canvas2D + +Compressed textures require WebGL or WebGPU. The Canvas2D backend can't sample them. If you need Canvas support, include a PNG/WebP fallback via the resolver format list: + +```ts +Assets.add({ alias: "bg", src: "bg.{ktx2,png}" }); +``` + + +### [MEDIUM] Large Basis files in WebGL1 + +Basis Universal transcodes to different GPU formats based on what the device supports. On WebGL1 without extensions, some devices fall back to an uncompressed format, defeating the memory savings. Check `renderer.context.supports` for supported compressed formats if you're targeting older hardware. + + +## API Reference + +- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md) +- [loadKTX2](https://pixijs.download/release/docs/assets.loadKTX2.html.md) +- [TextureSource](https://pixijs.download/release/docs/rendering.TextureSource.html.md) diff --git a/.agents/skills/pixijs-assets/references/fonts.md b/.agents/skills/pixijs-assets/references/fonts.md new file mode 100644 index 0000000..258defd --- /dev/null +++ b/.agents/skills/pixijs-assets/references/fonts.md @@ -0,0 +1,205 @@ +# Fonts + +PixiJS loads two kinds of fonts through `Assets`: web fonts (TTF/OTF/WOFF/WOFF2) via `loadWebFont`, and bitmap fonts (FNT/XML) via `loadBitmapFont`. Use web fonts for `Text` and `HTMLText`; use bitmap fonts for `BitmapText` when you need GPU-friendly rendering without runtime text layout. + +## Web fonts + +### Quick Start + +```ts +await Assets.load("fonts/titan-one.woff2"); + +const text = new Text({ + text: "Hello world", + style: { fontFamily: "Titan One", fontSize: 48 }, +}); +``` + +Once the font is loaded, reference it by its derived family name in any `TextStyle`. PixiJS registers the font with the browser's `FontFaceSet`, so DOM elements and Canvas can use it too. + +### Family name derivation + +```ts +// Loaded URL → Derived family name +// fonts/titan-one.woff → 'Titan One' +// fonts/open_sans.ttf → 'Open Sans' +// fonts/my-custom-font.otf → 'My Custom Font' +``` + +By default, the family name is the filename without extension, with dashes and underscores replaced by spaces and title-cased. Override it with `data.family`. + +### Load options via `data` + +```ts +await Assets.load({ + alias: "hero-font", + src: "fonts/hero.woff2", + data: { + family: "HeroFont", + weights: ["normal", "bold"], + style: "italic", + display: "swap", + unicodeRange: "U+0000-00FF", + stretch: "expanded", + featureSettings: '"liga" 1', + }, +}); +``` + +Fields on `data` map directly to FontFace descriptors: + +| Option | Purpose | +| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `family` | Override the derived font family name | +| `weights` | Array of weights to register. One `FontFace` per weight, all sharing the same URL. Valid values: `'normal'`, `'bold'`, `'100'`–`'900'` | +| `style` | `'normal'`, `'italic'`, `'oblique'` | +| `display` | CSS `font-display` (`'auto'`, `'block'`, `'swap'`, `'fallback'`, `'optional'`) | +| `unicodeRange` | Restrict which codepoints the font covers | +| `stretch` | `'normal'`, `'condensed'`, `'expanded'`, etc. | +| `variant` | CSS font-variant value | +| `featureSettings` | OpenType feature settings like `'"liga" 1, "dlig" 1'` | + +### Loading multiple weights + +```ts +await Assets.load({ + src: "fonts/inter.woff2", + data: { + family: "Inter", + weights: ["400", "700"], + }, +}); +``` + +A single URL registers as multiple weights. Use when your font file contains a variable font or when your platform lets one file satisfy multiple weights. + +### Supported extensions + +`.ttf`, `.otf`, `.woff`, `.woff2`. WOFF2 is the smallest and universally supported in current browsers. Prefer it unless you're targeting very old environments. + +## Bitmap fonts + +### Quick Start + +```ts +import "pixi.js/text-bitmap"; + +await Assets.load("fonts/arial.fnt"); + +const text = new BitmapText({ + text: "Score: 9999", + style: { fontFamily: "Arial", fontSize: 32 }, +}); +``` + +The side-effect import registers the `CanvasBitmapTextPipe` and `BitmapTextPipe` rendering pipes. `Assets.load('font.fnt')` works without it and returns a `BitmapFont`, but rendering a `BitmapText` fails at render time without the import. + +### Supported formats + +| Extension | Format | +| --------- | ------------------ | +| `.fnt` | BMFont text or XML | +| `.xml` | BMFont XML | + +The parser sniffs the content to pick between text and XML automatically. + +### Texture page loading + +```ts +// my-font.fnt references my-font_0.png, my-font_1.png +await Assets.load("fonts/my-font.fnt"); +``` + +Bitmap fonts reference page images by filename in the `.fnt` data. The parser resolves these relative to the `.fnt` URL and loads them automatically. Any search params on the `.fnt` URL (e.g. cache busting) propagate to the page texture URLs. + +### Signed Distance Field (SDF) fonts + +The parser detects distance field metadata in the `.fnt` file and enables `linear` scale mode plus disables mipmaps automatically. No extra configuration needed from the caller. SDF fonts stay crisp at any size, so you can render a single bitmap font at many different sizes. + +### Accessing the BitmapFont instance + +```ts +await Assets.load({ alias: "arial", src: "fonts/arial.fnt" }); + +const font = Assets.get("arial"); +console.log(font.chars); +console.log(font.fontFamily); +``` + +The cached asset is a `BitmapFont` instance. `Assets.get('arial')` and `Assets.get('arial-bitmap')` both return it, and `Assets.get('Arial-bitmap')` works if `fontFamily` matches. + +## Forcing the font parser + +If your font URL lacks an extension, force the loader: + +```ts +await Assets.load({ + src: "https://cdn.example.com/fonts/abc123", + parser: "web-font", + data: { family: "Hero", weights: ["400", "700"] }, +}); + +await Assets.load({ + src: "https://cdn.example.com/fonts/hero-bmfont", + parser: "bitmap-font", +}); +``` + +See the main `SKILL.md` section on "Forcing a parser with `parser`" for the full list of parser IDs. + +## Common Mistakes + +### [HIGH] Forgetting the bitmap-font import + +Wrong: + +```ts +import { Assets, BitmapText } from "pixi.js"; +await Assets.load("arial.fnt"); +const text = new BitmapText({ text: "Hi", style: { fontFamily: "Arial" } }); +app.stage.addChild(text); +``` + +Correct: + +```ts +import "pixi.js/text-bitmap"; +import { Assets, BitmapText } from "pixi.js"; +await Assets.load("arial.fnt"); +const text = new BitmapText({ text: "Hi", style: { fontFamily: "Arial" } }); +app.stage.addChild(text); +``` + +`Assets.load('arial.fnt')` succeeds in the default bundle and returns a `BitmapFont`, but `'pixi.js/text-bitmap'` registers the `CanvasBitmapTextPipe` and `BitmapTextPipe`. Without it, `BitmapText` renders nothing or errors at render time. + + +### [HIGH] Using Text before the font is loaded + +Wrong: + +```ts +const text = new Text({ text: "Hi", style: { fontFamily: "Hero" } }); +Assets.load("fonts/hero.woff2"); +``` + +Correct: + +```ts +await Assets.load("fonts/hero.woff2"); +const text = new Text({ text: "Hi", style: { fontFamily: "Hero" } }); +``` + +The browser falls back to a system font if the named family isn't registered yet, then the `Text` is cached at that fallback style. Reloading the font doesn't repaint existing Text objects. + + +### [MEDIUM] Family name mismatch + +If you don't pass `data.family`, the family name is derived from the filename. `my_hero_font.woff` becomes `'My Hero Font'`; use exactly that string in your `TextStyle.fontFamily`, or set `data.family` to an explicit value. + + +## API Reference + +- [loadWebFont](https://pixijs.download/release/docs/assets.loadWebFont.html.md) +- [loadBitmapFont](https://pixijs.download/release/docs/assets.loadBitmapFont.html.md) +- [LoadFontData](https://pixijs.download/release/docs/assets.LoadFontData.html.md) +- [BitmapFont](https://pixijs.download/release/docs/scene.BitmapFont.html.md) diff --git a/.agents/skills/pixijs-assets/references/gif.md b/.agents/skills/pixijs-assets/references/gif.md new file mode 100644 index 0000000..7b1d21f --- /dev/null +++ b/.agents/skills/pixijs-assets/references/gif.md @@ -0,0 +1,171 @@ +# Animated GIFs + +PixiJS loads animated GIFs through `Assets.load()` and returns a `GifSource` containing all decoded frames. Pass the source to `GifSprite` for playback, looping, and frame control. GIF support is opt-in via the `'pixi.js/gif'` side-effect import. + +## Quick Start + +```ts +import "pixi.js/gif"; +import { Assets, GifSprite } from "pixi.js"; + +const source = await Assets.load("explosion.gif"); +const gif = new GifSprite(source); +app.stage.addChild(gif); +``` + +Without `'pixi.js/gif'`, the `.gif` loader parser isn't registered and `Assets.load()` won't know what to do with the file. + +## Core Patterns + +### Load options via `data` + +```ts +const source = await Assets.load({ + src: "pixel-art.gif", + data: { + fps: 12, + scaleMode: "nearest", + resolution: 2, + autoGenerateMipmaps: false, + }, +}); +``` + +`data` accepts `GifBufferOptions`, which extends `CanvasSourceOptions`: + +| Option | Default | Purpose | +| --------------------- | ---------- | ---------------------------------------------------------------- | +| `fps` | `30` | Fallback frame rate when the GIF has no per-frame delay metadata | +| `scaleMode` | `'linear'` | `'nearest'` for pixel art, `'linear'` for smooth scaling | +| `resolution` | `1` | Render resolution of the decoded frames | +| `autoGenerateMipmaps` | `false` | Generate mipmaps for downscaling | + +Any other `CanvasSourceOptions` field works here too. + +### GifSprite options + +```ts +const gif = new GifSprite({ + source, + autoPlay: true, + loop: true, + animationSpeed: 0.5, + autoUpdate: true, + fps: 30, + onComplete: () => console.log("done"), + onLoop: () => console.log("looped"), + onFrameChange: (frame) => console.log(frame), +}); +``` + +Construction options control playback behavior; they're independent of the load-time `data` options. + +### Loading from a data URI + +```ts +const source = await Assets.load( + "data:image/gif;base64,R0lGODlhAQABAAAAACw...", +); +``` + +The parser matches both `.gif` file extensions and `data:image/gif` URIs. No extra configuration needed. + +### Playback control + +```ts +gif.play(); +gif.stop(); +gif.currentFrame = 5; +gif.animationSpeed = 0.5; +gif.loop = false; + +console.log(gif.totalFrames); +console.log(gif.playing); +console.log(gif.progress); +console.log(gif.duration); +``` + +### Sharing a source across sprites + +```ts +const source = await Assets.load("spin.gif"); + +const a = new GifSprite(source); +const b = new GifSprite(source); + +a.animationSpeed = 1; +b.animationSpeed = 0.25; +``` + +Multiple `GifSprite` instances can share the same `GifSource`; each gets independent playback state. The underlying textures are shared, so this is cheap. + +### Cleanup + +```ts +gif.destroy(); // destroys the sprite, not the source +gif.destroy(true); // destroys the sprite AND the source (breaks other sprites using it) +await Assets.unload("explosion.gif"); // unload through the Assets system +``` + +Prefer `Assets.unload` unless you know no other sprite shares the same `GifSource`. + +## Forcing the GIF parser + +If your GIF URL lacks an extension, force the parser: + +```ts +const source = await Assets.load({ + src: "https://cdn.example.com/gif/abc123", + parser: "gif", + data: { fps: 24 }, +}); +``` + +See the main `SKILL.md` section on "Forcing a parser with `parser`" for the full list of parser IDs. + +## Common Mistakes + +### [CRITICAL] Missing the GIF import + +Wrong: + +```ts +import { Assets } from "pixi.js"; +await Assets.load("explosion.gif"); +``` + +Correct: + +```ts +import "pixi.js/gif"; +import { Assets } from "pixi.js"; +await Assets.load("explosion.gif"); +``` + +Without `'pixi.js/gif'`, the loader parser isn't registered. The call fails or returns undefined. + + +### [MEDIUM] Using GIF when a spritesheet would be cheaper + +GIF decoding creates one texture per frame. For a 30-frame animation that's 30 separate uploads. A spritesheet packs all frames into a single atlas texture, which batches better and uses less GPU memory. Prefer spritesheets for performance-critical game animations; use GIFs for convenience and one-off effects. + + +### [MEDIUM] destroy(true) when other sprites share the source + +```ts +const source = await Assets.load("spin.gif"); +const a = new GifSprite(source); +const b = new GifSprite(source); + +a.destroy(true); // WRONG: also destroys source, breaking sprite b +``` + +Pass `true` to `destroy` only if you know nothing else references the `GifSource`. Otherwise call plain `destroy()` and `Assets.unload()` when the source is no longer needed. + + +## API Reference + +- [GifSource](https://pixijs.download/release/docs/gif.GifSource.html.md) +- [GifSprite](https://pixijs.download/release/docs/gif.GifSprite.html.md) +- [GifBufferOptions](https://pixijs.download/release/docs/gif.GifBufferOptions.html.md) +- [GifAsset](https://pixijs.download/release/docs/gif.GifAsset.html.md) diff --git a/.agents/skills/pixijs-assets/references/manifests.md b/.agents/skills/pixijs-assets/references/manifests.md new file mode 100644 index 0000000..939d9a7 --- /dev/null +++ b/.agents/skills/pixijs-assets/references/manifests.md @@ -0,0 +1,175 @@ +# Manifests + +A manifest is a JSON-shaped description of every bundle in your application. Pass it to `Assets.init({ manifest })` and the resolver registers every bundle at startup, so later code can reference them by name. Use manifests when you know your asset graph upfront and want one source of truth. + +## Quick Start + +```ts +await Assets.init({ + manifest: { + bundles: [ + { + name: "load-screen", + assets: [{ alias: "logo", src: "logo.png" }], + }, + { + name: "game", + assets: [ + { alias: "hero", src: "hero.{webp,png}" }, + { alias: "enemies", src: "enemies.json" }, + ], + }, + ], + }, +}); + +await Assets.loadBundle("load-screen"); +await Assets.loadBundle("game"); +``` + +Each bundle has a `name` and an `assets` array of `UnresolvedAsset` entries. Format expansions (`{webp,png}`) and resolution patterns (`@{1,2}x`) work inside `src`. + +## Core Patterns + +### Inline manifest object + +```ts +const manifest = { + bundles: [ + { + name: "ui", + assets: [ + { alias: "button", src: "ui/button.png" }, + { alias: "panel", src: "ui/panel.png" }, + ], + }, + ], +}; + +await Assets.init({ manifest }); +``` + +The manifest can be any plain object matching the `AssetsManifest` shape. Pass it directly to `init`. + +### Manifest from a URL + +```ts +await Assets.init({ manifest: "assets/manifest.json" }); +``` + +When `manifest` is a string, PixiJS loads it as JSON first, then registers the bundles. Useful when your build tooling generates a manifest at deploy time (e.g., with `@assetpack/core`). + +### Format and resolution patterns in manifests + +```ts +const manifest = { + bundles: [ + { + name: "hero", + assets: [{ alias: "hero", src: "hero@{0.5,1,2}x.{webp,avif,png}" }], + }, + ], +}; +``` + +The resolver expands the pattern to six candidates and picks the best match based on `window.devicePixelRatio` and browser format support. Configure preferences in `Assets.init({ texturePreference: {...} })`. + +### Multiple aliases per entry + +```ts +const manifest = { + bundles: [ + { + name: "characters", + assets: [ + { alias: ["hero", "player"], src: "hero.png" }, + { alias: "npc1", src: "villager.png" }, + ], + }, + ], +}; +``` + +An asset can expose multiple aliases. `Assets.load('hero')` and `Assets.load('player')` return the same texture. + +### Data options in manifest entries + +```ts +const manifest = { + bundles: [ + { + name: "pixel-art", + assets: [ + { + alias: "tile", + src: "tile.png", + data: { scaleMode: "nearest" }, + }, + ], + }, + ], +}; +``` + +Each asset entry can include a `data` field forwarded to the loader. Use it for `scaleMode`, `autoGenerateMipmaps`, `parseAsGraphicsContext`, FontFace descriptors, etc. + +### Background-loading from a manifest + +```ts +await Assets.init({ manifest }); +await Assets.loadBundle("load-screen"); + +Assets.backgroundLoadBundle("game"); +await Assets.loadBundle("game"); +``` + +After init, you can start background loading of other bundles immediately. The call is non-blocking; the `await Assets.loadBundle('game')` later resolves quickly if the background work finished. + +## Common Mistakes + +### [HIGH] Calling `Assets.init` twice + +Wrong: + +```ts +await Assets.init({ manifest }); +await Assets.init({ basePath: "https://cdn.example.com/" }); +``` + +Correct: + +```ts +await Assets.init({ manifest, basePath: "https://cdn.example.com/" }); +``` + +`Assets.init()` can only be called once. The second call is ignored with a warning. Combine all configuration into a single call. + + +### [MEDIUM] Missing format expansion on manifest entries + +Wrong: + +```ts +{ alias: 'hero', src: 'hero.webp' } +``` + +Correct: + +```ts +{ alias: 'hero', src: 'hero.{webp,png}' } +``` + +Listing only one format blocks the resolver from falling back on browsers without WebP/AVIF support. Always list at least one fallback. + + +### [MEDIUM] Loading manifest after `Assets.add` + +If you call `Assets.add(...)` or `Assets.addBundle(...)` before `Assets.init({ manifest })`, the manifest bundles will append to the existing state but preference-detection (format, resolution) hasn't run yet. Prefer calling `init` first, then adding ad-hoc assets. + + +## API Reference + +- [AssetsManifest](https://pixijs.download/release/docs/assets.AssetsManifest.html.md) +- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md) +- [Resolver](https://pixijs.download/release/docs/assets.Resolver.html.md) +- [UnresolvedAsset](https://pixijs.download/release/docs/assets.UnresolvedAsset.html.md) diff --git a/.agents/skills/pixijs-assets/references/progress.md b/.agents/skills/pixijs-assets/references/progress.md new file mode 100644 index 0000000..93e4122 --- /dev/null +++ b/.agents/skills/pixijs-assets/references/progress.md @@ -0,0 +1,142 @@ +# Progress Tracking + +`Assets.load` and `Assets.loadBundle` accept a progress callback that fires as each asset completes. Use it to drive loading bars, percentage readouts, or spinner state updates during long loads. The progress value is normalized `[0, 1]` across the entire call. + +## Quick Start + +```ts +const loadingBar = new Graphics(); +app.stage.addChild(loadingBar); + +await Assets.load(["hero.png", "enemy.png", "map.json"], (progress) => { + loadingBar.clear(); + loadingBar.rect(0, 0, progress * 400, 20).fill(0x66ccff); +}); +``` + +The callback is invoked after each asset resolves. Final invocation reaches `1.0` just before the promise resolves. + +## Core Patterns + +### Progress on a single asset + +```ts +await Assets.load("large-atlas.json", (progress) => { + console.log(`${Math.round(progress * 100)}%`); +}); +``` + +Even for a single asset, the callback fires (typically once, reaching `1.0`). For most cases, progress for a single call is not useful; prefer progress on bundles or arrays. + +### Progress on an array + +```ts +const assets = await Assets.load( + ["hero.png", "enemy.png", "map.json", "music.mp3"], + (progress) => updateBar(progress), +); +``` + +Progress is distributed evenly across the N assets. When the third asset in a four-asset array finishes, progress is `0.75`. + +### Progress on a bundle + +```ts +await Assets.loadBundle("level1", (progress) => { + loadingText.text = `Loading… ${Math.round(progress * 100)}%`; +}); +``` + +Each asset in the bundle contributes equally. If the bundle has 10 entries, each contributes `0.1` to the total. + +### Progress via `LoadOptions.onProgress` + +```ts +await Assets.load("game.json", { + onProgress: (progress) => updateBar(progress), + onError: (err, asset) => { + const src = typeof asset === "string" ? asset : asset.src; + console.warn("failed:", src, err); + }, +}); +``` + +Instead of a callback as the second argument, pass a `LoadOptions` object. This is the preferred form when you also need error handling or retry strategies. Note that `onError` receives `string | ResolvedAsset`; guard before accessing `.src`. + +### Global progress across multiple loads + +```ts +async function loadAllWithTotal(tasks: Array<() => Promise>) { + let done = 0; + for (const task of tasks) { + await task(); + done++; + updateBar(done / tasks.length); + } +} + +await loadAllWithTotal([ + () => Assets.load("menu.json"), + () => Assets.loadBundle("level1"), + () => Assets.loadBundle("sounds"), +]); +``` + +Progress callbacks are scoped per call. If you need a single bar across several sequential loads, wrap the calls manually and count completions yourself. + +## Common Mistakes + +### [HIGH] Treating progress callback as completion + +Wrong: + +```ts +Assets.load("hero.png", (progress) => { + if (progress === 1) { + showHero(); + } +}); +``` + +Correct: + +```ts +await Assets.load("hero.png", (progress) => updateBar(progress)); +showHero(); +``` + +`progress === 1` may fire slightly before the returned promise resolves. Always use the `await` or `.then()` to know when loading is truly complete. The progress callback is for UI updates only. + + +### [MEDIUM] Progress not updating smoothly + +Each asset contributes a discrete step. If your bundle has three assets, progress jumps `0 -> 0.33 -> 0.66 -> 1.0`. For a smoother bar, split large bundles into smaller ones, or animate the bar width toward the target value: + +```ts +let target = 0; +await Assets.loadBundle("game", (p) => { + target = p; +}); + +app.ticker.add(() => { + loadingBar.width += (target * maxWidth - loadingBar.width) * 0.1; +}); +``` + + +### [MEDIUM] Progress via background loading + +Wrong: + +```ts +Assets.backgroundLoadBundle("game", (p) => updateBar(p)); +``` + +Background loading has no progress callback. For visible progress, use `Assets.loadBundle` (foreground). See `references/background.md`. + + +## API Reference + +- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md) +- [LoadOptions](https://pixijs.download/release/docs/assets.LoadOptions.html.md) +- [ProgressCallback](https://pixijs.download/release/docs/assets.ProgressCallback.html.md) diff --git a/.agents/skills/pixijs-assets/references/resolution.md b/.agents/skills/pixijs-assets/references/resolution.md new file mode 100644 index 0000000..cc312ca --- /dev/null +++ b/.agents/skills/pixijs-assets/references/resolution.md @@ -0,0 +1,142 @@ +# Resolution and Format Detection + +PixiJS's asset resolver can pick the best asset variant for the current device based on pixel density (`@0.5x`, `@1x`, `@2x`) and supported image formats (`avif`, `webp`, `png`). Use resolution and format patterns to serve one asset spec that adapts to retina displays, format support, and bandwidth budgets. + +## Quick Start + +```ts +await Assets.init({ + texturePreference: { + resolution: window.devicePixelRatio, + format: ["avif", "webp", "png"], + }, +}); + +Assets.add({ alias: "hero", src: "hero@{0.5,1,2}x.{webp,png}" }); + +const texture = await Assets.load("hero"); +``` + +The resolver expands the pattern to six candidates (`hero@0.5x.webp`, `hero@0.5x.png`, `hero@1x.webp`, ...) and picks the best match based on device pixel ratio and format support. + +## Core Patterns + +### Configuring preferences at init + +```ts +await Assets.init({ + texturePreference: { + resolution: window.devicePixelRatio, // e.g., 2 on retina + format: ["avif", "webp", "png"], // preferred-first order + }, +}); +``` + +- `resolution` is a single number (best-match threshold) or array of acceptable resolutions. +- `format` is ordered by preference. The resolver tries each in turn and uses the first one the browser supports. + +### Resolution patterns in src + +```ts +Assets.add({ alias: "bg", src: "bg@{0.5,1,2}x.png" }); +``` + +The resolver expands this to `bg@0.5x.png`, `bg@1x.png`, `bg@2x.png` and picks based on `texturePreference.resolution`. Encoded resolution sets the texture's source resolution automatically, so the sprite's `width` / `height` appear as logical size regardless of the file chosen. + +### Format patterns in src + +```ts +Assets.add({ alias: "icon", src: "icon.{avif,webp,png}" }); +``` + +Format detection runs once during `Assets.init()`. The resolver learns which formats the browser supports, then picks the highest-preference supported format per load. + +### Combined resolution + format + +```ts +Assets.add({ alias: "hero", src: "hero@{0.5,1,2}x.{avif,webp,png}" }); +``` + +Both patterns can appear in the same `src`. The resolver does a Cartesian product: 3 resolutions × 3 formats = 9 candidates. It picks the best combination based on both preferences. + +### Manual resolution override + +```ts +Assets.add({ + alias: "sharp", + src: "sharp.png", + data: { resolution: 2 }, +}); +``` + +If a file is already at a known resolution but lacks the `@2x` filename suffix, pass `resolution` in `data` to tell the loader. Useful when your tooling doesn't produce suffixed filenames. + +### Custom retina prefix + +```ts +import { Resolver } from "pixi.js"; + +Resolver.RETINA_PREFIX = /@([0-9\.]+)density/; + +Assets.add({ alias: "hero", src: "hero@{1,2}density.png" }); +``` + +Change the resolution filename pattern if your build pipeline uses a different convention. Default is `/@([0-9\.]+)x/`. + +### Skipping format detection + +```ts +await Assets.init({ + skipDetections: true, + texturePreference: { format: ["webp"] }, +}); +``` + +If you know your target browser supports a specific format, `skipDetections: true` skips the runtime detection (a small init-time saving). Useful for embedded or kiosk deployments where format support is fixed. + +## Common Mistakes + +### [HIGH] Wrong pattern syntax + +Wrong: + +```ts +Assets.add({ alias: "hero", src: "hero@[1,2]x.png" }); +``` + +Correct: + +```ts +Assets.add({ alias: "hero", src: "hero@{1,2}x.png" }); +``` + +The expansion syntax uses `{}` (like shell brace expansion), not `[]`. Square brackets aren't recognized and the resolver tries to load the literal filename. + + +### [MEDIUM] Missing fallback format + +Wrong: + +```ts +Assets.add({ alias: "hero", src: "hero.avif" }); +``` + +Correct: + +```ts +Assets.add({ alias: "hero", src: "hero.{avif,png}" }); +``` + +If a browser doesn't support AVIF, the loader fails. Always list at least one fallback format that all target browsers support. + + +### [MEDIUM] Mismatch between spritesheet.json `meta.scale` and actual image + +In v8, a spritesheet's `meta.scale` field directly sets the resolution of the atlas texture. If the JSON says `"1"` but the image was exported at 2x, frames render at double the intended size. Verify `meta.scale` matches the actual image resolution; atlas tools like TexturePacker set this automatically. + + +## API Reference + +- [Assets](https://pixijs.download/release/docs/assets.Assets.html.md) +- [Resolver](https://pixijs.download/release/docs/assets.Resolver.html.md) +- [AssetInitOptions](https://pixijs.download/release/docs/assets.AssetInitOptions.html.md) diff --git a/.agents/skills/pixijs-assets/references/spritesheet.md b/.agents/skills/pixijs-assets/references/spritesheet.md new file mode 100644 index 0000000..194ffd3 --- /dev/null +++ b/.agents/skills/pixijs-assets/references/spritesheet.md @@ -0,0 +1,119 @@ +# Spritesheet: Texture Atlases and Animations + +Load and use texture atlases and animation sheets with PixiJS's `Spritesheet` class. Atlases reduce draw calls by packing many textures into a single image. + +## Quick Start + +```ts +const sheet = await Assets.load("spritesheet.json"); + +const hero = new Sprite(sheet.textures["hero.png"]); +app.stage.addChild(hero); + +const walk = new AnimatedSprite(sheet.animations["walk"]); +walk.animationSpeed = 0.15; +walk.play(); +app.stage.addChild(walk); +``` + +When loaded through `Assets.load()`, the JSON file is fetched, the atlas image is loaded, and `sheet.parse()` is called automatically. The returned object is a `Spritesheet` instance. + +## Core Patterns + +### SpritesheetData JSON format + +```json +{ + "frames": { + "hero.png": { + "frame": { "x": 0, "y": 0, "w": 64, "h": 64 }, + "sourceSize": { "w": 64, "h": 64 }, + "spriteSourceSize": { "x": 0, "y": 0, "w": 64, "h": 64 }, + "anchor": { "x": 0.5, "y": 0.5 }, + "borders": { "left": 10, "top": 10, "right": 10, "bottom": 10 } + }, + "walk_01.png": { + "frame": { "x": 64, "y": 0, "w": 64, "h": 64 }, + "rotated": true, + "trimmed": true, + "sourceSize": { "w": 80, "h": 80 }, + "spriteSourceSize": { "x": 8, "y": 8, "w": 64, "h": 64 } + } + }, + "animations": { + "walk": ["walk_01.png", "walk_02.png", "walk_03.png"] + }, + "meta": { + "image": "spritesheet.png", + "size": { "w": 512, "h": 256 }, + "scale": "1" + } +} +``` + +Key fields: + +- `frames` maps frame names to rectangle data, trim info, anchors, and 9-slice borders. +- `rotated` indicates the frame is stored rotated 90 degrees in the atlas. The parser swaps width/height automatically. +- `trimmed` indicates transparent padding was removed. `sourceSize` is the original dimensions; `spriteSourceSize` is the trimmed region within it. +- `animations` maps animation names to ordered arrays of frame names. +- `meta.scale` sets the resolution of the texture source. `"2"` means the atlas is @2x. +- `meta.image` is the atlas image filename, resolved relative to the JSON file. + +### Manual Spritesheet creation + +```ts +const texture = await Assets.load("atlas.png"); +const sheet = new Spritesheet({ + texture, + data: spritesheetJsonData, + cachePrefix: "myAtlas_", +}); +await sheet.parse(); + +const frame = new Sprite(sheet.textures["hero.png"]); +``` + +`parse()` is async for large spritesheets (over 1000 frames); it batches texture creation across multiple frames. For smaller sheets, `parseSync()` is also available. + +`cachePrefix` prepends a string to all cached texture names, preventing collisions when multiple atlases share frame names (e.g., `"hero.png"` in two different sheets). + +### Preloaded texture with Assets + +```ts +const atlasTexture = await Assets.load("images/spritesheet.png"); + +Assets.add({ + alias: "atlas", + src: "images/spritesheet.json", + data: { texture: atlasTexture }, +}); +const sheet = await Assets.load("atlas"); +``` + +### Multi-pack spritesheets + +When `meta.related_multi_packs` is present, the loader automatically loads and links related spritesheets. All linked sheets are accessible via `sheet.linkedSheets`. + +### Cleanup + +```ts +sheet.destroy(); +sheet.destroy(true); // also destroys the base atlas texture +``` + +## Common Mistakes + +### [HIGH] Spritesheet meta.scale behavior change + +In v8, `meta.scale` directly sets the texture source resolution. If your atlas was exported at @2x but `meta.scale` says `"1"`, frames render at double the intended size. Ensure `meta.scale` matches the actual resolution of the atlas image. Tools like TexturePacker set this automatically. + +### [MEDIUM] Not awaiting spritesheet parse + +`parse()` is async. Accessing `sheet.textures` before it resolves returns undefined entries. When loading via `Assets.load()`, parsing is handled automatically. + +## API Reference + +- [Spritesheet](https://pixijs.download/release/docs/assets.Spritesheet.html.md) +- [spritesheetAsset](https://pixijs.download/release/docs/assets.spritesheetAsset.html.md) +- [AnimatedSprite](https://pixijs.download/release/docs/scene.AnimatedSprite.html.md) diff --git a/.agents/skills/pixijs-assets/references/svg.md b/.agents/skills/pixijs-assets/references/svg.md new file mode 100644 index 0000000..01cf556 --- /dev/null +++ b/.agents/skills/pixijs-assets/references/svg.md @@ -0,0 +1,132 @@ +# SVG Loading + +PixiJS loads `.svg` files in one of two modes: rasterized to a texture (fast, fixed resolution) or parsed into a `GraphicsContext` (scalable vector, reusable across `Graphics` instances). Choose texture mode for backgrounds and decorative elements at a fixed size; choose Graphics mode for icons, UI elements, or anything that needs to scale or be modified at runtime. + +## Quick Start + +```ts +const svgTexture = await Assets.load("icon.svg"); +const sprite = new Sprite(svgTexture); + +const svgContext = await Assets.load({ + src: "icon.svg", + data: { parseAsGraphicsContext: true }, +}); +const graphic = new Graphics(svgContext); +``` + +By default, SVG files rasterize to a texture at their native size. Pass `parseAsGraphicsContext: true` in the `data` field to parse as vector geometry instead. + +## Core Patterns + +### Texture mode (default) + +```ts +const icon = await Assets.load("close.svg"); +const button = new Sprite(icon); +``` + +The SVG is rasterized to a bitmap via the browser's native SVG-to-image pipeline, then uploaded as a `Texture`. Rendering is batched just like a regular sprite. Scaling up beyond the rasterized resolution pixelates; the rasterization happens once. + +### Graphics mode + +```ts +const context = await Assets.load({ + src: "logo.svg", + data: { parseAsGraphicsContext: true }, +}); + +const small = new Graphics(context); +small.scale.set(0.5); + +const large = new Graphics(context); +large.scale.set(3); +``` + +The SVG is parsed into a `GraphicsContext` (a compiled list of fill/stroke instructions). Both `Graphics` instances share the same context; cheap, and both stay crisp at any scale. + +### Resolution for sharper texture mode + +```ts +const icon = await Assets.load({ + src: "icon.svg", + data: { resolution: 2 }, +}); +``` + +For texture mode, you can pass `resolution` in `data` to rasterize at a higher density. Pairs with `autoGenerateMipmaps` for smooth downscaling. Doesn't apply in Graphics mode. + +### Global default + +```ts +import { loadSvg } from "pixi.js"; + +loadSvg.config.parseAsGraphicsContext = true; +``` + +Flip the default mode globally. Any subsequent `Assets.load('*.svg')` call parses as Graphics unless overridden in the asset's `data` options. + +### What Graphics mode parses + +Graphics mode reads `` (including `fill-rule="evenodd"` holes), ``, ``, ``, ``, ``, ``, and ``. Styling comes from the `fill`, `stroke`, `stroke-width`, `fill-opacity`, `stroke-opacity`, and `opacity` attributes or inline `style="..."`. Fills and strokes can reference `` and `` definitions through `url(#id)`; `gradientUnits` and percentage coordinates are honored. Not supported: `transform` attributes, `