Skip to content

ModuleCore / Reading backConcept: Data on the GPU

Picker

Find a candidate under the pointer on the GPU, then use it in the same frame or read it back to the CPU.

import
import { picker } from '@typegpu/kit'
call
picker.create(root, camera, { capacity, size, position, … }) → Picker
facts
recordsframecomputelifecycleinitAsync()destroy()injectsmemberneedscameras
On this page

Wisps move on the GPU, so the CPU needs their positions to find one under a finger. Reading all positions copies the whole set and adds a or two of delay. A picking instead projects every candidate with your camera and selects the nearest within reach. It returns one index. Later kernels can use that index in the same frame, before it reaches the CPU.

star-map20 000 stars. Hover one and the GPU picks it in the same frame.

Hover a star to light it in the same frame through found(). result reaches the CPU frames later. The dashed ring shows reach around the pointer. Set nearest to eye to choose the frontmost star within reach. The picker’s rank reads this choice from a uniform. Click a star to select it.

const
const hits: picker.Picker
hits
=
import picker
picker
.
function create(root: TgpuRoot, camera: cameras.CameraBase, options: picker.Options): picker.Picker

Finds a candidate under a screen point on the GPU. Projects every candidate with the camera and keeps the one within reach with the best rank. Throws unless capacity is an integer from 1 to 2^24 whose threads, 64 to a workgroup, fit the device's maxComputeWorkgroupsPerDimension.

@injects ― member found and ray, for shaders that act on the pick in the same frame; ray also reads cameras.current

@binds ― 1 storage: found, the pick's key

@binds ― 1 uniform: ray, the pick's point

@owns ― 3 buffers, a pipeline, a readback: the pick's key, the pointer and the settings; the readback brings the key to the CPU

@records ― pick once in a frame that picks, in a compute pass after whatever moves the candidates; result.capture(frame) after that pass, which copies what a pick found.

@param ― camera the camera the candidates are drawn with

@param ― options.position where each candidate is; it, radius, alive and rank carry the fills of what they read, such as Star.position.pipe(stars.inject())

@returns ― a picker you destroy

