Skip to content

ModuleRendering / ShapesConcept: Scenes and passes

Mesh pool

Shapes and glTF models in shared buffers, so one pipeline draws any of them.

import
import { meshPool } from '@typegpu/kit'
call
meshPool.create(root, { capacity, … }) → MeshPoolalso roomFor
facts
stabilityunstablesubmitswhile setting uplifecycleinitAsync()destroy()injectsdefinitionmember
On this page

Separate mesh buffers require rebinding between draws. A mesh pool stores vertices in shared and indices in one index buffer. One pipeline can then draw any mesh by its range. Instances use a pool, and custom shaders can too.

Shapes fill one pool's vertex and index ranges

Try Add shapes until add throws. The pool has room for 2048 vertices and 8192 indices.
import {
import gltf
gltf
} from '@typegpu/kit';
import {
import meshPool
meshPool
} from '@typegpu/kit';
import {
import meshes
meshes
} from '@typegpu/kit/geometry';
const
const pool: meshPool.MeshPool<{}>
pool
=
import meshPool
meshPool
.
function create<{}>(root: TgpuRoot, options: meshPool.Options<{}>): meshPool.MeshPool<{}>

Creates shared vertex storage and an index buffer, with bounds and textures per mesh. One pipeline can draw any mesh. Each vertex uses 12 bytes for position and 8 for normal and UV coordinates, and 8 for a second uv set with uvs1. Skinned models add 8 bytes for joints and weights. Extras add the size of their struct per vertex.

@unstable

@injects ― definition the vertices vertexAt, positionAt and uv1At read, the joints and weights influencesAt reads, and the boxes boundsOf reads

@injects ― member the extras pool.extra reads

@binds ― 1 storage: positionAt, the positions

@binds ― 2 storage: vertexAt, the positions and the normals and uvs

@binds ― 1 storage: uv1At, the second uvs, in a pool made with uvs1

@binds ― 1 storage: influencesAt, the joints and weights

@binds ― 1 storage: boundsOf, every mesh's box

@binds ― 1 storage: pool.extra, every vertex's extras

@binds ― 1 uniform: pool.texturesOf(index) for materials, beside its textures and sampler, in the fragment stage

@submits ― setup a shape added without an encoder bakes in a compute pass of its own, submitted at once, and a model's images generate their mips as they decode

@owns ― 5 to 7 buffers, a uniform per way of reading textures, a uniform per shape added, a pipeline per pair of shape functions, textures, samplers, bind groups, what images makes: positions, normals and uvs, indices and boxes, second uvs with uvs1, joints and weights once a skinned model comes, and the extras when extra names any; a bake per vertexAt and indexAt it bakes, and per shape added the uniform of its ranges and their group; each image decoded once per format it is read in, and a group per set of a mesh's textures

@returns ― a pool you add meshes and models to and destroy

create
(
const root: TgpuRoot
root
, {
Options<E extends Extras = {}>.capacity: number

Limits the number of meshes to at most 256.

capacity
: 16 });
// Bake shapes into the same encoder
const
const encoder: TgpuCommandEncoder
encoder
=
const root: TgpuRoot
root
.
TgpuRoot.createCommandEncoder(descriptor?: GPUCommandEncoderDescriptor): TgpuCommandEncoder

Creates a

TgpuCommandEncoder

for batching multiple render/compute passes (and draws within them) into a single submission.

@example

const encoder = root.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [{ view: msaaTexture, resolveTarget: context }],
});
scenePipeline.with(pass).draw(vertexCount);
skyPipeline.with(pass).draw(3);
pass.end();
encoder.submit();

createCommandEncoder
();
const
const box: meshPool.Mesh
box
=
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.add(shape: meshPool.Shape, target?: Frame | TgpuCommandEncoder): meshPool.Mesh (+1 overload)

Bakes a shape into the next free ranges in a compute pass. Given a frame or an encoder, it records there; otherwise, it submits at once. The bake's pipeline inlines the shape's vertexAt and indexAt, and compiles, blocking, the first time the pool bakes those functions, unless initAsync compiled it for the shapes option. Throws when the pool is full.

add
(
import meshes
meshes
.
function roundedBox({ segments, ...options }?: meshes.patches.RoundedBoxOptions & {
segments?: number;
}): meshes.IndexedGeometry<WgslStruct<{
position: Vec3f;
normal: Vec3f;
uv: Vec2f;
}>>
roundedBox
(),
const encoder: TgpuCommandEncoder
encoder
);
const
const ball: meshPool.Mesh
ball
=
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.add(shape: meshPool.Shape, target?: Frame | TgpuCommandEncoder): meshPool.Mesh (+1 overload)

Bakes a shape into the next free ranges in a compute pass. Given a frame or an encoder, it records there; otherwise, it submits at once. The bake's pipeline inlines the shape's vertexAt and indexAt, and compiles, blocking, the first time the pool bakes those functions, unless initAsync compiled it for the shapes option. Throws when the pool is full.

add
(
import meshes
meshes
.
function sphere({ radius, segments, rings, }?: meshes.SphereOptions): meshes.IndexedGeometry
sphere
(),
const encoder: TgpuCommandEncoder
encoder
);
const encoder: TgpuCommandEncoder
encoder
.
TgpuCommandEncoder.submit(): void

Finishes the recording and submits the resulting command buffer to the device queue

submit
();
const
const response: Response
response
= await
function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
fetch
('/models/tavern.glb');
const
const tavern: meshPool.Model
tavern
=
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.add(model: meshPool.ModelData<{}>): meshPool.Model (+1 overload)

