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,405 @@
---
name: pixijs-custom-rendering
description: "Use this skill when writing custom shaders, uniforms, filters, batchers, or low-level draw code in PixiJS v8. Covers Shader.from({gl, gpu, resources}), GlProgram/GpuProgram, UniformGroup with typed uniforms (f32, vec2, mat4x4), UBO mode, textures as resources, TextureView for depth sampling, 3D and array textures (depth, arrayLayerCount, sampler3D, texture_3d), WebGPU storage textures (storage: true), WGSL override constants, custom bind group layouts (gpuLayout), partial buffer updates (Buffer.update), Geometry.vertexCount/indexCount, TexturePool scratch textures, State winding and culling (clockwiseFrontFace, cullMode), WebGPU render bundles, custom Filter via Filter.from, GLSL ES 3.0 conventions (finalColor), uBackTexture sampling, pixi.js/unsafe-eval for strict CSP, custom Batcher and InstructionPipe.destroyInstructionSet via extensions. Triggers on: Shader, GLSL, WGSL, uniform, custom shader, blendRequired, ShaderOverrides, bind group layout, depth texture, 3D texture, sampler3D, texture_3d, storage texture, getSize, indexCount, TexturePool, getOptimalTexture, destroyInstructionSet, beginBundle, executeBundle, RenderBundle."
license: MIT
---
Custom shaders bind GLSL and WGSL programs to scene objects via `Shader.from({ gl, gpu, resources })`. Uniforms live in typed `UniformGroup`s, textures are passed as separate resources, and the same shader can target both WebGL and WebGPU.
## Quick Start
```ts
const uniforms = new UniformGroup({
uTime: { value: 0, type: "f32" },
});
const shader = Shader.from({
gl: { vertex: vertexSrc, fragment: fragmentSrc },
resources: { uniforms },
});
const geometry = new MeshGeometry({
positions: new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]),
uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
});
const mesh = new Mesh({ geometry, shader });
app.stage.addChild(mesh);
app.ticker.add(() => {
shader.resources.uniforms.uniforms.uTime = performance.now() / 1000;
});
```
**Related skills:** `pixijs-filters` (built-in filters), `pixijs-scene-mesh` (custom geometry), `pixijs-performance` (batch optimization), `pixijs-migration-v8` (shader API migration from v7).
## Core Patterns
### Dual-renderer shader (WebGL + WebGPU)
```ts
import { Shader, GlProgram, GpuProgram, UniformGroup } from "pixi.js";
const glVertex = `...`; // GLSL vertex (write `#version 300 es` yourself if you want WebGL2/GLSL ES 3.0)
const glFragment = `...`; // GLSL fragment
const wgslSource = `...`; // WGSL combined
const shader = Shader.from({
gl: { vertex: glVertex, fragment: glFragment },
gpu: {
// entryPoint names are arbitrary; they must match the @vertex / @fragment
// function names in your WGSL source. PixiJS ships examples using
// 'mainVert' / 'mainFrag' but `main` is equally valid.
vertex: { entryPoint: "mainVert", source: wgslSource },
fragment: { entryPoint: "mainFrag", source: wgslSource },
},
resources: {
myUniforms: new UniformGroup({
uColor: { value: new Float32Array([1, 0, 0, 1]), type: "vec4<f32>" },
uMatrix: { value: new Float32Array(16), type: "mat4x4<f32>" },
}),
},
});
```
If only `gl` is provided, the shader works with WebGL only. If only `gpu` is provided, it works with WebGPU only. The `compatibleRenderers` bitmask is set automatically.
`GlProgram` does **not** auto-inject `#version 300 es`. If you write `#version 300 es` yourself, PixiJS preserves it and treats the shader as GLSL ES 3.0; otherwise it injects WebGL1 compat macros (`#define in varying`, `#define texture texture2D`) and runs the shader as WebGL1-style GLSL. `GlProgram` always injects a default precision (`highp` vertex, `mediump` fragment) and the program name. It also declares `highp` for sampler types GLSL ES 3.0 gives no default (`usampler2D`, `isampler2D`, `sampler2DArray`, `sampler3D`, and others), so you don't need a precision line for them; one you write yourself is kept. `sampler2D` and `samplerCube` keep their `lowp` default. For GLSL ES 3.0, use `in`/`out` instead of `attribute`/`varying`, `texture()` instead of `texture2D()`, and an `out vec4` instead of `gl_FragColor`.
### Textures as resources
Textures are resources, not uniforms. Pass the texture's `source` and `style` separately:
```ts
import { Shader, UniformGroup, Texture, Assets } from "pixi.js";
const texture = await Assets.load("myImage.png");
const shader = Shader.from({
gl: { vertex: vertSrc, fragment: fragSrc },
resources: {
uTexture: texture.source,
uSampler: texture.source.style,
myUniforms: new UniformGroup({
uAlpha: { value: 1.0, type: "f32" },
}),
},
});
// Swap texture at runtime
shader.resources.uTexture = otherTexture.source;
```
Resources are a flat key-value map. The key must match the uniform/binding name in the shader source.
Resources can also be plain objects (auto-wrapped into `UniformGroup`):
```ts
const shader = Shader.from({
gl: { vertex: vertSrc, fragment: fragSrc },
resources: {
myUniforms: {
uTime: { value: 0, type: "f32" },
},
},
});
```
### UBO mode (Uniform Buffer Objects)
UBO mode packs uniforms into a single GPU buffer. Required for WebGPU; optional (WebGL2+) for WebGL.
```ts
import { UniformGroup } from "pixi.js";
const ubo = new UniformGroup(
{
uProjection: { value: new Float32Array(16), type: "mat4x4<f32>" },
uAlpha: { value: 1.0, type: "f32" },
},
{ ubo: true, isStatic: true },
);
// Must call update() manually when isStatic is true
ubo.uniforms.uAlpha = 0.5;
ubo.update();
```
UBO rules:
- Only `f32` and `i32` based types are supported (no `u32`). Matrices are float-only.
- Samplers/textures cannot go in a UBO.
- The UniformGroup name in resources must exactly match the UBO block name in the shader.
- Structure and order must exactly match the shader layout.
- UBO sync uses `new Function` under the hood. In strict-CSP environments (no `unsafe-eval`), import `pixi.js/unsafe-eval` once at startup to swap in the fallback sync path; without it, UBO-backed shaders (and therefore WebGPU) will throw on first use.
### Custom filter
`Filter.from({ gl, resources })` is the shorthand. Pass only a fragment shader; PixiJS supplies a default vertex shader that handles output frame positioning.
```ts
import { Filter } from "pixi.js";
const filter = Filter.from({
gl: {
fragment: `
in vec2 vTextureCoord;
out vec4 finalColor;
uniform sampler2D uTexture;
uniform float uStrength;
void main(void) {
vec4 color = texture(uTexture, vTextureCoord);
finalColor = mix(color, vec4(1.0 - color.rgb, color.a), uStrength);
}
`,
},
resources: {
filterUniforms: {
uStrength: { value: 0.5, type: "f32" },
},
},
});
filter.resources.filterUniforms.uniforms.uStrength = 1.0;
```
For a custom vertex shader, use `new Filter({ glProgram: new GlProgram({ vertex, fragment }), resources })`.
#### Filter shader conventions (GLSL ES 3.0)
- `in vec2 vTextureCoord;` instead of `varying vec2 vTextureCoord;`
- `out vec4 finalColor;` instead of `gl_FragColor`
- `texture(uTexture, uv)` instead of `texture2D(uTexture, uv)`
- The default vertex shader exposes `uInputSize`, `uOutputFrame`, `uOutputTexture` and helpers `filterVertexPosition()` / `filterTextureCoord()`
#### Sampling the render target behind the filter
Set `blendRequired: true` and sample `uBackTexture` in the fragment shader. PixiJS copies the destination pixels into that uniform before running the filter:
```ts
const blendFilter = Filter.from({
gl: { fragment: blendFragSrc },
resources: { uniforms: { uAmount: { value: 0.5, type: "f32" } } },
blendRequired: true,
});
```
Only enable `blendRequired` when you need it; it forces an extra GPU copy every frame.
### Updating uniforms at runtime
```ts
// Access the UniformGroup via resources
shader.resources.myUniforms.uniforms.uTime = performance.now() / 1000;
// For isStatic UBOs, call update() after changing values
shader.resources.myUniforms.update();
```
### Advanced GPU features
See [references/advanced-gpu.md](references/advanced-gpu.md) for full samples of:
- **Partial buffer and texture uploads**: `buffer.update(sizeInBytes, offsetInBytes)` uploads only the changed byte range; `bufferImageSource.update(startTexel, endTexel)` uploads only a texel range of a data texture.
- **Vertex and index counts, winding, culling**: `geometry.vertexCount` (replaces the deprecated `getSize()`), `geometry.indexCount` to draw a prefix of a shared index buffer, `state.clockwiseFrontFace` and `cullMode`.
- **WGSL override constants** (WebGPU): `Shader.from({ gpu, resources, overrides: { STEPS: 8 } })`; each distinct set compiles its own pipeline.
- **Custom bind group layouts** (WebGPU): generate the default with `generateGpuLayoutGroups(extractStructAndGroups(source))`, edit it, pass it as `gpuLayout`.
- **Depth sampling with `TextureView`** (WebGPU): bind `new TextureView(depth, { aspect: "depth-only" })` as a resource while the target's depth attachment is `depthReadOnly`.
- **Integer textures**: `BufferImageSource` with `rgba32uint` etc., `usampler2D`/`texelFetch` and `texture_2d<u32>`/`textureLoad`, `scaleMode: "nearest"`.
- **3D and array textures**: `depth` or `arrayLayerCount` on a `TextureSource`/`BufferImageSource`, sampled with `sampler3D`/`texture_3d<f32>` or `sampler2DArray`/`texture_2d_array<f32>`; they upload whole, and `renderer.render({ container, target: source, layer })` draws into one slice or layer.
- **Storage textures** (WebGPU): `storage: true` on a `TextureSource`, then `renderer.texture.getGpuSource(source).createView()` to write it from your own compute pass.
- **Render bundles** (WebGPU): record draws once with `encoder.beginBundle()` / `endBundle()` and replay with `executeBundle()` while `isBundleValid()` holds.
- **Pooled scratch textures**: `TexturePool.getOptimalTexture({ width, height, resolution, antialias })` and `returnTexture()`.
### Uniform type reference
See [references/uniform-types.md](references/uniform-types.md) for the complete table of supported types, their WGSL/GLSL equivalents, and value formats.
### Custom Batcher (extension-based)
The `Batcher` abstract class enables custom batching for specialized rendering. Subclass it and register via extensions:
```ts
import { Batcher, extensions, ExtensionType } from "pixi.js";
import type {
BatcherOptions,
BatchableMeshElement,
BatchableQuadElement,
Geometry,
Shader,
} from "pixi.js";
class MyBatcher extends Batcher {
public static extension = {
type: [ExtensionType.Batcher],
name: "my-batcher",
};
public name = "my-batcher";
protected vertexSize = 6; // floats per vertex
public geometry: Geometry;
public shader: Shader;
constructor(options: BatcherOptions) {
super(options);
// Initialize geometry and shader
}
public packAttributes(
element: BatchableMeshElement,
float32View: Float32Array,
uint32View: Uint32Array,
index: number,
textureId: number,
): void {
// Pack mesh vertex attributes into the batch buffer
}
public packQuadAttributes(
element: BatchableQuadElement,
float32View: Float32Array,
uint32View: Uint32Array,
index: number,
textureId: number,
): void {
// Pack quad vertex attributes into the batch buffer
}
}
extensions.add(MyBatcher);
```
Elements reference the batcher by `batcherName`. The `BatchableElement` interface requires: `batcherName`, `texture`, `blendMode`, `indexSize`, `attributeSize`, `topology`, and `packAsQuad`.
A custom `InstructionPipe` that caches state per `InstructionSet` (the way `BatcherPipe` keeps its batchers) should implement `destroyInstructionSet(instructionSet)`. The renderer calls it when the owning render group is destroyed, so the cached GPU objects are released with it instead of leaking.
```ts
public destroyInstructionSet(instructionSet: InstructionSet): void {
this._cache[instructionSet.uid]?.destroy();
delete this._cache[instructionSet.uid];
}
```
## Common Mistakes
### [CRITICAL] Old Shader.from(vertex, fragment, uniforms) constructor
Wrong:
```ts
const shader = Shader.from(vertex, fragment, { uTime: 1 });
```
Correct:
```ts
const shader = Shader.from({
gl: { vertex, fragment },
resources: {
uniforms: new UniformGroup({
uTime: { value: 1, type: "f32" },
}),
},
});
```
v8 requires an options object with `gl`/`gpu` programs and `resources`. The positional API was removed.
### [CRITICAL] UniformGroup without type annotation
Wrong:
```ts
new UniformGroup({ uTime: 1 });
```
Correct:
```ts
new UniformGroup({ uTime: { value: 1, type: "f32" } });
```
Every uniform requires an explicit `{ value, type }` pair. Omitting the type causes a runtime error: "Uniform type undefined is not supported."
### [HIGH] UBO with unsupported types or wrong structure
UBO mode supports `f32` and `i32` based types (scalars and vectors). `u32` is not in the supported `UniformGroup` type list and will throw. Matrices are float-only (`mat*<f32>`). Samplers cannot be placed in UBOs.
The struct name and field order must exactly match the shader's UBO declaration. Mismatches produce garbled rendering with no error.
### [HIGH] Putting textures in UniformGroup
Wrong:
```ts
new UniformGroup({
uTexture: { value: texture, type: "f32" },
});
```
Correct:
```ts
const shader = Shader.from({
gl: { vertex, fragment },
resources: {
uTexture: texture.source,
uSampler: texture.source.style,
myUniforms: new UniformGroup({
uAlpha: { value: 1.0, type: "f32" },
}),
},
});
```
Textures are resources, not uniforms. Pass `texture.source` (TextureSource) and `texture.source.style` (TextureStyle) as top-level resource entries.
### [HIGH] Replaying a render bundle against a different render target
Wrong:
```ts
const bundle = encoder.endBundle();
// later, on every frame, regardless of what is bound
encoder.executeBundle(bundle);
```
Correct:
```ts
if (!bundle || !encoder.isBundleValid(bundle)) {
bundle = record();
}
encoder.executeBundle(bundle);
```
A bundle bakes the attachments and winding of the pass it was recorded in, and the device it was recorded on. Replaying it under a different target either fails WebGPU validation for the whole frame or silently renders inside out; replaying it after a device loss is rejected outright.
### [MEDIUM] Reading Geometry.getSize()
`geometry.getSize()` is deprecated since 8.20.0 and logs a warning. Use `geometry.vertexCount`, which is cached and only recomputed when buffers or attributes change.
## API Reference
- [Shader](https://pixijs.download/release/docs/rendering.Shader.html.md)
- [GlProgram](https://pixijs.download/release/docs/rendering.GlProgram.html.md)
- [GpuProgram](https://pixijs.download/release/docs/rendering.GpuProgram.html.md)
- [UniformGroup](https://pixijs.download/release/docs/rendering.UniformGroup.html.md)
- [Filter](https://pixijs.download/release/docs/filters.Filter.html.md)
- [Batcher](https://pixijs.download/release/docs/rendering.Batcher.html.md)
- [BatcherPipe](https://pixijs.download/release/docs/rendering.BatcherPipe.html.md)
- [ShaderOverrides](https://pixijs.download/release/docs/rendering.ShaderOverrides.html.md)
- [TextureView](https://pixijs.download/release/docs/rendering.TextureView.html.md)
- [RenderTarget](https://pixijs.download/release/docs/rendering.RenderTarget.html.md)
- [GpuEncoderSystem](https://pixijs.download/release/docs/rendering.GpuEncoderSystem.html.md)
- [RenderBundle](https://pixijs.download/release/docs/rendering.RenderBundle.html.md)
- [Geometry](https://pixijs.download/release/docs/rendering.Geometry.html.md)
- [State](https://pixijs.download/release/docs/rendering.State.html.md)
@@ -0,0 +1,244 @@
# Advanced GPU features
Lower-level rendering APIs for custom draw code. Items marked WebGPU only are ignored or unavailable on the WebGL renderer; branch on `renderer.name === "webgpu"` before relying on them.
## Partial buffer updates
```ts
import { Buffer, BufferUsage } from "pixi.js";
const buffer = new Buffer({
data: new Float32Array(4096),
usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,
});
buffer.data.set(newVertices, 256);
buffer.update(newVertices.byteLength, 256 * 4); // size and offset in bytes
```
`update()` with no arguments re-uploads the whole buffer. Pass a byte size and byte offset to upload only the range you changed. Works on WebGL and WebGPU.
## Partial texture uploads
```ts
import { BufferImageSource } from "pixi.js";
const data = new Float32Array(4096 * 64 * 4); // rgba32float: 4 floats per texel
const source = new BufferImageSource({ resource: data, width: 4096, height: 64 });
data.fill(1, 100 * 4, 116 * 4); // change texels 100 to 115
source.update(100, 116); // upload only those 16 texels
```
Texel `i` sits at `x = i % width`, `y = floor(i / width)`, and `end` is exclusive. The range applies to that call only, so track the lowest and highest changed texel yourself and call `update` once per frame. `update()` with no arguments uploads the whole texture. Works on WebGL and WebGPU. A 3D texture (`depth`) or 2D array (`arrayLayerCount`) always uploads whole, so call `update()` with no range.
## Vertex count, index count, winding, and culling
```ts
const count = geometry.vertexCount; // cached, from the first non-instanced attribute
// several geometries share one index buffer sized for the biggest batch;
// each draws only the prefix it currently uses
const quads = new Geometry({
attributes: { aPosition: positions },
indexBuffer: sharedIndices,
indexCount: liveQuads * 6,
});
quads.indexCount = 12; // read at draw time; no re-upload
const state = new State();
state.culling = true;
state.clockwiseFrontFace = true; // or state.cullMode = "front"
```
`geometry.getSize()` is deprecated since 8.20.0; read `vertexCount` instead. `indexCount` of `0` (the default) draws the whole index buffer; any other value draws that many indices. A `size` passed to `encoder.draw()` still wins. `clockwiseFrontFace` selects which winding counts as front-facing on both renderers. When rendering into a texture PixiJS inverts the winding to match the flipped projection; call `renderer.renderTarget.isFrontFaceInverted()` if your own code needs the resolved orientation, or `isFrontFaceInverted(target, flipY)` to ask about a `RenderTarget` before binding it (`renderer.renderTarget.getRenderTarget(texture)` returns one for a texture).
## WGSL override constants (WebGPU only)
```ts
const source = /* wgsl */ `
override BLUR_STEPS: u32 = 4u;
// ...
`;
const shader = Shader.from({
gpu: {
vertex: { source, entryPoint: "vsMain" },
fragment: { source, entryPoint: "fsMain" },
},
resources: { uniforms },
overrides: { BLUR_STEPS: 8 },
});
```
`overrides` takes a plain `Record<string, number>` or a `ShaderOverrides` instance. Values are fixed when the shader is created and become part of the pipeline cache key, so every distinct set compiles its own pipeline. To change a value, create a new shader. On browsers without pipeline constants (Safari) PixiJS substitutes the values into the WGSL source; `renderer.limits.supportsOverrideConstants` tells you which path is active. WebGL ignores `overrides` entirely.
## Custom bind group layout (WebGPU only)
```ts
import { GpuProgram, extractStructAndGroups, generateGpuLayoutGroups } from "pixi.js";
const gpuLayout = generateGpuLayoutGroups(extractStructAndGroups(source));
// narrow one texture binding to the fragment stage
gpuLayout[0][1].visibility = GPUShaderStage.FRAGMENT;
const program = new GpuProgram({
vertex: { source, entryPoint: "vsMain" },
fragment: { source, entryPoint: "fsMain" },
gpuLayout,
});
```
`generateGpuLayoutGroups` is the same generator `GpuProgram` runs when `gpuLayout` is omitted, and it marks every binding visible to both stages. Generate the default, edit the entries you care about, and pass the whole array back rather than hand-writing the layout.
## Sampling a depth texture with TextureView (WebGPU only)
```ts
import { RenderTarget, Shader, State, TextureSource, TextureView } from "pixi.js";
const depth = new TextureSource({ width: 512, height: 512, format: "depth24plus-stencil8" });
const color = new TextureSource({ width: 512, height: 512 });
// pass 1: write depth
const writeTarget = new RenderTarget({
colorAttachments: [{ texture: color, loadOp: "clear", clearValue: [0, 0, 0, 1] }],
depthStencilAttachment: { texture: depth, depthLoadOp: "clear", depthClearValue: 1 },
});
// pass 2: keep the same depth attached read-only while sampling it
const readTarget = new RenderTarget({
colorAttachments: [{ texture: color, loadOp: "load" }],
depthStencilAttachment: { texture: depth, depthReadOnly: true },
});
const shader = Shader.from({
gpu: { vertex: { source, entryPoint: "vsMain" }, fragment: { source, entryPoint: "fsMain" } },
resources: { uDepthTexture: new TextureView(depth, { aspect: "depth-only" }) },
});
```
Declare `@group(0) @binding(1) var uDepthTexture: texture_depth_2d;` in WGSL and read it with `textureLoad`. Use a `State` with `depthMask = false` in the read pass. A `TextureView` is a bind resource like a `TextureSource`; on WebGL it binds the underlying source and the descriptor is ignored.
## Integer textures
```ts
import { BufferImageSource, Shader } from "pixi.js";
const ids = new BufferImageSource({
resource: new Uint32Array([1, 2, 3, 4]), // picks rgba32uint
width: 1,
height: 1,
scaleMode: "nearest",
});
const shader = Shader.from({
gl: { vertex: vertSrc, fragment: fragSrc },
gpu: { vertex: { source, entryPoint: "vsMain" }, fragment: { source, entryPoint: "fsMain" } },
resources: { uIds: ids },
});
```
Integer formats (`*uint`, `*sint`) hold exact integers. Use them where a float texture would lose bits, since small integers are denormal floats and GPUs may flush them to zero. They can't be filtered, so set `scaleMode: "nearest"`. `BufferImageSource` infers `rgba32uint` from a `Uint32Array` and `rgba16uint` from a `Uint16Array`; pass `format: "rgba32sint"` (or another signed format) explicitly for signed data. It defaults integer formats to `alphaMode: "no-premultiply-alpha"` because integer data can't be premultiplied on upload.
In GLSL ES 3.0, declare `uniform usampler2D uIds;` (or `isampler2D`) and read it with `texelFetch(uIds, ivec2(x, y), 0)`. GLSL ES 3.0 gives integer samplers no default precision, so PixiJS declares `highp` for them and you don't need a precision line. A precision line you write yourself is kept. In WGSL, declare `@group(0) @binding(1) var uIds: texture_2d<u32>;` (or `<i32>`) and read it with `textureLoad(uIds, vec2<i32>(x, y), 0)`; the generated bind group layout takes its `sampleType` from the `<u32>` / `<i32>` suffix. PixiJS can't render into integer textures yet.
## 3D and array textures
```ts
import { BufferImageSource } from "pixi.js";
const size = 64;
const noise = new BufferImageSource({
resource: new Uint8Array(size * size * size * 4), // slice after slice, row-major
width: size,
height: size,
depth: size, // or arrayLayerCount: n for a 2D array
format: "rgba8unorm",
});
```
`depth` on a `TextureSource` or `BufferImageSource` makes a `"3d"` texture, and `arrayLayerCount > 1` makes a `"2d-array"` texture. A texture can't have both, and TypeScript rejects options that set both. Pass `viewDimension` only when the size doesn't decide it, such as `"cube"` for 6 layers. `dimensions` is deprecated; leave it out. These textures need WebGL2 or WebGPU; WebGL1 has no 3D or array textures.
The buffer holds the slices (or layers) one after another, each in row-major order, so texel `(x, y, z)` sits at index `x + y * width + z * width * height`. `resolution` doesn't scale `depth`. A 3D or array `BufferImageSource` defaults to `alphaMode: "no-premultiply-alpha"` and always uploads whole, so `update()` takes no range.
In GLSL ES 3.0, declare `uniform sampler3D` or `uniform sampler2DArray`. In WGSL, declare `texture_3d<f32>` or `texture_2d_array<f32>`. PixiJS adds the precision line for `sampler3D` and `sampler2DArray`, as for integer samplers above.
`rgba32float`, the default for a `Float32Array`, needs an optional feature for linear filtering that PixiJS doesn't request on WebGPU. Use `scaleMode: "nearest"` with it, or pick `rgba8unorm`, `r8unorm` or `rgba16float` for smooth sampling.
To draw into one slice or layer, pass the source itself as `target` and pick the slice with `layer`: `renderer.render({ container, target: noise, layer: z, clear: true })`. `layer` selects an array layer, a cube face, or a 3D depth slice. `RenderTexture.create` doesn't take `depth`, so use the `TextureSource` directly. `renderer.renderTarget.push({ target, layer })` takes `layer` too.
## Storage textures (WebGPU only)
```ts
import { TextureSource } from "pixi.js";
const volume = new TextureSource({ width: 64, height: 64, depth: 64, format: "rgba8unorm", storage: true });
// bind this view to a texture_storage_3d<rgba8unorm, write> in your own compute pass
const view = renderer.texture.getGpuSource(volume).createView();
```
`storage: true` adds `GPUTextureUsage.STORAGE_BINDING`, so your own compute pass can write the texture through `renderer.texture.getGpuSource(source).createView()`. PixiJS still samples it like any other texture. WebGL ignores the option.
Every device accepts `rgba8unorm`, `rgba16float`, `r32float`, `rg32float`, `rgba32float` and the matching integer formats as storage textures. `bgra8unorm` needs the `bgra8unorm-storage` feature, and formats such as `r8unorm` or `r16float` need `texture-formats-tier1`. PixiJS enables both features when the GPU has them. WebGPU rejects any other format when the texture is created.
`autoGenerateMipmaps` on a 3D texture uses `gl.generateMipmap` on WebGL. WebGPU writes the mips with a compute shader, so the texture needs `storage: true` and the `rgba8unorm` or `rgba16float` format.
## Render bundles (WebGPU only)
```ts
import { RenderContainer } from "pixi.js";
import type { RenderBundle, WebGPURenderer } from "pixi.js";
let bundle: RenderBundle | null = null;
const props = new RenderContainer({
render: (renderer) => {
const encoder = (renderer as WebGPURenderer).encoder;
if (!bundle || !encoder.isBundleValid(bundle)) {
encoder.beginBundle("static-props");
encoder.draw({ geometry, shader, state });
bundle = encoder.endBundle();
}
encoder.executeBundle(bundle);
},
});
```
A bundle records draw calls once and replays them on later frames. It bakes the render target it was recorded in (formats, sample count, winding) and the device, so `isBundleValid` returns `false` after the target changes (a filter wrapping the container, `flipY` flipping) or after a device loss. Re-record when it does; otherwise WebGPU rejects the frame or draws inside out. Pass an array to `executeBundle` to replay several bundles in one call. The optional label names the bundle in GPU captures.
## Pooled scratch textures
```ts
import { TexturePool } from "pixi.js";
const scratch = TexturePool.getOptimalTexture({
width: bounds.width,
height: bounds.height,
resolution: renderer.resolution,
antialias: true,
scaleMode: "nearest",
});
const { width, height } = TexturePool.getOptimalSize(bounds.width, bounds.height, renderer.resolution);
TexturePool.returnTexture(scratch);
```
`getOptimalTexture` takes one request object: `width` and `height` are the minimum frame size; `resolution`, `antialias`, `autoGenerateMipmaps`, `format`, and `scaleMode` are optional, and each combination has its own bucket, so ask for a float or depth format directly instead of restyling a returned texture. Each axis is rounded up to the next power of two or the renderer's screen size, whichever is smaller. `getOptimalSize` reports that backing size without taking a texture, and `getSameSizeTexture(texture)` matches an existing texture's frame and resolution. The positional `getOptimalTexture(width, height, resolution, antialias)` form, `TexturePool.textureStyle`, and `enableFullScreen` are deprecated since 8.21.0.
## API Reference
- [TexturePool](https://pixijs.download/release/docs/rendering.TexturePool.html.md)
- [Buffer](https://pixijs.download/release/docs/rendering.Buffer.html.md)
- [Geometry](https://pixijs.download/release/docs/rendering.Geometry.html.md)
- [State](https://pixijs.download/release/docs/rendering.State.html.md)
- [ShaderOverrides](https://pixijs.download/release/docs/rendering.ShaderOverrides.html.md)
- [GpuProgram](https://pixijs.download/release/docs/rendering.GpuProgram.html.md)
- [TextureView](https://pixijs.download/release/docs/rendering.TextureView.html.md)
- [RenderTarget](https://pixijs.download/release/docs/rendering.RenderTarget.html.md)
- [GpuEncoderSystem](https://pixijs.download/release/docs/rendering.GpuEncoderSystem.html.md)
- [RenderBundle](https://pixijs.download/release/docs/rendering.RenderBundle.html.md)
@@ -0,0 +1,95 @@
# Uniform Types Reference
All supported PixiJS v8 uniform types for use with `UniformGroup`. These type strings are passed in the `type` field of each uniform definition.
## Type Table
| PixiJS type | WGSL equivalent | GLSL equivalent | JS value |
| ------------- | --------------- | --------------- | ----------------------------- |
| `f32` | `f32` | `float` | `number` |
| `i32` | `i32` | `int` | `number` |
| `vec2<f32>` | `vec2<f32>` | `vec2` | `Float32Array(2)` or `[x, y]` |
| `vec3<f32>` | `vec3<f32>` | `vec3` | `Float32Array(3)` |
| `vec4<f32>` | `vec4<f32>` | `vec4` | `Float32Array(4)` |
| `vec2<i32>` | `vec2<i32>` | `ivec2` | `Int32Array(2)` |
| `vec3<i32>` | `vec3<i32>` | `ivec3` | `Int32Array(3)` |
| `vec4<i32>` | `vec4<i32>` | `ivec4` | `Int32Array(4)` |
| `mat2x2<f32>` | `mat2x2<f32>` | `mat2` | `Float32Array(4)` |
| `mat3x3<f32>` | `mat3x3<f32>` | `mat3` | `Float32Array(9)` or `Matrix` |
| `mat4x4<f32>` | `mat4x4<f32>` | `mat4` | `Float32Array(16)` |
| `mat3x2<f32>` | `mat3x2<f32>` | `mat3x2` | `Float32Array(6)` |
| `mat4x2<f32>` | `mat4x2<f32>` | `mat4x2` | `Float32Array(8)` |
| `mat2x3<f32>` | `mat2x3<f32>` | `mat2x3` | `Float32Array(6)` |
| `mat4x3<f32>` | `mat4x3<f32>` | `mat4x3` | `Float32Array(12)` |
| `mat2x4<f32>` | `mat2x4<f32>` | `mat2x4` | `Float32Array(8)` |
| `mat3x4<f32>` | `mat3x4<f32>` | `mat3x4` | `Float32Array(12)` |
## Array Uniforms
For arrays of a type, use the `size` property instead of array syntax in the type:
```ts
import { UniformGroup } from "pixi.js";
// Array of 10 vec4 values
const uniforms = new UniformGroup({
uColors: { value: new Float32Array(40), type: "vec4<f32>", size: 10 },
});
```
Using `array<vec4<f32>, 10>` in the type field will throw an error directing you to use the `size` property instead.
## Usage Examples
### Scalars
```ts
import { UniformGroup } from "pixi.js";
const uniforms = new UniformGroup({
uTime: { value: 0, type: "f32" },
uIndex: { value: 0, type: "i32" },
});
uniforms.uniforms.uTime = 1.5;
uniforms.uniforms.uIndex = 3;
```
### Vectors
```ts
import { UniformGroup } from "pixi.js";
const uniforms = new UniformGroup({
uPosition: { value: new Float32Array([100, 200]), type: "vec2<f32>" },
uDirection: { value: new Float32Array([0, 1, 0]), type: "vec3<f32>" },
uColor: { value: new Float32Array([1, 0, 0, 1]), type: "vec4<f32>" },
uGridSize: { value: new Int32Array([16, 16]), type: "vec2<i32>" },
});
```
### Matrices
```ts
import { UniformGroup, Matrix } from "pixi.js";
const uniforms = new UniformGroup({
uTransform: { value: new Matrix(), type: "mat3x3<f32>" },
uProjection: { value: new Float32Array(16), type: "mat4x4<f32>" },
uRotation: { value: new Float32Array(4), type: "mat2x2<f32>" },
});
```
PixiJS `Matrix` (2D affine transform) maps to `mat3x3<f32>`. For 3D projection matrices, use a raw `Float32Array(16)` with `mat4x4<f32>`.
## UBO Constraints
When using `{ ubo: true }` on a UniformGroup:
- `f32` and `i32` based types are supported (scalars and vectors)
- Matrices are float-only (`mat*<f32>`)
- `u32` is not in the supported `UniformGroup` type list
- Samplers and textures cannot be placed in UBOs
- Field names and order must exactly match the shader's uniform block declaration
- The resource key in the shader must match the UBO block name