create
(
const root: TgpuRoot
root
,
const view: cameras.OrbitCamera
view
, {
Options.capacity: number

Sets the number of candidate slots, including dead slots. Indices range from 0 to `capacity

  • 1`. Must be an integer from 1 to 2^24.

capacity
: 512,
Options.size: SizeSource

Supplies the view size at each pick, such as the canvas surface. pixelRatio scales reach from screen points to pixels. Without it, one point equals one pixel.

size
:
const surface: web.Surface
surface
,
Options.position: (i: number) => d.v3f

Returns the candidate center in world space.

@gpu

position
: (
i: number
i
) => {
'use gpu';
return
import d
d
.
const vec3f: d.Vec3f
(v: AnyNumericVec3Instance) => d.v3f (+5 overloads)
vec3f
(
const wisps: TgpuReadonly<d.WgslArray<d.Vec3f>>
wisps
.
TgpuReadonly<WgslArray<Vec3f>>.$: d.v3f[]
$
[
i: number
i
]);
},
});
let
let tap: [number, number] | undefined
tap
: [number, number] | undefined;
const canvas: HTMLCanvasElement
canvas
.
HTMLCanvasElement.addEventListener<"pointerup">(type: "pointerup", listener: (this: HTMLCanvasElement, ev: PointerEvent) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

MDN Reference

addEventListener
('pointerup', (
event: PointerEvent
event
) => {
let tap: [number, number] | undefined
tap
= [
event: PointerEvent
event
.
MouseEvent.offsetX: number

The offsetX read-only property of the MouseEvent interface provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.

MDN Reference

offsetX
/
const canvas: HTMLCanvasElement
canvas
.
Element.clientWidth: number

The clientWidth read-only property of the Element interface is zero for inline elements and elements with no CSS; otherwise, it's the inner width of an element in pixels. It includes padding but excludes borders, margins, and vertical scrollbars (if present).

MDN Reference

clientWidth
,
event: PointerEvent
event
.
MouseEvent.offsetY: number

The offsetY read-only property of the MouseEvent interface provides the offset in the Y coordinate of the mouse pointer between that event and the padding edge of the target node.

MDN Reference

offsetY
/
const canvas: HTMLCanvasElement
canvas
.
Element.clientHeight: number

The clientHeight read-only property of the Element interface is zero for elements with no CSS or inline layout boxes; otherwise, it's the inner height of an element in pixels. It includes padding but excludes borders, margins, and horizontal scrollbars (if present).

MDN Reference

clientHeight
];
});
import frames
frames
.
function create(root: TgpuRoot, record: Recorder): frames.Frames

Records a frame into one encoder and submits once, with a clock. Borrows the root. The synchronous recorder borrows each frame's encoder.

@submits ― always once a frame after your recorder returns, and again at each frame.submit()

@param ― record your frame, recorded into each frame's encoder

@returns ― a loop you run with each frame's time and destroy

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const
const compute: TgpuComputePass
compute
=
frame: frames.Frame
frame
.
Frame.encoder: TgpuCommandEncoder

Records commands for submission after the recorder returns. submit() replaces this encoder. Read it at each call instead of keeping it, and let the frame submit it.

encoder
.
TgpuCommandEncoder.beginComputePass(descriptor?: TgpuComputePassDescriptor): TgpuComputePass

Begins recording a compute pass

beginComputePass
();
// ... the steps that move the wisps
if (
let tap: [number, number] | undefined
tap
)
const hits: picker.Picker
hits
.
Picker.pick(pass: TgpuComputePass, x: number, y: number): void

Picks at x, y from 0 to 1 across the view, from the top-left corner, as view.rayAt and pointing take them. Uses the camera given to create. Records one pick per frame: a second call into the same pass replaces the point and records no second dispatch.

pick
(
const compute: TgpuComputePass
compute
, ...
let tap: [number, number]
tap
);
const compute: TgpuComputePass
compute
.
TgpuComputePass.end(): void

Completes the recording of this compute pass

end
();
const hits: picker.Picker
hits
.
Picker.result: Readback<number | null>

Reads the picked candidate index to the CPU, or null if nothing was found. Capture after the picker pass, then call take() or await next(). Without hz, each pick requests a copy for the next capture.

result
.
Readback<number | null>.capture(frame: frames.Frame): void

Records a copy when a next() is waiting, a request is pending or the capture rate is due. Maps the copy after submission. Call after the pass that writes the buffer. A second call in the same frame does nothing.

capture
(
frame: frames.Frame
frame
);
let tap: [number, number] | undefined
tap
=
var undefined
undefined
;
const
const found: number | null | undefined
found
=
const hits: picker.Picker
hits
.
Picker.result: Readback<number | null>

Reads the picked candidate index to the CPU, or null if nothing was found. Capture after the picker pass, then call take() or await next(). Without hz, each pick requests a copy for the next capture.

result
.
Readback<number | null>.take(): number | null | undefined

Returns latest once per completed copy, then undefined until the next copy completes. Each value goes to one caller. Callers sharing a readback split the values between them.

take
(); // undefined until a pick comes back
if (
const found: number | null | undefined
found
!==
var undefined
undefined
)
function select(wisp: number | null): void
select
(
const found: number | null
found
);
});
  • The point x and y run from 0 to 1 across the view from its top-left corner, as a ’s pointing and a camera’s rayAt take them.
  • Reach settings.reach is a distance in points. The picker reads size and its pixelRatio at each pick, as text does, so reach stays the same when a window moves between screens. Without a pixelRatio, a point is a pixel.
  • Candidates A candidate is within reach when its centre is within reach points, plus its radius as it looks from the eye. One behind the eye, or one alive turns down, is never picked.
  • One pick pick writes the point and clears the result with queue writes, so a frame picks once. A second pick into the same pass replaces the point and records no second .
  • The result result is a readback of the candidate’s index, or null for nothing. Capture it after the pass that picks. Without hz, each tap comes back once, a frame or two later.

Several candidates can be within reach. rank is a 'use gpu' function that maps a picker.Candidate to a number from 0 to 1. The lowest rank wins. Ties go to the lower index. A candidate holds:

  • index;
  • gap, from the point to its centre on the screen, as a fraction of the screen’s diagonal;
  • depth, 0 at the near plane and 1 at the far, in equal steps of distance;
  • position, its centre in the world;
  • ray, the ray through the point, as cameras.rayOf gives it.

picker.byPointer, the default, ranks by gap, for wisps a finger covers. picker.byEye ranks by depth, the one in front, for a hover among stars that overlap on the screen.

A rank that reads a uniform switches between them without a new picker, as the star map’s nearest does:

const
const byEye: TgpuUniform<d.U32>
byEye
=
const root: TgpuRoot
root
.
TgpuRoot.createUniform<d.U32>(typeSchema: d.U32, initial?: number | ((buffer: TgpuBuffer<NoInfer<d.U32>>) => void) | undefined): TgpuUniform<d.U32> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader. Read-only on the GPU, optimized for small data. For a general-purpose buffer, use

