/** * A representation of a compute shader with the associated resources, that can be executed on the * GPU. Only supported on WebGPU platform. * * Every uniform and resource the compute shader declares has to be given a value on the compute * instance, using {@link Compute#setParameter}. Values set globally on the scope of the graphics * device are not used. The scene depth and color maps of a camera are made available to the shader * using {@link Compute#setSceneDepthMap} and {@link Compute#setSceneColorMap}. * * A compute instance is dispatched at most once in a frame. To dispatch a compute shader more than * once in a frame, use a separate compute instance for each dispatch. The instances can share the * shader, which is compiled only once. * * Call {@link Compute#destroy} when no longer needed. The graphics device retains compute * instances for device recovery until they are explicitly destroyed. * * @category Graphics */ export class Compute { /** * Calculate near-square 2D dispatch dimensions for a given workgroup count, * respecting the WebGPU per-dimension limit. When the count fits within a single * dimension, Y is 1. Otherwise, dimensions are chosen to be roughly square to * minimize wasted padding threads. * * @param {number} count - Total number of workgroups needed. * @param {Vec2} result - Output vector to receive X (x) and Y (y) dimensions. * @param {number} [maxDimension] - Maximum workgroups per dimension. * @returns {Vec2} The result vector with dimensions set. * @ignore */ static calcDispatchSize(count: number, result: Vec2, maxDimension?: number): Vec2; /** * Create a compute instance. Note that this is supported on WebGPU only and is a no-op on * other platforms. * * @param {GraphicsDevice} graphicsDevice * The graphics device. * @param {Shader} shader - The compute shader. * @param {string} [name] - The name of the compute instance, used for debugging only. */ constructor(graphicsDevice: GraphicsDevice, shader: Shader, name?: string); /** * A compute shader. * * @type {Shader|null} * @ignore */ shader: Shader | null; /** * The non-unique name of an instance of the class. Defaults to 'Unnamed'. * * @type {string} */ name: string; /** * The shader the compute is dispatched with - the {@link Compute#shader} itself, or its variant * compiled for the attached scene maps. * * @type {Shader|null} * @ignore */ activeShader: Shader | null; /** * @type {Map} * @ignore */ parameters: Map; /** * Incremented when a parameter is added or deleted, so that the implementation knows to look up * the parameters of the bind group slots again. * * @type {number} * @ignore */ parametersVersion: number; /** * @type {SceneDepthMapHandle|null} * @private */ private _sceneDepthMap; /** * @type {SceneColorMapHandle|null} * @private */ private _sceneColorMap; /** * The key of the shader variant the compute is dispatched with, 0 for the shader itself. * * @type {number} * @private */ private _variantKey; /** * The variants of the shader compiled for the scene maps the compute has been dispatched with, * keyed by their variant key. Created on first use, and destroyed with the compute. * * @type {Map|null} * @private */ private _variants; /** * The number of threads of the dispatch set up by {@link Compute#setupDispatchThreads}, for * the uniform of the dispatchThreadsCS chunk. * * @type {Uint32Array} * @private */ private _dispatchThreadCount; /** @ignore */ countX: number; /** * @type {number|undefined} * @ignore */ countY: number | undefined; /** * @type {number|undefined} * @ignore */ countZ: number | undefined; /** * Slot index in the indirect dispatch buffer, or -1 for direct dispatch. * * @ignore */ indirectSlotIndex: number; /** * Custom buffer for indirect dispatch, or null to use device's built-in buffer. * * @type {StorageBuffer|null} * @ignore */ indirectBuffer: StorageBuffer | null; /** * Frame stamp (device.renderVersion) when indirect slot was set. Used for validation * when using the built-in buffer. * * @ignore */ indirectFrameStamp: number; device: GraphicsDevice; impl: any; /** * Sets a shader parameter on a compute instance. Every uniform and resource the compute shader * declares needs a value set this way. * * @param {string} name - The name of the parameter to set. * @param {number|number[]|Float32Array|Int32Array|Texture|StorageBuffer|VertexBuffer|IndexBuffer|TextureView} value * The value for the specified parameter. */ setParameter(name: string, value: number | number[] | Float32Array | Int32Array | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView): void; /** * @param {string} name - The name of the parameter to set. * @param {*} value - The value. * @private */ private _setParameter; /** * Returns the value of a shader parameter from the compute instance. * * @param {string} name - The name of the parameter to get. * @returns {number|number[]|Float32Array|Texture|StorageBuffer|VertexBuffer|IndexBuffer|TextureView|undefined} * The value of the specified parameter. */ getParameter(name: string): number | number[] | Float32Array | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView | undefined; /** * Deletes a shader parameter from the compute instance. * * @param {string} name - The name of the parameter to delete. */ deleteParameter(name: string): void; /** * Attaches the scene depth map of a camera to this compute instance, making it available to * the compute shader, which accesses it using the functions of the `sceneDepthCS` chunk it * includes: * * - `sceneDepthSize() -> vec2u`: the dimensions of the depth map. * - `sceneDepthViewport() -> vec4u`: the viewport the camera rendered the depth map with, in * texels: the x and y of its first texel, and its width and height. A camera rendering to only a * part of its target, see {@link CameraComponent#rect}, covers only this part of the depth map. * - `sceneDepthNearClip() -> f32`, `sceneDepthFarClip() -> f32`: the clip planes the depth map * was rendered with. * - `sceneDepthLinear(texel: vec2i) -> f32`: the linear camera depth, in world units. * - `sceneDepthWorldPosition(texel: vec2i) -> vec3f`: the world position of the surface at the * texel, which needs to be within the viewport. * * The handle is kept, and the depth map it identifies is read each time the compute is * dispatched, so this only needs to be called once. A dispatch uses the depth map the camera * rendered most recently - when dispatched before the camera renders, for example from an * update event, that is the depth map of the previous frame. However the camera stored the * depth, it is decoded with the camera parameters it was rendered with. * * The camera only renders the depth map when requested, see * {@link CameraComponent#requestSceneDepthMap}, or when its {@link CameraFrame} is configured to. * * @param {SceneDepthMapHandle|null} handle - The handle to the scene depth map of a camera, see * {@link CameraComponent#sceneDepthMapHandle}, or null to detach the depth map. * @example * // the compute shader includes the chunk, for example: * // #include "sceneDepthCS" * // let position = sceneDepthWorldPosition(vec2i(id.xy)); * cameraEntity.camera.requestSceneDepthMap(true); * compute.setSceneDepthMap(cameraEntity.camera.sceneDepthMapHandle); */ setSceneDepthMap(handle: SceneDepthMapHandle | null): void; /** * Attaches the scene color map of a camera to this compute instance, making it available to * the compute shader, which accesses it using the functions of the `sceneColorCS` chunk it * includes: * * - `sceneColorSize(lod: i32) -> vec2u`: the dimensions of a mip level of the color map. * - `sceneColorLoad(texel: vec2i, lod: i32) -> vec4f`: the color of a texel. * - `sceneColorSample(uv: vec2f, lod: f32) -> vec4f`: the color sampled with filtering. When * the format of the color map cannot be filtered on the device, the nearest texel is returned. * - `sceneColorToLinear(color: vec3f) -> vec3f`: converts a color to linear. * - `sceneColorToDisplay(color: vec3f) -> vec3f`: converts a color to gamma encoded. * * The colors are returned the way the camera stored them - linear when it renders without gamma * correction, as it does when using {@link CameraFrame}, and gamma encoded otherwise. * `SCENE_COLORMAP_GAMMA` is defined in the shader when they are gamma encoded, and the * conversion functions do nothing when the color is already in the requested space. * * The handle is kept, and the color map it identifies is read each time the compute is * dispatched, so this only needs to be called once. A dispatch uses the color map the camera * rendered most recently - when dispatched before the camera renders, for example from an * update event, that is the color map of the previous frame. * * The camera only renders the color map when requested, see * {@link CameraComponent#requestSceneColorMap}, or when its {@link CameraFrame} is configured to. * * @param {SceneColorMapHandle|null} handle - The handle to the scene color map of a camera, see * {@link CameraComponent#sceneColorMapHandle}, or null to detach the color map. * @example * // the compute shader includes the chunk, for example: * // #include "sceneColorCS" * // let color = sceneColorToLinear(sceneColorLoad(vec2i(id.xy), 0).rgb); * cameraEntity.camera.requestSceneColorMap(true); * compute.setSceneColorMap(cameraEntity.camera.sceneColorMapHandle); */ setSceneColorMap(handle: SceneColorMapHandle | null): void; /** * Returns true when the shader declares a texture of the given name. * * @param {string} name - The name of the texture. * @returns {boolean} True when the shader declares it. * @private */ private _declares; /** * Returns true when the shader declares a uniform of the given name. * * @param {string} name - The name of the uniform. * @returns {boolean} True when the shader declares it. * @private */ private _declaresUniform; /** * Frees resources associated with this compute instance. */ destroy(): void; /** * Prepares the compute for a dispatch which is about to be recorded. The attached scene maps * are read now, as this is the point in the frame the dispatch runs at, assigned to the * resources of the chunks accessing them, and the shader variant matching how they are stored * is selected. * * @ignore */ prepareDispatch(): void; /** * Returns the texture to bind for a scene map. In place of a map the camera has not rendered, a * substitute is bound and the omission reported. A substitute is also bound in place of a map * whose texture has since been destroyed, as happens when the way a camera renders its maps * changes, until the camera publishes the next one - which is expected, and not reported. * Neither is a destroyed camera, which the caller reports. * * @param {SceneDepthMapHandle|SceneColorMapHandle} handle - The handle to the map. * @param {string} kind - The kind of the map, for the report. * @param {string} substitute - The name of the built-in texture to bind. * @returns {Texture} The texture to bind. * @private */ private _sceneMapTexture; /** * Switches the compute to the shader variant of the key, recreating the implementation for it. * The parameters are kept, as they are stored on the compute itself. * * @param {number} key - The key of the variant. * @private */ private _setVariant; /** * Prepare the compute work dispatch, for a grid of workgroups. To dispatch for a number of * threads instead, with the workgroups derived from them, use * {@link Compute#setupDispatchThreads}. * * @param {number} x - X dimension of the grid of work-groups to dispatch. * @param {number} [y] - Y dimension of the grid of work-groups to dispatch. * @param {number} [z] - Z dimension of the grid of work-groups to dispatch. */ setupDispatch(x: number, y?: number, z?: number): void; /** * Prepare the compute work dispatch, for a number of threads in each dimension, a thread being * one invocation of the compute shader, as identified by its `global_invocation_id`. The * workgroups to dispatch are derived from the workgroup size the entry point of the shader * declares using `@workgroup_size` with integer literals, which can be the values of defines * injected into the shader. The dispatch is rounded up to whole workgroups, so the shader skips * the threads beyond the requested number. To do that, and to index the threads, it uses the * functions of the `dispatchThreadsCS` chunk it includes: * * - `dispatchThreadCount() -> vec3u`: the number of threads the dispatch was set up for. * - `dispatchThreadInRange(globalId: vec3u) -> bool`: true when the thread is one of those * threads. * - `dispatchThreadIndex(globalId: vec3u) -> u32`: the linear index of the thread, x varying * fastest. * * A dispatch of threads in one dimension, which needs more workgroups than the device supports * in a single dimension, is spread over rows of workgroups. The shader then needs to include * the chunk, as the functions account for that. * * A compute shader using the chunk, dispatched for a thread for each particle: * * ```wgsl * #include "dispatchThreadsCS" * * @compute @workgroup_size(64) * fn main(@builtin(global_invocation_id) id: vec3u) { * if (!dispatchThreadInRange(id)) { return; } * let index = dispatchThreadIndex(id); * } * ``` * * @param {number} x - The number of threads in the X dimension. * @param {number} [y] - The number of threads in the Y dimension. Defaults to 1. * @param {number} [z] - The number of threads in the Z dimension. Defaults to 1. * @example * compute.setupDispatchThreads(particleCount); */ setupDispatchThreads(x: number, y?: number, z?: number): void; /** * Prepare the compute work dispatch to use indirect parameters from a buffer. The dispatch * parameters (x, y, z workgroup counts) are read from the buffer at the specified slot index. * * When using the device's built-in buffer (buffer parameter is null), this method must be * called each frame as slots are only valid for the current frame. * * @param {number} slotIndex - Slot index in the indirect dispatch buffer. When using the * device's built-in buffer, obtain this by calling {@link GraphicsDevice#getIndirectDispatchSlot}. * @param {StorageBuffer|null} [buffer] - Optional custom storage buffer containing dispatch * parameters. If not provided, uses the device's built-in {@link GraphicsDevice#indirectDispatchBuffer}. * When providing a custom buffer, the user is responsible for its lifetime and contents. * @example * // Reserve a slot in the indirect dispatch buffer * const slot = device.getIndirectDispatchSlot(); * * // First compute shader writes dispatch parameters to the buffer * prepareCompute.setParameter('indirectBuffer', device.indirectDispatchBuffer); * prepareCompute.setParameter('slot', slot); * prepareCompute.setupDispatch(1, 1, 1); * device.computeDispatch([prepareCompute]); * * // Second compute shader uses indirect dispatch * processCompute.setupIndirectDispatch(slot); * device.computeDispatch([processCompute]); */ setupIndirectDispatch(slotIndex: number, buffer?: StorageBuffer | null): void; } import { Shader } from './shader.js'; /** * A helper class storing a parameter value. * * @ignore */ declare class ComputeParameter { value: any; } import type { StorageBuffer } from './storage-buffer.js'; import type { GraphicsDevice } from './graphics-device.js'; import type { Texture } from './texture.js'; import type { VertexBuffer } from './vertex-buffer.js'; import type { IndexBuffer } from './index-buffer.js'; import type { TextureView } from './texture-view.js'; import { SceneDepthMapHandle } from './scene-depth-map-handle.js'; import { SceneColorMapHandle } from './scene-color-map-handle.js'; import { Vec2 } from '../../core/math/vec2.js'; export {};