Uploads each mesh into the next free ranges and decodes images in the background. Each image decodes once per pool and format, and pixels and bitmaps upload during the call. The first skinned mesh allocates a joint-and-weight buffer for the full vertex capacity. Throws if the pool is full, the model has no meshes, its arrays disagree or encoded images other than HDR have no decoder.

add
(
import gltf
gltf
.
function read<never>(source: ArrayBuffer | ArrayBufferView, options?: gltf.ReadOptions<never, false> | undefined): gltf.ModelData<never> (+1 overload)

Reads a binary glTF 2.0 file into meshes, selected parts, a skin and animations. It applies default-scene node transforms and groups meshes by material. Morph targets are omitted.

Skinned meshes use their bind pose with four joints and weights per vertex. An unskinned mesh attached to a joint, such as a helmet, binds to that joint. An unskinned mesh without a joint ancestor must be read as a part or this throws. A part holding a skinned mesh binds to the skin as meshes do; other parts have no skin bindings.

It checks every index, count and range before reading. Invalid glTF, unsupported file versions and unsupported required features throw with details. Use load for a model whose buffers or images are separate files. For extensions that need conversion, errors name the gltf-transform command.

@param ― source the file's bytes, from anywhere

@param ― options.parts names of nodes to keep apart from the rest, each posed about its own origin or, holding a skinned mesh, by the skin

@param ― options.rotation a turn of the whole model, for one that doesn't face +z

@returns ― plain arrays and images, for meshPool.add

read
(await
const response: Response
response
.
Body.arrayBuffer(): Promise<ArrayBuffer>
arrayBuffer
()));
await
const tavern: meshPool.Model
tavern
.
Model.ready: Promise<void>

Resolves when all textures have decoded and uploaded, at once for a model whose materials name none. Until then, meshes draw without textures. Rejects if image decoding fails or the pool is destroyed before upload. A destroyed pool uploads nothing.

ready
; // wait for image decoding and uploads

add returns a Mesh or a Model with one mesh per material. A mesh has its pool index and ranges firstIndex, indexCount, baseVertex and vertexCount. Meshes cannot be removed.

  • Baking pool.add(shape) bakes triangle-list shapes from @typegpu/kit/geometry in a compute pass. Supply a or an encoder to record into it, or omit it to submit immediately.
  • Bake pipelines A bake’s pipeline inlines the shape’s vertexAt and indexAt. The pool compiles one, blocking, the first time it bakes those functions. It reuses that pipeline when you add the same shape again or a copy that shares them. Add new shapes while loading, or compile their bakes ahead.
  • Indices and bounds Unindexed shapes get one index per vertex. Baking also computes their bounding boxes.
  • Defaults Shapes default to white, roughness 1, metallic 0, single-sided, unmasked and untextured.

Name the shapes you will add in shapes, and initAsync compiles their bakes without blocking. Include the pool in pipelines.compile with the scene’s other pipelines, and those shapes bake later without a compile:

import {
import meshPool
meshPool
,
import pipelines
pipelines
} from '@typegpu/kit';
import {
import meshes
meshes
} from '@typegpu/kit/geometry';
const
const rock: meshes.IndexedGeometry<WgslStruct<{
position: Vec3f;
normal: Vec3f;
uv: Vec2f;
}>>
rock
=
import meshes
meshes
.
function roundedBox({ segments, ...options }?: meshes.patches.RoundedBoxOptions & {
segments?: number;
}): meshes.IndexedGeometry<WgslStruct<{
position: Vec3f;
normal: Vec3f;
uv: Vec2f;
}>>
roundedBox
();
const
const ring: meshes.IndexedGeometry<WgslStruct<{
position: Vec3f;
normal: Vec3f;
uv: Vec2f;
}>>
ring
=
import meshes
meshes
.
function torus({ radius, tube, ringSegments, tubeSegments, }?: meshes.TorusOptions): meshes.IndexedGeometry
torus
();
const
const pool: meshPool.MeshPool<{}>
pool
=
import meshPool
meshPool
.
function create<{}>(root: TgpuRoot, options: meshPool.Options<{}>): meshPool.MeshPool<{}>

Creates shared vertex storage and an index buffer, with bounds and textures per mesh. One pipeline can draw any mesh. Each vertex uses 12 bytes for position and 8 for normal and UV coordinates, and 8 for a second uv set with uvs1. Skinned models add 8 bytes for joints and weights. Extras add the size of their struct per vertex.

@unstable

@injects ― definition the vertices vertexAt, positionAt and uv1At read, the joints and weights influencesAt reads, and the boxes boundsOf reads

@injects ― member the extras pool.extra reads

@binds ― 1 storage: positionAt, the positions

@binds ― 2 storage: vertexAt, the positions and the normals and uvs

@binds ― 1 storage: uv1At, the second uvs, in a pool made with uvs1

@binds ― 1 storage: influencesAt, the joints and weights

@binds ― 1 storage: boundsOf, every mesh's box

@binds ― 1 storage: pool.extra, every vertex's extras

@binds ― 1 uniform: pool.texturesOf(index) for materials, beside its textures and sampler, in the fragment stage

@submits ― setup a shape added without an encoder bakes in a compute pass of its own, submitted at once, and a model's images generate their mips as they decode

@owns ― 5 to 7 buffers, a uniform per way of reading textures, a uniform per shape added, a pipeline per pair of shape functions, textures, samplers, bind groups, what images makes: positions, normals and uvs, indices and boxes, second uvs with uvs1, joints and weights once a skinned model comes, and the extras when extra names any; a bake per vertexAt and indexAt it bakes, and per shape added the uniform of its ranges and their group; each image decoded once per format it is read in, and a group per set of a mesh's textures

@returns ― a pool you add meshes and models to and destroy