TgpuRoot.createBuffer

.

@param ― typeSchema The type of data that this buffer will hold.

@param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

createUniform
(
import d
d
.
const u32: d.U32
export u32

A schema that represents an unsigned 32-bit integer value. (equivalent to u32 in WGSL)

Can also be called to cast a value to an u32 in accordance with WGSL casting rules.

@example const value = u32(); // 0

@example const value = u32(7); // 7

@example const value = u32(3.14); // 3

@example const value = u32(-1); // 4294967295

@example const value = u32(-3.1); // 0

u32
, 0);
const
const hits: picker.Picker
hits
=
import picker
picker
.
function create(root: TgpuRoot, camera: cameras.CameraBase, options: picker.Options): picker.Picker

Finds a candidate under a screen point on the GPU. Projects every candidate with the camera and keeps the one within reach with the best rank. Throws unless capacity is an integer from 1 to 2^24 whose threads, 64 to a workgroup, fit the device's maxComputeWorkgroupsPerDimension.

@injects ― member found and ray, for shaders that act on the pick in the same frame; ray also reads cameras.current

@binds ― 1 storage: found, the pick's key

@binds ― 1 uniform: ray, the pick's point

@owns ― 3 buffers, a pipeline, a readback: the pick's key, the pointer and the settings; the readback brings the key to the CPU

@records ― pick once in a frame that picks, in a compute pass after whatever moves the candidates; result.capture(frame) after that pass, which copies what a pick found.

@param ― camera the camera the candidates are drawn with

@param ― options.position where each candidate is; it, radius, alive and rank carry the fills of what they read, such as Star.position.pipe(stars.inject())

@returns ― a picker you destroy

create
(
const root: TgpuRoot
root
,
const view: cameras.OrbitCamera
view
, {
Options.capacity: number

Sets the number of candidate slots, including dead slots. Indices range from 0 to `capacity

  • 1`. Must be an integer from 1 to 2^24.

capacity
: 512,
Options.size: SizeSource

Supplies the view size at each pick, such as the canvas surface. pixelRatio scales reach from screen points to pixels. Without it, one point equals one pixel.

size
,
Options.position: (i: number) => d.v3f

Returns the candidate center in world space.

@gpu

position
: (
i: number
i
) => {
'use gpu';
return
import d
d
.
const vec3f: d.Vec3f
(v: AnyNumericVec3Instance) => d.v3f (+5 overloads)
vec3f
(
const stars: TgpuReadonly<d.WgslArray<d.Vec3f>>
stars
.
TgpuReadonly<WgslArray<Vec3f>>.$: d.v3f[]
$
[
i: number
i
]);
},
Options.rank?: ((candidate: picker.Candidate) => number) | undefined

Ranks candidates within reach, from 0 to 1. Keeps the lowest rank, then the lowest index among ties. A negative rank turns the candidate down, so a rank can be the distance at which candidate.ray meets the candidate's shape, negative for a miss. Can read a uniform to switch rankings, such as between byPointer and byEye, without recreating the picker. Default byPointer.

@gpu

rank
: (
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
) => {
'use gpu';
return
import std
std
.
function select(f: number, t: number, cond: boolean): number (+2 overloads)
export select

Returns t if cond is true, and f otherwise. Component-wise if cond is a vector.

@example select(1, 2, false) // returns 1 select(1, 2, true) // returns 2 select(vec2i(1, 2), vec2i(3, 4), true) // returns vec2i(3, 4) select(vec2i(1, 2), vec2i(3, 4), vec2b(false, true)) // returns vec2i(1, 4)

select
(
import picker
picker
.
const byPointer: (candidate: picker.Candidate) => number

Ranks candidates by the screen distance from their center to the pointer, nearest first.

byPointer
(
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
),
import picker
picker
.
const byEye: (candidate: picker.Candidate) => number

Ranks candidates by depth, nearest the eye first.

byEye
(
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
),
const byEye: TgpuUniform<d.U32>
byEye
.
TgpuUniform<U32>.$: number
$
=== 1);
},
});
const byEye: TgpuUniform<d.U32>
byEye
.
TgpuBufferBindingBase<U32>.write(data: number, options?: BufferWriteOptions): void
write
(1); // the next pick keeps the star in front

radius, in world units, makes a big candidate easier to hit, and grows on the screen as it comes closer. One picker spans every kind of object a pointer can land on. Give each kind a range of indices, and the best rank of any kind wins. Here guns follow the wisps and are wider:

