added pixlJS official skills and the prototype document

This commit is contained in:
2026-11-01 20:15:27 +01:00
parent db608f1f45
commit d966af3f8f
93 changed files with 14681 additions and 0 deletions
@@ -0,0 +1,216 @@
# Render Loop
Every PixiJS frame runs a fixed sequence of ticker callbacks in priority order, with `app.render()` registered at `UPDATE_PRIORITY.LOW` — scene graph update and GPU draw happen _inside_ that one callback. The `Application`'s `TickerPlugin` drives this loop automatically. Understanding the priority order and when to render yourself is key for integrating game logic, physics, and custom frame pacing.
## Frame lifecycle
Each frame, the `Ticker` measures elapsed time, clamps it with `minFPS`/`maxFPS`, then calls every listener registered with `ticker.add()` in priority order. `app.render()` is itself one of those listeners, registered at `UPDATE_PRIORITY.LOW`. When it runs, it walks the display list from `app.stage`, recalculates world transforms (position/rotation/scale propagated parent-to-child), fires each object's `onRender` hook, culls off-screen objects if culling is enabled, then batches draw calls and issues GPU commands.
```
requestAnimationFrame
│
[Ticker._tick()]
│
├─ Compute elapsed time (minFPS/maxFPS clamp)
└─ Call listeners in priority order
├─ INTERACTION / HIGH / NORMAL listeners
├─ LOW: app.render()
│ ├─ Traverse display list
│ ├─ Update world transforms
│ │ └─ object.onRender() (per-object during traversal)
│ ├─ Cull display objects (if enabled)
│ ├─ Upload data to GPU
│ └─ Draw
└─ UTILITY listeners (post-render)
```
Rendering is **retained mode**: objects persist across frames unless you explicitly remove them.
## Quick Start
```ts
app.ticker.add((ticker) => {
sprite.rotation += 0.01 * ticker.deltaTime;
});
app.ticker.add(
(ticker) => {
updatePhysics(ticker.deltaMS);
},
undefined,
UPDATE_PRIORITY.HIGH,
);
```
Callbacks receive a `Ticker` instance. Use `ticker.deltaTime` (dimensionless, ~1.0 at 60fps) for simple multipliers; use `ticker.deltaMS` (milliseconds) for time-based calculations.
## Core Patterns
### Priority order
The ticker runs registered callbacks in descending priority. The `TickerPlugin` registers `app.render()` at `UPDATE_PRIORITY.LOW`, so callbacks at `NORMAL`, `HIGH`, or `INTERACTION` run before the render.
```
UPDATE_PRIORITY.INTERACTION = 50 // pointer events
UPDATE_PRIORITY.HIGH = 25 // physics, input sampling
UPDATE_PRIORITY.NORMAL = 0 // gameplay (default)
UPDATE_PRIORITY.LOW = -25 // app.render() registered here
UPDATE_PRIORITY.UTILITY = -50 // post-render cleanup
```
```ts
import { UPDATE_PRIORITY } from "pixi.js";
app.ticker.add(
(ticker) => {
handleInput(ticker.deltaMS);
},
undefined,
UPDATE_PRIORITY.HIGH,
);
app.ticker.add((ticker) => {
updateAnimations(ticker.deltaTime);
});
```
### Time units
| Property | Type | Scaled by speed? | Capped by minFPS? |
| ----------- | ----------------------------- | ---------------- | ----------------- |
| `deltaTime` | dimensionless (~1.0 at 60fps) | yes | yes |
| `deltaMS` | milliseconds | yes | yes |
| `elapsedMS` | milliseconds | no | no |
Use `deltaTime` as a frame-rate multiplier for simple per-frame logic; use `deltaMS` for pixels-per-second or other time-based math; use `elapsedMS` only for profiling (raw, uncapped, unscaled).
### Manual rendering
```ts
await app.init({ autoStart: false, width: 800, height: 600 });
function frame(time: number) {
updateGameState();
app.renderer.render(app.stage);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```
`autoStart: false` disables the `TickerPlugin`'s automatic render registration. You control when the scene draws, letting you integrate with a custom loop, an external animation library, or a fixed-timestep game clock.
### Stop and start
```ts
app.stop(); // pause the ticker and rendering
app.start(); // resume
```
Useful for a pause menu or when the user switches away from the tab. The ticker is automatically paused on page blur when `sharedTicker: false` (default).
### Per-object update via `onRender`
```ts
const sprite = new Sprite(texture);
sprite.onRender = () => {
sprite.rotation += 0.01;
};
app.stage.addChild(sprite);
```
`onRender` is called during scene graph traversal, just before the object is drawn. It's a per-object hook; an alternative to a global ticker callback when the logic is tied to a specific display object.
### Frame rate capping
```ts
app.ticker.maxFPS = 30; // run at 30fps
app.ticker.minFPS = 10; // cap deltaTime at 10fps worth if frames drop
```
`maxFPS` enforces a ceiling by skipping updates. `minFPS` caps `deltaTime` so large frame drops don't produce enormous deltas that break physics. Defaults: no `maxFPS`, `minFPS: 10`.
## Common Mistakes
### [CRITICAL] Treating the ticker callback arg as a number
Wrong:
```ts
app.ticker.add((dt) => {
sprite.rotation += dt; // dt is the Ticker instance, not a number
});
```
Correct:
```ts
app.ticker.add((ticker) => {
sprite.rotation += ticker.deltaTime;
});
```
v8 passes the `Ticker` instance to the callback, not a delta. Old v7 code that used `(dt) => sprite.x += dt` compiles but produces `NaN` because `dt` is an object.
### [HIGH] Using `updateTransform` for per-frame logic
Wrong:
```ts
class MySprite extends Sprite {
updateTransform() {
super.updateTransform();
this.rotation += 0.01;
}
}
```
Correct:
```ts
class MySprite extends Sprite {
constructor() {
super();
this.onRender = () => {
this.rotation += 0.01;
};
}
}
```
`updateTransform` was removed in v8. Use `onRender` for per-object per-frame logic.
### [MEDIUM] Assuming ticker callbacks run after render
Wrong:
```ts
app.ticker.add(() => {
readPixelsFromCanvas(); // empty; render hasn't happened yet this frame
});
```
Correct:
```ts
app.ticker.add(
() => {
readPixelsFromCanvas();
},
undefined,
UPDATE_PRIORITY.UTILITY,
);
```
Callbacks added at the default priority (`NORMAL = 0`) run _before_ the render call (at `LOW = -25`). Use `UTILITY = -50` for post-render work like pixel readbacks or DOM sync.
## API Reference
- [Ticker](https://pixijs.download/release/docs/ticker.Ticker.html.md)
- [TickerPlugin](https://pixijs.download/release/docs/app.TickerPlugin.html.md)
- [UPDATE_PRIORITY](https://pixijs.download/release/docs/ticker.UPDATE_PRIORITY.html.md)
- [Application](https://pixijs.download/release/docs/app.Application.html.md)
@@ -0,0 +1,287 @@
# Renderers: WebGPU, WebGL, and Canvas
PixiJS v8 ships three renderers: `WebGPURenderer` (fastest where available), `WebGLRenderer` (broad compatibility, WebGL2), and `CanvasRenderer` (a last-resort 2D Canvas backend). `autoDetectRenderer` (used internally by `Application.init`) picks the best available backend based on a preference list.
**Status:** `WebGLRenderer` is recommended for production. `WebGPURenderer` is feature-complete but still experimental; browser implementations have inconsistencies. `CanvasRenderer` is a fallback for environments without WebGL/WebGPU and supports a reduced feature set.
## Quick Start
```ts
const app = new Application();
await app.init({
preference: ["webgpu", "webgl"],
width: 800,
height: 600,
background: 0x222233,
antialias: true,
});
document.body.appendChild(app.canvas);
```
`preference` can be a single string (try that first, fall back to default order) or an array (use only these, in this order; others are excluded). Default priority when `preference` is not set: `webgl`, `webgpu`, `canvas`.
## Core Patterns
### Preference forms
```ts
// Single string: try webgpu first, fall back through defaults
await app.init({ preference: "webgpu" });
// Array: only try listed backends in order
await app.init({ preference: ["webgpu", "webgl"] });
// Array acts as a blocklist; anything not listed is excluded
await app.init({ preference: ["webgl"] }); // never uses webgpu or canvas
// Force canvas (legacy-only environments)
await app.init({ preference: ["canvas"] });
```
A string form falls through to defaults if the preferred backend isn't available. An array form excludes any backend not in the list, even if the preferred one fails.
### Per-renderer options
```ts
await app.init({
width: 800,
height: 600,
webgpu: { antialias: true, powerPreference: "high-performance" },
webgl: { antialias: true, premultipliedAlpha: false },
canvasOptions: { backgroundAlpha: 0 },
});
```
Common options live at the top level; renderer-specific options go in `webgpu`, `webgl`, or `canvasOptions`. Only the options for the selected renderer apply; the others are discarded.
### Systems and pipes
Each renderer is composed of a fixed set of `System`s (lifecycle services: textures, buffers, state, events, filters, masks) and a set of `RenderPipe`s (per-renderable instruction builders: sprite, graphics, mesh, particle, text, tiling-sprite).
- `Systems` run once per renderer lifecycle and manage GPU state.
- `RenderPipes` run every frame, one per renderable type. They batch instructions for their object class and flush them to the GPU.
Writing a custom renderable means implementing a `RenderPipe`, a `BatchableX` class, and registering both via the extensions system. See `pixijs-custom-rendering`.
### Lazy-loading backend-specific systems and pipes
Systems and pipes that only one backend needs can stay out of the main bundle. Register a renderer loader (`ExtensionType.WebGLLoader`, `ExtensionType.WebGPULoader`, or `ExtensionType.CanvasLoader`) whose `load()` dynamic-imports the module that registers them. During `init`, the renderer awaits every loader for its own backend after the environment extensions load and before it creates its systems and pipes; loaders for other backends never run.
```ts
import { extensions, ExtensionType } from "pixi.js";
extensions.add({
extension: { type: ExtensionType.WebGLLoader, name: "my-plugin" },
load: () => import("./gl/register"), // registers WebGL systems and pipes on import
});
```
Loader names are unique per backend; a second loader with the same name is ignored. Loaders run concurrently; registered systems and pipes are ordered by their own `priority`, not by loader completion. `skipExtensionImports: true` skips loaders too, so custom builds import backend modules directly.
### Direct renderer construction
```ts
import { WebGLRenderer } from "pixi.js";
const renderer = new WebGLRenderer();
await renderer.init({ width: 800, height: 600 });
```
Most apps use `Application.init` or `autoDetectRenderer()`, but you can instantiate a specific renderer directly when the target environment is known (tests, tooling, editor integrations).
### `renderer.render()` options
The `.render()` method accepts either a `Container` or an options object:
```ts
// shorthand: just render the stage
renderer.render(app.stage);
// options form: control clearing, transform, or a render target
renderer.render({
container: app.stage,
clear: true,
transform: new Matrix(),
});
// render into a mip level, array layer, cube face or 3D slice of a texture
renderer.render({
container: myContainer,
target: renderTexture,
mipLevel: 1,
layer: 0,
});
// store the capture in screen orientation (for 3D UVs)
renderer.render({ container: scene3d, target: renderTexture, flipY: true });
```
`container` is the scene root to draw. `target` is a separate destination (e.g. a `RenderTexture`). `mipLevel > 0` is useful for custom LOD systems or manual mipmap generation. `flipY` defaults to `false`; set it to store a texture render un-flipped, with winding adjusted so back-face culling still works. `layer` selects an array layer, a cube face, or a depth slice of a 3D `TextureSource` (`depth`); pass the source itself as `target`.
### Render targets
```ts
import { CLEAR, RenderTarget, Texture, TextureSource } from "pixi.js";
const depthSource = new TextureSource({ width: 512, height: 512, format: "depth24plus-stencil8" });
const target = new RenderTarget({
colorAttachments: [{ texture: new TextureSource({ width: 512, height: 512 }), loadOp: "clear" }],
depthStencilAttachment: { texture: depthSource, depthLoadOp: "clear" },
});
renderer.render({ container, target });
// bind directly from custom render code; always use the options object
renderer.renderTarget.push({ target, clear: CLEAR.COLOR, mipLevel: 0 });
renderer.renderTarget.pop();
const saved = renderer.renderTarget.getBindState();
renderer.renderTarget.bind(saved); // replays without clearing
// copy the depth attachment into another depth-format texture (WebGL2 and WebGPU)
const depthCopy = new Texture({
source: new TextureSource({ width: 512, height: 512, format: "depth24plus-stencil8" }),
});
renderer.renderTarget.copyDepthTexture(target, depthCopy, { x: 0, y: 0 }, { width: 512, height: 512 });
```
- `RenderTarget` takes WebGPU-style `colorAttachments`/`depthStencilAttachment` or the older `colorTextures`/`depth`/`stencil`/`depthStencilTexture` options. `colorTextures: 0` with `depth: true` makes a depth-only target.
- Positional `bind(target, clear, ...)` and `push(...)` are deprecated since 8.20.0. `pop()` throws when the stack is empty.
- `copyDepthTexture` needs WebGL2 or WebGPU and a depth-format destination. The next render into the destination target must clear color only (`clear: CLEAR.COLOR`), or the copied depth is lost.
- Destroy a target you constructed with `target.destroy()`; the renderer releases the GPU objects it built for it.
### Resizing, texture generation, and interop
```ts
renderer.resize(window.innerWidth, window.innerHeight);
const texture = renderer.generateTexture(displayObject);
// Mixing PixiJS with Three.js (or any other WebGL/WebGPU library)
threeRenderer.resetState();
threeRenderer.render(scene, camera);
pixiRenderer.resetState();
pixiRenderer.render({ container: stage });
```
Call `resetState()` before each library renders. Both libraries leave GPU state (bound textures, blend modes, active shaders) that conflicts with the other; without `resetState()`, objects can disappear or blend incorrectly.
### Destroying a renderer
```ts
renderer.destroy();
```
Releases GPU resources, systems, pipes, and event listeners. A destroyed renderer cannot be used for further rendering.
### Manual rendering
```ts
await app.init({ autoStart: false, width: 800, height: 600 });
function frame() {
app.renderer.render(app.stage);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```
Disable the automatic ticker plugin with `autoStart: false`, then call `app.renderer.render(app.stage)` yourself. Useful for integrating with an external game loop.
### Renderer selection at runtime
```ts
console.log(app.renderer.name); // 'webgl', 'webgpu', or 'canvas'
```
After `init`, `app.renderer` is the concrete class. Use `app.renderer.name` (a string) to branch on backend; `app.renderer.type` exists but is a numeric id meant for internal dispatch — prefer `name` in user code.
### Supports check
```ts
if (await isWebGPUSupported()) {
// ok to prefer webgpu
}
if (isWebGLSupported()) {
// ok to prefer webgl
}
// after init, WebGPU-only capability flags
if (renderer.name === "webgpu") {
renderer.device.extensions.transientAttachment; // GPUTextureUsage.TRANSIENT_ATTACHMENT available
renderer.limits.supportsOverrideConstants; // pipeline constants vs. source-baked overrides
}
```
Both helpers are exported from `pixi.js`. Useful if you want to tell the user which backend is about to be used before calling `app.init`.
### Context and device loss
```ts
// both renderers recover on their own; only render bundles need re-recording
if (!renderer.encoder.isBundleValid(bundle)) {
bundle = record();
}
```
The WebGL renderer restores itself after `webglcontextrestored`. The WebGPU renderer requests a new device when the browser reports `GPUDevice.lost` and rebuilds its GPU resources on the next render. A device you pass through the WebGPU `gpu` option is neither restored nor destroyed by PixiJS. A render bundle recorded on a lost device fails `isBundleValid` and must be re-recorded.
## Common Mistakes
### [HIGH] Expecting WebGPU everywhere
Wrong:
```ts
await app.init({ preference: ["webgpu"] });
```
Correct:
```ts
await app.init({ preference: ["webgpu", "webgl"] });
```
WebGPU is not yet available on all browsers. An array-form preference of only `['webgpu']` will fail init on unsupported browsers (no fallback). Always include `'webgl'` as a fallback unless you've verified WebGPU support upstream.
### [MEDIUM] Assuming CanvasRenderer supports everything
CanvasRenderer does not support filters, masks beyond basic clipping, compressed textures, or custom shaders. It's intended as a last-resort for environments that can't run WebGL. If you need full feature parity, target WebGL or WebGPU.
### [MEDIUM] Calling render before init
Wrong:
```ts
const app = new Application();
app.renderer.render(app.stage);
await app.init();
```
Correct:
```ts
const app = new Application();
await app.init();
app.renderer.render(app.stage);
```
`app.renderer` is populated only after `init()` resolves. Any access before that is `undefined`.
## API Reference
- [autoDetectRenderer](https://pixijs.download/release/docs/rendering.autoDetectRenderer.html.md)
- [AbstractRenderer](https://pixijs.download/release/docs/rendering.AbstractRenderer.html.md)
- [WebGLRenderer](https://pixijs.download/release/docs/rendering.WebGLRenderer.html.md)
- [WebGPURenderer](https://pixijs.download/release/docs/rendering.WebGPURenderer.html.md)
- [CanvasRenderer](https://pixijs.download/release/docs/rendering.CanvasRenderer.html.md)
- [RenderTarget](https://pixijs.download/release/docs/rendering.RenderTarget.html.md)
- [RenderTargetSystem](https://pixijs.download/release/docs/rendering.RenderTargetSystem.html.md)