create
(
const root: TgpuRoot
root
, {
Options<E extends Extras = {}>.capacity: number

Limits the number of meshes to at most 256.

capacity
: 64,
Options<E extends Extras = {}>.shapes?: readonly meshPool.Shape[] | undefined

Builds the bake of each shape now, for initAsync to compile without blocking, so adding one of them later compiles nothing. Default none.

shapes
: [
const rock: meshes.IndexedGeometry<WgslStruct<{
position: Vec3f;
normal: Vec3f;
uv: Vec2f;
}>>
rock
,
const ring: meshes.IndexedGeometry<WgslStruct<{
position: Vec3f;
normal: Vec3f;
uv: Vec2f;
}>>
ring
] });
await
import pipelines
pipelines
.
function compile(from: readonly pipelines.Warmable[] | Owner, options?: pipelines.CompileOptions): Promise<void>

Starts compiling every item the list holds at the call, yielding to the event loop past the time budget so the page's other work, such as a loading animation, keeps running. Use before the frame loop starts. Waits for every item to finish, then rejects if any failed.

@param ― from a list of pipelines and modules that compile their own, or an owner that took them

@returns ― a promise that resolves once every item has compiled

compile
([
const pool: meshPool.MeshPool<{}>
pool
]); // while loading
// Later, in a frame
const
const boulder: meshPool.Mesh
boulder
=
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.add(shape: meshPool.Shape, target?: Frame | TgpuCommandEncoder): meshPool.Mesh (+1 overload)

Bakes a shape into the next free ranges in a compute pass. Given a frame or an encoder, it records there; otherwise, it submits at once. The bake's pipeline inlines the shape's vertexAt and indexAt, and compiles, blocking, the first time the pool bakes those functions, unless initAsync compiled it for the shapes option. Throws when the pool is full.

add
(
const rock: meshes.IndexedGeometry<WgslStruct<{
position: Vec3f;
normal: Vec3f;
uv: Vec2f;
}>>
rock
,
const frame: Frame
frame
);
  • Adding pool.add(model) copies a gltf.read model into the pool. It validates every mesh before changing the pool. Empty models, insufficient capacity or mismatched normals, UVs, indices, joints or weights throw.
  • Capacity Size the pool for the combined mesh, vertex and index counts. meshPool.roomFor(items) totals them for models such as impostors.CARD, individual meshes, shapes and explicit counts. Spread the result into the pool options. It includes uvs1: true if a mesh carries uvs1.
  • Factors Mesh material stores file factors, with colour alpha in opacity. Textures multiply these factors. Instance fields replace them.
  • Masking An alpha: 'mask' mesh cuts out pixels below alphaCutoff in colour and shadow passes. Alpha is texture alpha times opacity.
  • Other fields doubleSided draws back faces lit from their side. normalScale controls normal-map strength and occlusionStrength how far the occlusion texture darkens.
  • Textured meshes A mesh whose material names a texture or masks alpha is textured; read textures only for those.
  • Vertex colours Preserve glTF vertex colours from COLOR_0 by declaring an extra named color. A pool without it drops those colours and warns once, unless every colour is white.
  • Skinned meshes Skinned meshes retain joints and weights for poses. The pool creates their buffer when the first skinned model is added.

Declare custom vertex fields with extra, using the same types as tables. Models supply arrays in extra, and shaders read them through pool.extra:

import {
import gltf
gltf
} from '@typegpu/kit';
import {
import instances
instances
,
import meshPool
meshPool
,
import shading
shading
} from '@typegpu/kit';
const
const pool: meshPool.MeshPool<{
color: d.Vec4f;
}>
pool
=
import meshPool
meshPool
.
function create<{
color: d.Vec4f;
}>(root: TgpuRoot, options: meshPool.Options<{
color: d.Vec4f;
}>): meshPool.MeshPool<{
color: d.Vec4f;
}>

Creates shared vertex storage and an index buffer, with bounds and textures per mesh. One pipeline can draw any mesh. Each vertex uses 12 bytes for position and 8 for normal and UV coordinates, and 8 for a second uv set with uvs1. Skinned models add 8 bytes for joints and weights. Extras add the size of their struct per vertex.

@unstable

@injects ― definition the vertices vertexAt, positionAt and uv1At read, the joints and weights influencesAt reads, and the boxes boundsOf reads

@injects ― member the extras pool.extra reads

@binds ― 1 storage: positionAt, the positions

@binds ― 2 storage: vertexAt, the positions and the normals and uvs

@binds ― 1 storage: uv1At, the second uvs, in a pool made with uvs1

@binds ― 1 storage: influencesAt, the joints and weights

@binds ― 1 storage: boundsOf, every mesh's box

@binds ― 1 storage: pool.extra, every vertex's extras

@binds ― 1 uniform: pool.texturesOf(index) for materials, beside its textures and sampler, in the fragment stage

@submits ― setup a shape added without an encoder bakes in a compute pass of its own, submitted at once, and a model's images generate their mips as they decode

@owns ― 5 to 7 buffers, a uniform per way of reading textures, a uniform per shape added, a pipeline per pair of shape functions, textures, samplers, bind groups, what images makes: positions, normals and uvs, indices and boxes, second uvs with uvs1, joints and weights once a skinned model comes, and the extras when extra names any; a bake per vertexAt and indexAt it bakes, and per shape added the uniform of its ranges and their group; each image decoded once per format it is read in, and a group per set of a mesh's textures

@returns ― a pool you add meshes and models to and destroy