const
const hits: picker.Picker
hits
=
import picker
picker
.
function create(root: TgpuRoot, camera: cameras.CameraBase, options: picker.Options): picker.Picker

Finds a candidate under a screen point on the GPU. Projects every candidate with the camera and keeps the one within reach with the best rank. Throws unless capacity is an integer from 1 to 2^24 whose threads, 64 to a workgroup, fit the device's maxComputeWorkgroupsPerDimension.

@injects ― member found and ray, for shaders that act on the pick in the same frame; ray also reads cameras.current

@binds ― 1 storage: found, the pick's key

@binds ― 1 uniform: ray, the pick's point

@owns ― 3 buffers, a pipeline, a readback: the pick's key, the pointer and the settings; the readback brings the key to the CPU

@records ― pick once in a frame that picks, in a compute pass after whatever moves the candidates; result.capture(frame) after that pass, which copies what a pick found.

@param ― camera the camera the candidates are drawn with

@param ― options.position where each candidate is; it, radius, alive and rank carry the fills of what they read, such as Star.position.pipe(stars.inject())

@returns ― a picker you destroy

create
(
const root: TgpuRoot
root
,
const view: cameras.OrbitCamera
view
, {
Options.capacity: number

Sets the number of candidate slots, including dead slots. Indices range from 0 to `capacity

  • 1`. Must be an integer from 1 to 2^24.

capacity
:
const WISPS: 480
WISPS
+ 32,
Options.size: SizeSource

Supplies the view size at each pick, such as the canvas surface. pixelRatio scales reach from screen points to pixels. Without it, one point equals one pixel.

size
,
Options.position: (i: number) => d.v3f

Returns the candidate center in world space.

@gpu

position
: (
i: number
i
) => {
'use gpu';
if (
i: number
i
<
const WISPS: 480
WISPS
) return
const wisps: TgpuReadonly<d.WgslArray<d.Vec4f>>
wisps
.
TgpuReadonly<WgslArray<Vec4f>>.$: d.v4f[]
$
[
i: number
i
].
xyz: d.v3f
xyz
;
return
import d
d
.
const vec3f: d.Vec3f
(v: AnyNumericVec3Instance) => d.v3f (+5 overloads)
vec3f
(
const guns: TgpuReadonly<d.WgslArray<d.Vec3f>>
guns
.
TgpuReadonly<WgslArray<Vec3f>>.$: d.v3f[]
$
[
i: number
i
-
const WISPS: 480
WISPS
]);
},
Options.radius?: ((i: number) => number) | undefined

Returns the candidate radius in world units. Default 0, a point.

@gpu

radius
: (
i: number
i
) => {
'use gpu';
return
import std
std
.
function select(f: number, t: number, cond: boolean): number (+2 overloads)
export select

Returns t if cond is true, and f otherwise. Component-wise if cond is a vector.

@example select(1, 2, false) // returns 1 select(1, 2, true) // returns 2 select(vec2i(1, 2), vec2i(3, 4), true) // returns vec2i(3, 4) select(vec2i(1, 2), vec2i(3, 4), vec2b(false, true)) // returns vec2i(1, 4)

select
(0, 0.6,
i: number
i
>=
const WISPS: 480
WISPS
);
},
Options.alive?: ((i: number) => boolean) | undefined

Tests whether a candidate can be picked. Default every candidate can be picked.

@gpu

alive
: (
i: number
i
) => {
'use gpu';
return
i: number
i
>=
const WISPS: 480
WISPS
||
const wisps: TgpuReadonly<d.WgslArray<d.Vec4f>>
wisps
.
TgpuReadonly<WgslArray<Vec4f>>.$: d.v4f[]
$
[
i: number
i
].
v4f.w: number
w
> 0;
},
});

The picker kernel compiles these callbacks. They can read cameras.current.$ and any instance’s members, such as stars.gpu.position. Candidates in a take its capacity, alive and span from stars.live(): picker.create(root, view, { ...stars.live(), size, position }).

A centre and a radius only approximate a tall or long candidate, and reach admits candidates the pointer is only near. A negative rank turns a candidate down, so rank can test the real shape against candidate.ray. Returning the distance along the ray also puts the nearest hit first. Here each wisp is a ball, picked only where the ray passes through it:

const
const RANGE: 100
RANGE
= 100; // farther than any wisp is from the eye
const
const hits: picker.Picker
hits
=
import picker
picker
.
function create(root: TgpuRoot, camera: cameras.CameraBase, options: picker.Options): picker.Picker

Finds a candidate under a screen point on the GPU. Projects every candidate with the camera and keeps the one within reach with the best rank. Throws unless capacity is an integer from 1 to 2^24 whose threads, 64 to a workgroup, fit the device's maxComputeWorkgroupsPerDimension.

@injects ― member found and ray, for shaders that act on the pick in the same frame; ray also reads cameras.current

@binds ― 1 storage: found, the pick's key

@binds ― 1 uniform: ray, the pick's point

@owns ― 3 buffers, a pipeline, a readback: the pick's key, the pointer and the settings; the readback brings the key to the CPU

@records ― pick once in a frame that picks, in a compute pass after whatever moves the candidates; result.capture(frame) after that pass, which copies what a pick found.

@param ― camera the camera the candidates are drawn with

@param ― options.position where each candidate is; it, radius, alive and rank carry the fills of what they read, such as Star.position.pipe(stars.inject())

@returns ― a picker you destroy

create
(
const root: TgpuRoot
root
,
const view: cameras.OrbitCamera
view
, {
Options.capacity: number

Sets the number of candidate slots, including dead slots. Indices range from 0 to `capacity

  • 1`. Must be an integer from 1 to 2^24.

capacity
: 512,
Options.size: SizeSource

Supplies the view size at each pick, such as the canvas surface. pixelRatio scales reach from screen points to pixels. Without it, one point equals one pixel.

size
,
Options.position: (i: number) => d.v3f

Returns the candidate center in world space.

@gpu

position
: (
i: number
i
) => {
'use gpu';
return
const wisps: TgpuReadonly<d.WgslArray<d.Vec4f>>
wisps
.
TgpuReadonly<WgslArray<Vec4f>>.$: d.v4f[]
$
[
i: number
i
].
xyz: d.v3f
xyz
;
},
Options.radius?: ((i: number) => number) | undefined

Returns the candidate radius in world units. Default 0, a point.

@gpu

radius
: (
i: number
i
) => {
'use gpu';
return
const wisps: TgpuReadonly<d.WgslArray<d.Vec4f>>
wisps
.
TgpuReadonly<WgslArray<Vec4f>>.$: d.v4f[]
$
[
i: number
i
].
v4f.w: number
w
;
},
Options.rank?: ((candidate: picker.Candidate) => number) | undefined

Ranks candidates within reach, from 0 to 1. Keeps the lowest rank, then the lowest index among ties. A negative rank turns the candidate down, so a rank can be the distance at which candidate.ray meets the candidate's shape, negative for a miss. Can read a uniform to switch rankings, such as between byPointer and byEye, without recreating the picker. Default byPointer.

@gpu

rank
: (
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
) => {
'use gpu';
const
const to: d.v3f
to
=
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
.
position: d.v3f

Gives the candidate center in world space, as position returned it.

position
-
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
.
ray: {
origin: d.v3f;
direction: d.v3f;
}

Gives the ray through the pointer in world space, as cameras.rayOf computes it.

ray
.
origin: d.v3f
origin
;
const
const along: number
along
=
import std
std
.
dot<d.v3f>(lhs: d.v3f, rhs: d.v3f): number
export dot
dot
(
const to: d.v3f
to
,
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
.
ray: {
origin: d.v3f;
direction: d.v3f;
}

Gives the ray through the pointer in world space, as cameras.rayOf computes it.

ray
.
direction: d.v3f

Gives the unit ray direction.

direction
);
const
const beside: number
beside
=
import std
std
.
length<d.v3f>(value: d.v3f): number (+1 overload)
export length
length
(
const to: d.v3f
to
-
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
.
ray: {
origin: d.v3f;
direction: d.v3f;
}

Gives the ray through the pointer in world space, as cameras.rayOf computes it.

ray
.
direction: d.v3f

Gives the unit ray direction.

direction
*
const along: number
along
);
return
import std
std
.
function select(f: number, t: number, cond: boolean): number (+2 overloads)
export select

Returns t if cond is true, and f otherwise. Component-wise if cond is a vector.

@example select(1, 2, false) // returns 1 select(1, 2, true) // returns 2 select(vec2i(1, 2), vec2i(3, 4), true) // returns vec2i(3, 4) select(vec2i(1, 2), vec2i(3, 4), vec2b(false, true)) // returns vec2i(1, 4)

select
(
import d
d
.
function f32(v?: number | boolean): number
export f32

A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)

Can also be called to cast a value to an f32.

@example const value = f32(); // 0

@example const value = f32(1.23); // 1.23

@example const value = f32(true); // 1

f32
(-1),
const along: number
along
/
const RANGE: 100
RANGE
,
const beside: number
beside
<
const wisps: TgpuReadonly<d.WgslArray<d.Vec4f>>
wisps
.
TgpuReadonly<WgslArray<Vec4f>>.$: d.v4f[]
$
[
candidate: {
index: number;
gap: number;
depth: number;
position: d.v3f;
ray: {
origin: d.v3f;
direction: d.v3f;
};
}
candidate
.
index: number

Identifies the candidate by its index from 0 to capacity - 1.

index
].
v4f.w: number
w
);
},
});