create
(
const root: TgpuRoot
root
, {
Options<E extends Extras = {}>.capacity: number

Limits the number of meshes to at most 256.

capacity
: 16,
Options<{ color: Vec4f; }>.extra?: {
color: d.Vec4f;
} | undefined

Declares custom vertex attributes, for example { tint: d.vec4f }. Model meshes supply their data in extra; shaders read it through pool.extra.tint(i). These attributes use a separate buffer with one struct per vertex. Shapes read as zero. Default none.

extra
: {
color: d.Vec4f
color
:
import d
d
.
const vec4f: d.Vec4f
vec4f
} });
const
const painted: meshPool.Model
painted
=
const pool: meshPool.MeshPool<{
color: d.Vec4f;
}>
pool
.
MeshPool<{ color: Vec4f; }>.add(model: meshPool.ModelData<{
color: d.Vec4f;
}>): meshPool.Model (+1 overload)

Uploads each mesh into the next free ranges and decodes images in the background. Each image decodes once per pool and format, and pixels and bitmaps upload during the call. The first skinned mesh allocates a joint-and-weight buffer for the full vertex capacity. Throws if the pool is full, the model has no meshes, its arrays disagree or encoded images other than HDR have no decoder.

add
(
import gltf
gltf
.
function read<never>(source: ArrayBuffer | ArrayBufferView, options?: gltf.ReadOptions<never, false> | undefined): gltf.ModelData<never> (+1 overload)

Reads a binary glTF 2.0 file into meshes, selected parts, a skin and animations. It applies default-scene node transforms and groups meshes by material. Morph targets are omitted.

Skinned meshes use their bind pose with four joints and weights per vertex. An unskinned mesh attached to a joint, such as a helmet, binds to that joint. An unskinned mesh without a joint ancestor must be read as a part or this throws. A part holding a skinned mesh binds to the skin as meshes do; other parts have no skin bindings.

It checks every index, count and range before reading. Invalid glTF, unsupported file versions and unsupported required features throw with details. Use load for a model whose buffers or images are separate files. For extensions that need conversion, errors name the gltf-transform command.

@param ― source the file's bytes, from anywhere

@param ― options.parts names of nodes to keep apart from the rest, each posed about its own origin or, holding a skinned mesh, by the skin

@param ― options.rotation a turn of the whole model, for one that doesn't face +z

@returns ― plain arrays and images, for meshPool.add

read
(
const bytes: ArrayBuffer
bytes
)); // its COLOR_0, in extra.color
const
const Painted: instances.Kind<"Painted", {}, {}, "host">
Painted
=
import instances
instances
.
function define<"Painted", {}, {}, "host">(name: "Painted", options?: instances.KindOptions<{}, {}, "host"> | undefined): instances.Kind<"Painted", {}, {}, "host"> (+1 overload)

Defines an instance kind with custom fields, transform ownership and callbacks for vertex motion or materials. Each kind uses colour and shadow pipelines per renderer. name brands set ids, as in Id<typeof Fish>, and labels the table and WGSL. Throws if both material and surface are supplied, or a custom field duplicates a built-in or reserved name.

@param ― name a label for ids and WGSL

@returns ― a kind to give instances.create as kind

define
('Painted', {
KindOptions<{}, {}, "host">.carry?: ((vertexIndex: number, instance: {
rotation: d.v4f;
position: d.v3f;
scale: d.v3f;
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
mesh: number;
opacity: number;
}) => d.v4f) | undefined

Returns four values to interpolate between vertices and hand to the fragment hooks as pixel.carried. For example, read an extra attribute with pool.extra.tint(vertexIndex). vertexIndex indexes the pool, as in meshPool.vertexAt. Default none, which omits four floats per vertex and sets carried to zero.

@gpu

carry
: (
vertexIndex: number
vertexIndex
) => {
'use gpu';
return
const pool: meshPool.MeshPool<{
color: d.Vec4f;
}>
pool
.
MeshPool<{ color: Vec4f; }>.extra: meshPool.ExtraReaders<{
color: d.Vec4f;
}>

Reads the attributes named in extra for pool vertex i. Create calling shaders from root.pipe(pool.inject()).

extra
.
color: (i: number) => d.v4f
color
(
vertexIndex: number
vertexIndex
);
},
KindOptions<{}, {}, "host">.material?: ((pixel: instances.Pixel<{
rotation: d.v4f;
position: d.v3f;
scale: d.v3f;
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
mesh: number;
opacity: number;
}>, base: shading.Material) => shading.Material) | undefined

Returns the material at a pixel. base combines the instance material fields with the mesh textures, as materials.textured does. Default base.

@gpu

material
: (
pixel: instances.Pixel<{
rotation: d.v4f;
position: d.v3f;
scale: d.v3f;
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
mesh: number;
opacity: number;
}>
pixel
,
base: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
base
) => {
'use gpu';
const
const tinted: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
tinted
=
import shading
shading
.
const Material: d.WgslStruct
(props?: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
} | undefined) => {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}

This schema describes a surface with the glTF metallic-roughness model. New fields are only appended, each off at zero. Make one with a materials preset or copy one with Material(m), then assign the fields you set: a struct literal stops compiling when a field is added.

Material
(
base: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
base
);
const tinted: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
tinted
.
color: d.v3f

Sets the diffuse colour of a dielectric or the reflection colour of a metal, in linear colour space.

color
=
base: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
base
.
color: d.v3f

Sets the diffuse colour of a dielectric or the reflection colour of a metal, in linear colour space.

color
*
pixel: instances.Pixel<{
rotation: d.v4f;
position: d.v3f;
scale: d.v3f;
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
mesh: number;
opacity: number;
}>
pixel
.
Pixel<I>.carried: d.v4f

Holds the values interpolated from carry, or zero without it.

carried
.
rgb: d.v3f
rgb
;
return
const tinted: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
tinted
;
},
});
const
const things: instances.Instances<instances.Kind<"Painted", {}, {}, "host">>
things
=
import instances
instances
.
function create<instances.Kind<"Painted", {}, {}, "host">>(root: TgpuRoot, pool: meshPool.MeshPool, options: instances.Options<instances.Kind<"Painted", {}, {}, "host">> & {
readonly kind: instances.Kind<"Painted", {}, {}, "host">;
}): instances.Instances<instances.Kind<"Painted", {}, {}, "host">> (+3 overloads)