For a box or a capsule, return where the ray enters it, as a fraction of a distance nothing lies beyond. Only candidates within reach are ranked, so radius must cover the shape.

For a finger, return half the hit’s rank and 0.5 + candidate.gap * 0.5 for a miss in place of the negative number, so hits come first and reach still finds a candidate when the ray meets none. A miss then ranks by the gap to its centre, which suits compact shapes.

hits.found() is the candidate the last pick found, or picker.none, in any shader. hits.ray() is the ray of that pick, in a pipeline piped with the camera, for a kernel that needs where the pick landed or which way to push. A kernel after pick sees this frame’s pick, so a tapped wisp lights up the frame the tap lands:

const
const mark: TgpuComputeFn<{}>
mark
=
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
.
computeFn: (options: {
workgroupSize: number[];
}) => TgpuComputeFnShell<{}> (+1 overload)
computeFn
({
workgroupSize: number[]
workgroupSize
: [1] })(() => {
'use gpu';
const
const wisp: number
wisp
=
const hits: picker.Picker
hits
.
Picker.found: () => number

Returns the candidate index from the last pick, or none, in any shader. Available in later passes of the same frame.

found
();
if (
const wisp: number
wisp
===
import picker
picker
.
const none: 4294967295

Marks a pick that found no candidate, as returned by found.

none
) return;
const marked: TgpuMutable<d.WgslArray<d.U32>>
marked
.
TgpuMutable<WgslArray<U32>>.$: number[]
$
[
const focus: TgpuMutable<d.U32>
focus
.
TgpuMutable<U32>.$: number
$
] = 0;
const marked: TgpuMutable<d.WgslArray<d.U32>>
marked
.
TgpuMutable<WgslArray<U32>>.$: number[]
$
[
const wisp: number
wisp
] = 1;
const focus: TgpuMutable<d.U32>
focus
.
TgpuMutable<U32>.$: number
$
=
const wisp: number
wisp
;
});
const
const marking: TgpuComputePipeline
marking
=
const root: TgpuRoot
root
.
WithBinding.createComputePipeline<{}>(descriptor: TgpuComputePipeline.Descriptor<{}>): TgpuComputePipeline
createComputePipeline
({
compute: TgpuComputeFn<{}>
compute
:
const mark: TgpuComputeFn<{}>
mark
});

For hovering, pick every frame and set hz to control . Only captures due at that rate copy the result. The star map reads at 20 Hz. result.latest holds the newest completed read, a frame or two behind. result.latestFrame identifies the frame that picked it. take() returns each completed read once.

When the pointer leaves, call hits.clear() and stop picking. found() returns none from then on, and the next capture reads null, without a dispatch.

A picker finds one candidate. To select everything inside a dragged box, list the candidates with live lists, whose alive can be any test, such as whether a centre lies between two corners of the screen:

const
const box: TgpuUniform<d.Vec4f>
box
=
const root: TgpuRoot
root
.
TgpuRoot.createUniform<d.Vec4f>(typeSchema: d.Vec4f, initial?: ((buffer: TgpuBuffer<NoInfer<d.Vec4f>>) => void) | d.InferInput<NoInfer<d.Vec4f>> | undefined): TgpuUniform<d.Vec4f> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader. Read-only on the GPU, optimized for small data. For a general-purpose buffer, use

TgpuRoot.createBuffer

.

@param ― typeSchema The type of data that this buffer will hold.

@param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

createUniform
(
import d
d
.
const vec4f: d.Vec4f
vec4f
); // two corners, from -1 to 1 with +y up
const
const selected: liveLists.LiveLists
selected
=
import liveLists
liveLists
.
function create(root: TgpuRoot, options: liveLists.Options): liveLists.LiveLists