Creates a set of mesh instances with transforms, materials and optional custom fields. Each instance uses a row, and renderers draw one list of live rows per mesh.

@param ― pool the mesh pool whose meshes it draws

@param ― options.kind a kind from instances.define

@returns ― a set of instances you flush every frame and destroy

create
(
const root: TgpuRoot
root
,
const pool: meshPool.MeshPool<{
color: d.Vec4f;
}>
pool
, {
kind: Getters<HostOf<{}, "host">> & Getters<{}> & {
readonly host: TgpuAccessor<Rows<HostOf<{}, "host">>>;
readonly device: TgpuAccessor<Rows<{}>>;
readonly row: TgpuGenericFn<(i: number) => {
rotation: d.v4f;
position: d.v3f;
scale: d.v3f;
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
mesh: number;
opacity: number;
}>;
readonly alive: TgpuGenericFn<(i: number) => boolean>;
readonly span: TgpuGenericFn<() => number>;
readonly slotOf: TgpuGenericFn<(id: number) => number>;
readonly '~parts': Parts<...>;
} & {
...;
}

Selects a kind from instances.define. Default a plain kind with a transform and material.

kind
:
const Painted: instances.Kind<"Painted", {}, {}, "host">
Painted
,
Options<K extends AnyKind = Plain>.capacity: number

Limits the number of rows. A mesh instance uses one row; a model instance uses one row per mesh.

capacity
: 64 });
const things: instances.Instances<instances.Kind<"Painted", {}, {}, "host">>
things
.
Instances<Kind<"Painted", {}, {}, "host">>.add(mesh: meshPool.Mesh | Pick<meshPool.Model, "meshes">, values?: {
readonly position?: FieldInput<d.Vec3f>;
readonly rotation?: FieldInput<d.Vec4f>;
readonly scale?: number | FieldInput<d.Vec3f>;
readonly color?: FieldInput<d.Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<d.Vec3f>;
readonly opacity?: number;
} | ((mesh: meshPool.Mesh, index: number) => {
readonly position?: FieldInput<d.Vec3f>;
readonly rotation?: FieldInput<d.Vec4f>;
readonly scale?: number | FieldInput<d.Vec3f>;
readonly color?: FieldInput<d.Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<d.Vec3f>;
readonly opacity?: number;
}) | undefined): instances.Id<...>

Adds an instance of a mesh, model or group of meshes from the pool. Each mesh uses a row, and all rows move and change together under one id. values may be a function of each mesh, to give a model's meshes values of their own. Throws if a mesh belongs to another pool, the group is empty, a posed kind receives a mesh without joints or the set is full. When values or a write throws, it adds no row and rethrows.

add
(
const painted: meshPool.Model
painted
);
  • Fields accept 32-bit scalars or vectors, including d.f32, d.u32, d.i32 and d.vec2f through d.vec4i. Supply components in vertex order as Float32Array, Uint32Array or Int32Array matching the field type.
  • Shape extras and omitted fields default to zero. Undeclared extras are dropped with one warning per field, naming the declaration needed to keep it.
  • In a shader created from root.pipe(pool.inject()), pool.extra.color(i) reads the vertex indexed as vertexAt does. Use carry to pass it to fragments.
  • Kinds Meshes have colour, metallic-roughness, normal, emission and occlusion textures, all with mipmaps. Colour and emission use ; the others use linear values. Normal maps need no tangents. A material without a normal map skips normal mapping, since its reading’s normalScale is 0.
  • Transforms A texture’s transform scales, rotates and then offsets the coordinates it reads, as glTF’s KHR_texture_transform does. A mesh can then tile one texture and read another from an . Each texture of a mesh keeps its own. The cloister tiles its paving, turns its border and cuts its panels from one atlas this way.
  • Second uv set A texture with uvSet: 1 reads the mesh’s second uv set, uvs1, as a lightmap or occlusion map baked on its own unwrap does. The pool keeps uvs1 only when created with uvs1: true, which roomFor sets for meshes that carry it. add throws for a mesh whose texture reads a uv set the pool can’t keep. The cloister bakes its occlusion on a second set, and the classroom its daylight and its lamps’ bounce.
  • Sampler A material samples all its textures with one . It takes the colour texture’s, or the first texture’s when there is no colour texture. The pool ignores the samplers a model gives its other textures, so give a lightmap’s charts margins when the colour texture repeats.
  • Shared images The pool decodes each image once per format and shares identical bytes across meshes and models. The pool uploads pixels and bitmaps during add. It reuses the upload when the same image object is added again in the same format. Give changed pixels a new object. If one image is used for both colour and normals, it decodes twice.
  • Loading Meshes draw without textures until ready settles. A model whose materials name no texture is ready at once. Decode failures or destroying the pool before completion reject ready. Failed decodes are not cached, so later models can retry them.

Images decode with createImageBitmap, which some lack. Radiance files, with the MIME type images.HDR, decode in the kit on any thread:

  • On React Native, react-native-webgpu installs it on the JS thread only. It ignores colorSpaceConversion: 'none', so an image with a colour profile may decode differently than on the web.
  • , including hosted scenes, lack createImageBitmap. Decode on the JS thread with images.decodeBitmap, then pass the model with those bitmaps in the scene’s options. A bitmap is a native object, so it reaches the worker as the device does.
  • Alternatively, supply decode returning { width, height, pixels }, with four unpremultiplied bytes per pixel and rows from the top. A Skia decoder can provide this. Encoded images without a decoder cause add to throw.
// On the JS thread, before the scene starts
const model = gltf.read(bytes);
const decoded = { ...model, images: await Promise.all(model.images.map(images.decodeBitmap)) };
  • Node and dawn.node also need a decoder. Pass it through scene options as in Testing.

Build shaders from root.pipe(pool.inject()) to call meshPool.vertexAt(i). It decodes a pool vertex into the @typegpu/kit/geometry vertex type. Bind pool.indices and draw a mesh range:

const
const ring: meshPool.Mesh
ring
=
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.add(shape: meshPool.Shape, target?: Frame | TgpuCommandEncoder): meshPool.Mesh (+1 overload)

Bakes a shape into the next free ranges in a compute pass. Given a frame or an encoder, it records there; otherwise, it submits at once. The bake's pipeline inlines the shape's vertexAt and indexAt, and compiles, blocking, the first time the pool bakes those functions, unless initAsync compiled it for the shapes option. Throws when the pool is full.

add
(
import meshes
meshes
.
function torus({ radius, tube, ringSegments, tubeSegments, }?: meshes.TorusOptions): meshes.IndexedGeometry
torus
());
const
const vertex: TgpuVertexFn<{}, {
normal: d.Vec3f;
}>
vertex
=
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
.
vertexFn: <{
i: d.BuiltinVertexIndex;
}, {
position: d.BuiltinPosition;
normal: d.Vec3f;
}>(options: {
in: {
i: d.BuiltinVertexIndex;
};
out: {
position: d.BuiltinPosition;
normal: d.Vec3f;
};
}) => TgpuVertexFnShell<{
i: d.BuiltinVertexIndex;
}, {
position: d.BuiltinPosition;
normal: d.Vec3f;
}> (+1 overload)
vertexFn
({
in: {
i: d.BuiltinVertexIndex;
}
in
: {
i: d.BuiltinVertexIndex
i
:
import d
d
.
const builtin: {
readonly vertexIndex: d.BuiltinVertexIndex;
readonly instanceIndex: d.BuiltinInstanceIndex;
readonly clipDistances: d.BuiltinClipDistances;
readonly position: d.BuiltinPosition;
readonly frontFacing: d.BuiltinFrontFacing;
readonly fragDepth: d.BuiltinFragDepth;
readonly primitiveIndex: d.BuiltinPrimitiveIndex;
readonly sampleIndex: d.BuiltinSampleIndex;
... 11 more ...;
readonly numSubgroups: d.BuiltinNumSubgroups;
}
export builtin
builtin
.
vertexIndex: d.BuiltinVertexIndex
vertexIndex
},
out: {
position: d.BuiltinPosition;
normal: d.Vec3f;
}
out
: {
position: d.BuiltinPosition
position
:
import d
d
.
const builtin: {
readonly vertexIndex: d.BuiltinVertexIndex;
readonly instanceIndex: d.BuiltinInstanceIndex;
readonly clipDistances: d.BuiltinClipDistances;
readonly position: d.BuiltinPosition;
readonly frontFacing: d.BuiltinFrontFacing;
readonly fragDepth: d.BuiltinFragDepth;
readonly primitiveIndex: d.BuiltinPrimitiveIndex;
readonly sampleIndex: d.BuiltinSampleIndex;
... 11 more ...;
readonly numSubgroups: d.BuiltinNumSubgroups;
}
export builtin
builtin
.
position: d.BuiltinPosition
position
,
normal: d.Vec3f
normal
:
import d
d
.
const vec3f: d.Vec3f
vec3f
},
})(({
i: number
i
}) => {
'use gpu';
const
const corner: {
position: d.v3f;
normal: d.v3f;
uv: d.v2f;
}
corner
=
import meshPool
meshPool
.
const vertexAt: (i: number) => {
position: d.v3f;
normal: d.v3f;
uv: d.v2f;
}

Decodes pool vertex i into an @typegpu/kit/geometry vertex. In a mesh draw, the vertex index already includes baseVertex. Create calling shaders from root.pipe(pool.inject()).

vertexAt
(
i: number
i
); // i already counts from the mesh's baseVertex
return {
position: d.v4f
position
:
import cameras
cameras
.
const toClip: (point: d.v3f) => d.v4f

Returns a world point in clip space, as a vertex shader's position. It reads cameras.current; code that projects with a view of its own multiplies by that view's viewProjection.

toClip
(
const corner: {
position: d.v3f;
normal: d.v3f;
uv: d.v2f;
}
corner
.
position: d.v3f
position
),
normal: d.v3f
normal
:
const corner: {
position: d.v3f;
normal: d.v3f;
uv: d.v2f;
}
corner
.
normal: d.v3f
normal
,
};
});
const
const pipeline: TgpuRenderPipeline<d.Vec4f>
pipeline
=
const root: TgpuRoot
root
.
WithBinding.pipe(transform: (cfg: Configurable) => Configurable): WithBinding
pipe
(
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.inject(): Inject

Fills mesh resources for pipelines created from the configuration you pipe it into.

inject
())
.
WithBinding.pipe(transform: (cfg: Configurable) => Configurable): WithBinding
pipe
(
const view: cameras.OrbitCamera
view
.
CameraBase.inject(): Inject

Fills cameras.current for the pipelines created from the configuration it is piped into.

inject
())
.
WithBinding.createRenderPipeline<{}, {}, {
normal: d.Vec3f;
}, d.Vec4f>(descriptor: TgpuRenderPipeline<in Targets = never>.DescriptorBase & {
attribs?: {} | undefined;
vertex: TgpuVertexFn<{}, {
normal: d.Vec3f;
}> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>);
fragment: TgpuFragmentFn<{
normal: d.Vec3f;
} & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<...>) => d.v4f | (AnyAutoCustoms & Partial<...>));
targets?: TgpuColorTargetState;
}): TgpuRenderPipeline<...> (+2 overloads)
createRenderPipeline
({
vertex: TgpuVertexFn<{}, {
normal: d.Vec3f;
}> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>)
vertex
,
fragment: TgpuFragmentFn<{
normal: d.Vec3f;
} & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<InferGPURecord<{
normal: d.Vec3f;
}>>) => d.v4f | (AnyAutoCustoms & Partial<InferGPURecord<{
readonly $fragDepth: import("node_modules/typegpu/builtin").BuiltinFragDepth;
readonly $sampleMask: import("node_modules/typegpu/builtin").BuiltinSampleMask;
}>>))
fragment
,
targets?: TgpuColorTargetState
targets
: {
format?: GPUTextureFormat | undefined

The

GPUTextureFormat

of this color target. The pipeline will only be compatible with

GPURenderPassEncoder

s which use a

GPUTextureView

of this format in the corresponding color attachment.

@default ― navigator.gpu.getPreferredCanvasFormat()

format
: 'rgba16float' } });
const
const drawing: TgpuRenderPipeline<d.Vec4f> & HasIndexBuffer
drawing
=
const pipeline: TgpuRenderPipeline<d.Vec4f>
pipeline
.
TgpuRenderPipeline<Vec4f>.withIndexBuffer(buffer: TgpuBuffer<d.BaseData> & IndexFlag, offsetElements?: number, sizeElements?: number): TgpuRenderPipeline<d.Vec4f> & HasIndexBuffer (+1 overload)
withIndexBuffer
(
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.indices: TgpuBuffer<d.WgslArray<d.U32>> & IndexFlag & StorageFlag

Holds all mesh indices, relative to each mesh baseVertex.

indices
); // at setup
const pass: TgpuRenderPass
pass
.
TgpuRenderCommands.setPipeline(pipeline: TgpuRenderPipeline): void