Creates a list of live slots and an indirect draw per group. Each group reserves capacity slots. A shader finds rows with live.slot(group, i) using a captured group index. With firstInstance, it can use live.instanceSlot(instanceIndex) instead. Throws if the groups, draws or workgroup size are invalid, the slot buffer exceeds maxStorageBufferBindingSize, compact over the capacity needs more than maxComputeWorkgroupsPerDimension workgroups, or firstInstance lacks its required feature.

@param ― options.alive whether a slot holds a live row, carrying the fills of what it reads, such as a table's from rows.live(), spread into the options with its capacity

@param ― options.draws one draw per group

@returns ― live lists you run every frame and destroy

create
(
const root: TgpuRoot
root
, {
ListOptions.capacity: number

Sets the number of slots, including dead slots. Indices range from 0 to capacity - 1.

capacity
: 512,
alive: (i: number) => boolean

Tests whether slot i holds a live row. A table supplies this through live(). Default every slot is live.

@gpu

alive
:
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
.
fn: <(i: number) => boolean>(inner: (i: number) => boolean) => TgpuGenericFn<(i: number) => boolean> (+2 overloads)
fn
((
i: number
i
: number) => {
'use gpu';
const
const clip: d.v4f
clip
=
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 wisps: TgpuReadonly<d.WgslArray<d.Vec3f>>
wisps
.
TgpuReadonly<WgslArray<Vec3f>>.$: d.v3f[]
$
[
i: number
i
]);
const
const at: d.v2f
at
=
const clip: d.v4f
clip
.
xy: d.v2f
xy
/
const clip: d.v4f
clip
.
v4f.w: number
w
;
const
const inside: boolean
inside
=
import std
std
.
function all(value: boolean | AnyBooleanVecInstance): boolean
export all

Returns true if each component of value is true.

@example all(vec2b(false, true)) // returns false all(vec3b(true, true, true)) // returns true

all
(
import std
std
.
ge<d.v2f>(lhs: d.v2f, rhs: d.v2f): d.v2b
export ge

Checks component-wise whether lhs >= rhs. This function does not return bool, for that use-case, wrap the result in all.

@example ge(vec2f(0.0, 0.0), vec2f(0.0, 1.0)) // returns vec2b(true, false) ge(vec3u(0, 1, 2), vec3u(2, 1, 0)) // returns vec3b(false, true, true) all(ge(vec4i(2, 2, 4, 5), vec4i(1, 2, 3, 4))) // returns true

ge
(
const at: d.v2f
at
,
const box: TgpuUniform<d.Vec4f>
box
.
TgpuUniform<Vec4f>.$: d.v4f
$
.
xy: d.v2f
xy
)) &&
import std
std
.
function all(value: boolean | AnyBooleanVecInstance): boolean
export all

Returns true if each component of value is true.

@example all(vec2b(false, true)) // returns false all(vec3b(true, true, true)) // returns true

all
(
import std
std
.
le<d.v2f>(lhs: d.v2f, rhs: d.v2f): d.v2b
export le

Checks component-wise whether lhs <= rhs. This function does not return bool, for that use-case, wrap the result in all.

@example le(vec2f(0.0, 0.0), vec2f(0.0, 1.0)) // returns vec2b(true, true) le(vec3u(0, 1, 2), vec3u(2, 1, 0)) // returns vec3b(true, true, false) all(le(vec4i(1, 2, 3, 4), vec4i(2, 3, 3, 5))) // returns true

le
(
const at: d.v2f
at
,
const box: TgpuUniform<d.Vec4f>
box
.
TgpuUniform<Vec4f>.$: d.v4f
$
.
zw: d.v2f
zw
));
return
const clip: d.v4f
clip
.
v4f.w: number
w
> 0 &&
const inside: boolean
inside
;
})
.
TgpuGenericFn<(i: number) => boolean>.pipe(transform: (cfg: Configurable) => Configurable): TgpuGenericFn<(i: number) => boolean>

Applies a configuration transform to the slots and accessors this function reads, as root.pipe does to a pipeline's.

pipe
(
const view: cameras.OrbitCamera
view
.
CameraBase.inject(): Inject

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

inject
()),
});

Write the corners into box and record selected.compact(pass) in each frame that drags. selected.count(0) and selected.slot(0, i) give the selection to any shader, selected.dispatch runs a kernel over it, and a readback of selected.slots, with its count in selected.args, brings it to the CPU.

For a few candidates already on the CPU, use the camera’s projection to compare their screen positions without a kernel.

  • Rank precision Rank and index share one u32, which leaves rank about 2^(32 − ceil(log2 capacity)) levels, at most 2^24. That is 4 096 levels at a capacity of 2^20 and 256 at 2^24. Closer ranks tie, so a very large capacity ranks coarsely.
  • Second pointer A second pointer needs a picker of its own.
  • Capacity A pick runs a a candidate, 64 to a , so create throws past 64 times the device’s maxComputeWorkgroupsPerDimension: 4 194 240 candidates at WebGPU’s default.
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 →
kernelA kernel is a compute function that the GPU runs many times at once, each run on its own thread.A frame in plain TypeGPU →
hostA host runs a scene for you, which means it makes the device, the surface and the frame loop and frees them in order.Hosting scenes →
dispatchA dispatch runs a kernel once over a number of threads, inside a compute pass.Words →
tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
readbackA readback copies a buffer during a frame and hands it to the CPU a frame or two later, without making the frame wait.Results back →
threadA thread is one run of a kernel, and the GPU starts many at once, each with its own number.Slime mould →
workgroupA workgroup is a block of threads that the GPU starts together, and a dispatch runs as many workgroups as cover the work.Slime mould →

Reference

kit.picker

moduleHow to read this card

Callsborrows, never destroystakesneeds a modulereturns

picker.create(root, camera, { capacity, size, position, … }) → Picker

root
the root
camera
cameras the camera the candidates are drawn with
position
where each candidate is; it, radius, alive and rank carry the fills of what they read, such as Star.position.pipe(stars.inject())
Picker
a picker you destroy
takes

Options

9 fields
capacity

number

Sets the number of candidate slots, including dead slots.

size

SizeSource

Supplies the view size at each pick, such as the canvas surface.

position

(i: number) => d.v3f'use gpu'

Returns the candidate center in world space.

radius?

(i: number) => number'use gpu'

Returns the candidate radius in world units.Default 0, a point.

alive?

(i: number) => boolean'use gpu'

Tests whether a candidate can be picked.Default every candidate can be picked.

span?

() => number

Returns the highest live slot plus one, read when pick records, such as a table's from live().Default capacity.

rank?

(candidate: Candidate) => number'use gpu'

Ranks candidates within reach, from 0 to 1.Default byPointer.

hz?

number

Reads results this many times per second for hovering, which picks every frame.Default none.

settings?

Partial<Settings>

Sets the initial reach.Default defaults, 24 points.

returns

Picker

11 members
capacity

number

Reports the number of candidate slots, from the capacity option.

inject()

Fills found with this picker's key, as its default does.

found()

Returns the candidate index from the last pick, or none, in any shader.

ray()

Returns the ray through the point of the last pick in world space, as cameras.rayOf computes it, in a shader of a pipeline piped with the camera.

result

Readback<number | null>

Reads the picked candidate index to the CPU, or null if nothing was found.

result.capture(frame)

Records a copy when a next() is waiting, a request is pending or the capture rate is due.

settings

TgpuUniform<Settings>

Holds the reach setting.

initAsync()

Compiles the pick pipeline.

pick(pass, x, y)

Picks at x, y from 0 to 1 across the view, from the top-left corner, as view.rayAt and pointing take them.

clear()

Forgets the last pick without a dispatch, such as when the pointer leaves: found returns none and the next capture reads null, until the next pick.

destroy()

Destroys its key buffer and readback.

In a frame

records

pick once in a frame that picks, in a compute pass after whatever moves the candidates; result.capture(frame) after that pass, which copies what a pick found.

Holds

owns

3 buffers ·a pipeline ·a readback

The pick's key, the pointer and the settings; the readback brings the key to the CPU.

lifecycle

initAsync()destroy()[Symbol.dispose]

binds
  • 1 storage

    found, the pick's key.

  • 1 uniform

    ray, the pick's point.

Connects to

injects
  • member

    found and ray, for shaders that act on the pick in the same frame; ray also reads cameras.current.

needs
  • cameras

    As camera; fills a hook in its pipelines.

Exports

GPU functions
byPointer byEye
schemas
Settings Candidate
constants
none defaults
schema

Settings

1 field
reach

d.f32

Extends the candidate edge by this many screen points.

schema

Candidate

5 fields
index

d.u32

Identifies the candidate by its index from 0 to capacity - 1.

gap

d.f32

Measures the screen distance from the pointer to the candidate center as a fraction of the screen diagonal.

depth

d.f32

Gives the center depth, from 0 at the near plane to 1 at the far plane, in equal steps of distance along the viewing direction.

position

d.vec3f

Gives the candidate center in world space, as position returned it.

ray

cameras.Ray

Gives the ray through the pointer in world space, as cameras.rayOf computes it.

used byDomino runJelliesSolar systemStampedeStar map