Sets the current

TgpuRenderPipeline

for subsequent draw calls

setPipeline
(
const drawing: TgpuRenderPipeline<d.Vec4f> & HasIndexBuffer
drawing
);
const pass: TgpuRenderPass
pass
.
TgpuRenderCommands.drawIndexed(indexCount: number, instanceCount?: number, firstIndex?: number, baseVertex?: number, firstInstance?: number): void
drawIndexed
(
const ring: meshPool.Mesh
ring
.
Mesh.indexCount: number
indexCount
, 1,
const ring: meshPool.Mesh
ring
.
Mesh.firstIndex: number
firstIndex
,
const ring: meshPool.Mesh
ring
.
Mesh.baseVertex: number
baseVertex
);
  • Vertex data Depth passes can read only meshPool.positionAt(i). influencesAt(i) reads joints and weights. boundsOf(mesh.index) returns the mesh box in local space.
  • Textures Bind pool.texturesOf(mesh.index) before drawing a textured mesh. In the fragment shader, use materials.textured and materials.mappedNormal(normal, world, uv, uv1), with uv1 from meshPool.uv1At(i), which reads zero in a pool without uvs1.
  • Masked meshes For masked meshes, discard where materials.masked(uv, uv1, opacity) requests it.
  • Double-sided meshes Use cullMode: 'none' for double-sided meshes.
  • Your own sampling meshPool.textureLayout exposes the bind-group layout for custom sampling. materials.uvOf(meshPool.textureLayout.$.reading.uvs.color, uv, uv1) gives the coordinates the colour texture reads. It reads uv1 only in a pipeline piped with the inject() of a pool made with uvs1.
What
a pool 20 bytes per vertex and 4 per index of capacity. Defaults use about 2.4 MB.
skinned 8 additional bytes per vertex of capacity after the first skinned model. Defaults add 512 KB.
uvs1 8 additional bytes per vertex of capacity, as full floats. Defaults add 512 KB.
extras Struct size per vertex of capacity. A d.vec4f adds 1 MB at default capacity.
an image 4 bytes per pixel plus one third for mipmaps, per format. A 1024 × 1024 image uses 5.6 MB.
Message Thrown by
The mesh pool is full (64 meshes). add, past the pool’s capacity
The mesh pool has room for 120 vertices and 400 indices. … add, for a shape or a model that doesn’t fit
Mesh 2 of the model has … add, for a model whose arrays don’t agree, naming the count that is off
Mesh 2 of the model supplies extra 'tint' as Int32Array. … add, for an extra in another array than its type reads
Mesh 2 of the model reads uv set 1 in its emission texture… add, for a texture reading uvs1 that the mesh lacks or the pool doesn’t keep
This platform lacks `createImageBitmap`. … add, for a model with encoded images on a runtime without it, given no decode
The mesh pool was destroyed before its images were … ready, rejected
The mesh pool has no skinned model. … a pipeline that reads joints, such as a posed kind’s renderer, compiled before the pool held a skinned model
The pipeline is missing a fill for the mesh pool's vertices. … a pipeline that calls vertexAt without root.pipe(pool.inject())
  • The pool’s size is fixed at creation.
  • Indices use u32 because WGSL has no 16-bit storage.
  • UVs use half floats. Their precision is 1/2048 below 1 and 1/16 between 64 and 128, so large tiled UV values can drift.
  • A material’s textures share one sampler.
  • Normal maps use per-pixel screen-space derivatives without tangents. Maps baked with MikkTSpace tangents can differ near UV seams or stretched coordinates.
storage bufferA storage buffer is GPU memory that shaders read by index and kernels can write, which is where the kit keeps rows.Words →
frameA frame is one turn of the loop, and the object your function gets for it, which holds the encoder, the time and the time since the last frame.You own the frame →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
rendererA renderer draws one sort of thing, such as instances or particles, by handing a pass description a drawing.Every renderer is a drawing →
sRGBsRGB is the encoding screens and most image files use for colour, which a shader turns into linear light before it does maths on it.Words →
atlasAn atlas is one texture that holds many small pictures side by side, such as every glyph of a font or every view of a model.Words →
samplerA sampler tells the GPU how to read a texture between its texels and past its edges, such as smoothly or in blocks.Words →
runtimeA runtime is one JavaScript thread with its own memory, such as the page, a worker or a React Native worklet thread.Words →
HDRHDR, high dynamic range, is colour stored with more range than a screen shows, so a light can be brighter than white.A module borrows →
workletA worklet is a function that react-native-worklets can run on a thread other than the main JavaScript thread.Words →

Reference

Callsborrows, never destroystakesreturns

meshPool.create(root, { capacity, … }) → MeshPool

root
the root
MeshPool
a pool you add meshes and models to and destroy
takes

Options

8 fields
capacity

number

Limits the number of meshes to at most 256.

extra?

E

Declares custom vertex attributes, for example { tint: d.vec4f }.Default none.

vertices?

number

Limits the total vertex count across all meshes.Default 65 536.

indices?

number

Limits the total index count across all meshes.Default 262 144.

uvs1?

boolean

Keeps each mesh's second uv set, uvs1, for textures with uvSet: 1, in 8 more bytes per vertex.Default false.

decode?

Decode

Decodes encoded images when createImageBitmap is unavailable.Default createImageBitmap.

anisotropy?

number

Sets the texture sample count at grazing angles, up to 16.Default 1.

shapes?

Shape[]

Builds the bake of each shape now, for initAsync to compile without blocking, so adding one of them later compiles nothing.Default none.

returns

MeshPool

10 members
meshes

Mesh[]

Lists added meshes by pool index.

capacity

number

Gives the maximum mesh count.

indices

TgpuBuffer<d.WgslArray<d.U32>> & IndexFlag & StorageFlag

Holds all mesh indices, relative to each mesh baseVertex.

add(shape, target?)

Bakes a shape into the next free ranges in a compute pass.

add(model)

Bakes a shape into the next free ranges in a compute pass.

extra

ExtraReaders<E>

Reads the attributes named in extra for pool vertex i.

inject()

Fills mesh resources for pipelines created from the configuration you pipe it into.

initAsync()

Compiles the bakes of the shapes option.

texturesOf(index)

Returns the texture bind group for mesh index.

destroy()

Destroys the buffers and textures.

meshPool.roomFor(items) → Sized

items
what the pool will hold
Sized
the capacity, vertices and indices they take, and uvs1: true when a mesh needs it
returns

Sized

4 members
capacity

number

Gives the number of meshes to hold.

vertices

number

Gives the number of vertices to hold.

indices

number

Gives the number of indices to hold.

uvs1?

true

Keeps a second uv set in the pool, present when a mesh carries one.

In a frame

submits

while setting up

A shape added without an encoder bakes in a compute pass of its own, submitted at once, and a model's images generate their mips as they decode.

Holds

owns

5 to 7 buffers ·a uniform per way of reading textures ·a uniform per shape added ·a pipeline per pair of shape functions ·textures ·samplers ·bind groups ·what images makes

Positions, normals and uvs, indices and boxes, second uvs with uvs1, joints and weights once a skinned model comes, and the extras when extra names any; a bake per vertexAt and indexAt it bakes, and per shape added the uniform of its ranges and their group; each image decoded once per format it is read in, and a group per set of a mesh's textures.

lifecycle

initAsync()destroy()[Symbol.dispose]

binds
  • 1 storage

    positionAt, the positions.

  • 2 storage

    vertexAt, the positions and the normals and uvs.

  • 1 storage

    uv1At, the second uvs, in a pool made with uvs1.

  • 1 storage

    influencesAt, the joints and weights.

  • 1 storage

    boundsOf, every mesh's box.

  • 1 storage

    pool.extra, every vertex's extras.

  • 1 uniform

    pool.texturesOf(index) for materials, beside its textures and sampler, in the fragment stage.

Connects to

injects
  • definition

    The vertices vertexAt, positionAt and uv1At read, the joints and weights influencesAt reads, and the boxes boundsOf reads.

  • member

    The extras pool.extra reads.

Exports

GPU functions
positionAt vertexAt uv1At influencesAt boundsOf
schemas
Reading TextureUvs Box Influences
helpers
textureLayout
types
SamplerData TextureData TexturesData TextureTransformData Shape Factors Mesh Model MaterialData ExtraType Extras ExtraData ExtraReaders MeshData ModelData Room
schema

Reading

4 fields
normalScale

d.f32

Scales the x and y components of the sampled normal.

occlusionStrength

d.f32

Sets how much the occlusion texture darkens, from 0 for none to 1 for all of it.

alphaCutoff

d.f32

Sets the alpha threshold for discarding a pixel.

uvs

d.struct({ color: TextureUvs, metallicRoughness: TextureUvs, normal: TextureUvs, emission: TextureUvs, occlusion: TextureUvs })

Holds the uvs each texture reads.

schema

TextureUvs

3 fields
u

d.vec3f

v

d.vec3f

uvSet

d.u32

schema

Box

2 fields
center

d.vec3f

half

d.vec3f

schema

Influences

2 fields
joints

d.vec4u

weights

d.vec4f

used byAfterimageBlockfallClassroomCloisterDomino runFireworksFish tankForestHex isleKineticNight marketQuiver treesRobot armSkeletonsSolar systemSpiderStampedeSurvey model