wgpu

Cross-platform GPU compute and rendering via WebGPU (wgpu-native)

Files

FileDescription
.editorconfigEditor formatting configuration
.gitignoreGit ignore rules for build artifacts and dependencies
.tool-versionsasdf tool versions (Zig, Kit)
LICENSEMIT license file
README.mdThis file
c/kit_wgpu.cC FFI wrapper
c/kit_wgpu.hC header for FFI wrapper
examples/hello-compute.kitBasic GPU compute example
examples/texture-invert.kitTexture color inversion example
examples/image-sepia.kitImage sepia tone via GPU compute
kit.tomlPackage manifest with metadata and dependencies
src/main.kitkit-wgpu: GPU compute and rendering via WebGPU
src/buffer.kitGPU buffer creation and float read/write
src/compute.kitWGSL shader compilation and compute dispatch
src/context.kitGPU context initialization and teardown
src/sampler.kitTexture sampler creation
src/texture.kitGPU texture creation, pixel access, and upload/download
src/types.kitGPUError type, buffer/texture/filter/address constants
tests/compute.test.kitTests for compute pipeline
tests/texture.test.kitTests for texture operations
tests/image-bridge.test.kitTests for kit-image integration

Dependencies

PackageDescription
kit-imageImage loading and manipulation (for bulk texture transfers)

Installation

kit add gitlab.com/kit-lang/packages/kit-wgpu.git

System Requirements

wgpu-native must be installed on your system:

PlatformCommand
macOSbrew install wgpu-native
Ubuntusudo apt install libwgpu-native-dev
Fedorasudo dnf install wgpu-native-devel

Usage

import Kit.WGPU as GPU

main = fn(-env) =>
  # Initialize GPU
  ctx = GPU.init 0 |> Result.unwrap
  println "GPU: ${GPU.adapter-name ctx}"

  count = 8
  storage = GPU.buffer-usage-storage
  copy-src = GPU.buffer-usage-copy-src
  copy-dst = GPU.buffer-usage-copy-dst
  map-rd = GPU.buffer-usage-map-read

  # Create input buffer (storage + copy-src), mapped for writing
  input-buf = GPU.create-buffer ctx count (storage + copy-src) 1 |> Result.unwrap

  # Write 8 float values: [1.0, 2.0, 3.0, ..., 8.0]
  List.range 0 count |> List.map (fn(i) => GPU.set-float input-buf i (Int.to-float (i + 1)))
  GPU.unmap input-buf

  # Create output buffer (storage + copy-src) for compute shader output
  output-buf = GPU.create-buffer ctx count (storage + copy-src) 0 |> Result.unwrap

  # Create staging buffer (map-read + copy-dst) for CPU readback
  staging-buf = GPU.create-buffer ctx count (map-rd + copy-dst) 0 |> Result.unwrap

  # WGSL shader that doubles each value
  wgsl = <<~WGSL
    @group(0) @binding(0) var<storage, read> input: array<f32>;
    @group(0) @binding(1) var<storage, read_write> output: array<f32>;
    @compute @workgroup_size(64)
    fn main(@builtin(global_invocation_id) id: vec3<u32>) {
      let i = id.x;
      if (i < arrayLength(&input)) {
        output[i] = input[i] * 2.0;
      }
    }
  WGSL
  shader = GPU.create-shader ctx wgsl |> Result.unwrap

  # Dispatch compute (1 workgroup)
  GPU.dispatch-clear
  GPU.dispatch-add input-buf
  GPU.dispatch-add output-buf
  GPU.compute ctx shader "main" 1 1 1 |> Result.unwrap

  # Copy output to staging buffer, then read
  GPU.copy-buffer ctx output-buf staging-buf count
  GPU.map-read ctx staging-buf |> Result.unwrap
  println "Results:"
  List.range 0 count |> List.map (fn(i) =>
    val = GPU.get-float staging-buf i
    println "  output[${show i}] = ${show val}"
  )
  GPU.unmap staging-buf

  # Cleanup
  GPU.release-buffer input-buf
  GPU.release-buffer output-buf
  GPU.release-buffer staging-buf
  GPU.destroy-shader shader
  GPU.destroy ctx

main

Development

Running Examples

Run examples with the interpreter:

kit run examples/hello-compute.kit

Compile examples to a native binary:

kit build examples/hello-compute.kit && ./hello-compute

Running Tests

Run the test suite:

kit test

Run the test suite with coverage:

kit test --coverage

Running kit dev

Run the standard development workflow (format, check, test):

kit dev

This will:

  1. Format and check source files in src/
  2. Run tests in tests/ with coverage

Generating Documentation

Generate API documentation from doc comments:

kit doc

Note: Kit sources with doc comments (##) will generate HTML documents in docs/*.html

Cleaning Build Artifacts

Remove generated files, caches, and build artifacts:

kit task clean

Note: Defined in kit.toml.

Local Installation

To install this package locally for development:

kit install

This installs the package to ~/.kit/packages/@kit/wgpu/, making it available for import as Kit.WGPU in other projects.

License

This package is released under the MIT License - see LICENSE for details.

wgpu-native is released under the Apache 2.0 / MIT License.

Exported Functions & Types

create-shader

Compile a WGSL shader module.

Parameters:

Returns:

Ptr -> NonEmptyString -> Result Ptr GPUError

destroy-shader

Destroy a shader module and release its resources.

Ptr -> Unit

dispatch-clear

Clear the dispatch entry list. Call this before adding entries for a new compute dispatch.

Unit

dispatch-add

Add a buffer to the dispatch entry list. Entries are bound in order as @binding(0), @binding(1), etc.

Ptr -> Unit

dispatch-add-storage-texture

Add a storage texture view to the dispatch entry list. Used for textures bound as read_write storage (textureStore).

Ptr -> Unit

dispatch-add-sampled-texture

Add a sampled texture view to the dispatch entry list. Used for textures bound as read-only (textureLoad/textureSample).

Ptr -> Unit

dispatch-add-sampler

Add a sampler to the dispatch entry list.

Ptr -> Unit

run

Run a compute shader.

Uses the entries previously added via dispatch-clear/dispatch-add*. Blocks until the compute operation is complete.

Parameters:

Returns:

Ptr -> Ptr -> NonEmptyString -> PositiveInt -> PositiveInt -> PositiveInt -> Result Unit GPUError

GPUError

GPU error type for typed error handling.

Variants

GPUError

AdapterNotFound

Adapter not found error variant.

Variants

AdapterNotFound

DeviceRequestFailed

Device request failed error variant.

Variants

DeviceRequestFailed

ShaderCompileError

Shader compile error variant.

Variants

ShaderCompileError

BufferError

Buffer error variant.

Variants

BufferError

ComputeError

Compute error variant.

Variants

ComputeError

TextureError

Texture error variant.

Variants

TextureError

buffer-usage-map-read

Buffer can be mapped for reading.

Int

buffer-usage-map-write

Buffer can be mapped for writing.

Int

buffer-usage-copy-src

Buffer can be used as a copy source.

Int

buffer-usage-copy-dst

Buffer can be used as a copy destination.

Int

buffer-usage-uniform

Buffer can be used as a uniform buffer.

Int

buffer-usage-storage

Buffer can be used as a storage buffer.

Int

texture-format-r8-unorm

R8Unorm texture format (1 byte per pixel, single channel).

Int

texture-format-r32-float

R32Float texture format (4 bytes per pixel, single float channel).

Int

texture-format-rgba8-unorm

RGBA8Unorm texture format (4 bytes per pixel, 8-bit RGBA).

Int

texture-format-rgba8-unorm-srgb

RGBA8UnormSrgb texture format (4 bytes per pixel, sRGB RGBA).

Int

texture-format-bgra8-unorm

BGRA8Unorm texture format (4 bytes per pixel, BGRA order).

Int

texture-format-rgba32-float

RGBA32Float texture format (16 bytes per pixel, 32-bit float RGBA).

Int

texture-usage-copy-src

Texture can be used as a copy source.

Int

texture-usage-copy-dst

Texture can be used as a copy destination.

Int

texture-usage-texture-binding

Texture can be bound as a sampled texture.

Int

texture-usage-storage-binding

Texture can be bound as a storage texture.

Int

filter-nearest

Nearest-neighbor filtering.

Int

filter-linear

Linear interpolation filtering.

Int

address-clamp-to-edge

Clamp texture coordinates to [0, 1].

Int

address-repeat

Repeat texture coordinates.

Int

address-mirror-repeat

Mirror and repeat texture coordinates.

Int

init

Initialize the GPU context.

NonNegativeInt -> Result Ptr GPUError

destroy

Destroy the GPU context and release all resources.

Ptr -> Unit

adapter-name

Get the name of the GPU adapter.

Ptr -> String

create-buffer

Create a GPU buffer for float data.

Ptr -> PositiveInt -> Int -> Int -> Result Ptr GPUError

set-float

Write a float value to a mapped buffer at the given index.

Ptr -> NonNegativeInt -> Float -> Unit

get-float

Read a float value from a mapped buffer at the given index.

Ptr -> NonNegativeInt -> Float

map-read

Map a buffer for CPU reading. Blocks until mapped.

Ptr -> Ptr -> Result Unit GPUError

unmap

Unmap a previously mapped buffer.

Ptr -> Unit

copy-buffer

Copy float data between GPU buffers.

Ptr -> Ptr -> Ptr -> PositiveInt -> Unit

release-buffer

Release a buffer and its resources.

Ptr -> Unit

create-shader

Compile a WGSL shader module.

Ptr -> NonEmptyString -> Result Ptr GPUError

destroy-shader

Destroy a shader module and release its resources.

Ptr -> Unit

dispatch-clear

Clear the dispatch entry list.

Unit

dispatch-add

Add a buffer to the dispatch entry list.

Ptr -> Unit

dispatch-add-storage-texture

Add a storage texture view to the dispatch entry list.

Ptr -> Unit

dispatch-add-sampled-texture

Add a sampled texture view to the dispatch entry list.

Ptr -> Unit

dispatch-add-sampler

Add a sampler to the dispatch entry list.

Ptr -> Unit

compute

Run a compute shader with the previously added entries.

Ptr -> Ptr -> NonEmptyString -> PositiveInt -> PositiveInt -> PositiveInt -> Result Unit GPUError

create-texture

Create a 2D GPU texture with CPU staging buffer.

Ptr -> PositiveInt -> PositiveInt -> Int -> Int -> Result Ptr GPUError

texture-width

Get the width of a texture in pixels.

Ptr -> Int

texture-height

Get the height of a texture in pixels.

Ptr -> Int

texture-set-pixel

Set a pixel's RGBA values in the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Byte -> Byte -> Byte -> Byte -> Unit

texture-get-pixel-r

Get the red channel of a pixel from the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Int

texture-get-pixel-g

Get the green channel of a pixel from the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Int

texture-get-pixel-b

Get the blue channel of a pixel from the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Int

texture-get-pixel-a

Get the alpha channel of a pixel from the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Int

texture-upload

Upload staging buffer data to the GPU texture.

Ptr -> Ptr -> Result Unit GPUError

texture-download

Download GPU texture data to the CPU staging buffer.

Ptr -> Ptr -> Result Unit GPUError

create-texture-view

Create a texture view for use in bind groups.

Ptr -> Result Ptr GPUError

release-texture

Release a texture and its staging buffer.

Ptr -> Unit

texture-copy-from-bytes

Copy raw bytes from an image data pointer into the texture staging buffer. Handles channel conversion (1ch/3ch/4ch → RGBA8) internally.

Ptr -> Ptr -> PositiveInt -> PositiveInt -> PositiveInt -> Unit

texture-copy-to-bytes

Copy texture staging buffer data to a raw byte pointer. Handles channel conversion (RGBA8 → 1ch/3ch/4ch) internally.

Ptr -> Ptr -> PositiveInt -> PositiveInt -> PositiveInt -> Unit

release-texture-view

Release a texture view.

Ptr -> Unit

create-sampler

Create a GPU sampler for texture filtering.

Ptr -> Int -> Int -> Int -> Result Ptr GPUError

release-sampler

Release a sampler and its resources.

Ptr -> Unit

init

Initialize the GPU context.

Creates a WebGPU instance, requests an adapter and device. The backend parameter is reserved for future use (pass 0 for default).

Returns:

NonNegativeInt -> Result Ptr GPUError

destroy

Destroy the GPU context and release all resources.

Ptr -> Unit

adapter-name

Get the name of the GPU adapter.

Ptr -> String

create

Create a 2D GPU texture with a CPU staging buffer.

Parameters:

Returns:

Ptr -> PositiveInt -> PositiveInt -> Int -> Int -> Result Ptr GPUError

width

Get the width of a texture in pixels.

Ptr -> Int

height

Get the height of a texture in pixels.

Ptr -> Int

set-pixel

Set a pixel's RGBA values in the CPU staging buffer. Values are clamped to 0-255.

Ptr -> NonNegativeInt -> NonNegativeInt -> Byte -> Byte -> Byte -> Byte -> Unit

get-pixel-r

Get the red channel of a pixel from the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Int

get-pixel-g

Get the green channel of a pixel from the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Int

get-pixel-b

Get the blue channel of a pixel from the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Int

get-pixel-a

Get the alpha channel of a pixel from the CPU staging buffer.

Ptr -> NonNegativeInt -> NonNegativeInt -> Int

upload

Upload staging buffer data to the GPU texture.

Ptr -> Ptr -> Result Unit GPUError

download

Download GPU texture data to the CPU staging buffer.

Ptr -> Ptr -> Result Unit GPUError

create-view

Create a texture view for use in bind groups.

Ptr -> Result Ptr GPUError

release

Release a texture and its staging buffer.

Ptr -> Unit

copy-from-bytes

Copy raw bytes from an image data pointer into the texture staging buffer. Handles channel conversion (1ch/3ch/4ch → RGBA8) internally.

Ptr -> Ptr -> PositiveInt -> PositiveInt -> PositiveInt -> Unit

copy-to-bytes

Copy texture staging buffer data to a raw byte pointer. Handles channel conversion (RGBA8 → 1ch/3ch/4ch) internally.

Ptr -> Ptr -> PositiveInt -> PositiveInt -> PositiveInt -> Unit

release-view

Release a texture view.

Ptr -> Unit

create

Create a GPU sampler for texture filtering.

Parameters:

Returns:

Ptr -> Int -> Int -> Int -> Result Ptr GPUError

release

Release a sampler and its resources.

Ptr -> Unit

create

Create a GPU buffer for float data.

Parameters:

Returns:

Ptr -> PositiveInt -> Int -> Int -> Result Ptr GPUError

set-float

Write a float value to a mapped buffer at the given index.

Ptr -> NonNegativeInt -> Float -> Unit

get-float

Read a float value from a mapped buffer at the given index.

Ptr -> NonNegativeInt -> Float

map-read

Map a buffer for CPU reading. Blocks until the buffer is mapped.

Parameters:

Returns:

Ptr -> Ptr -> Result Unit GPUError

unmap

Unmap a previously mapped buffer.

Ptr -> Unit

copy

Copy float data from one buffer to another on the GPU.

Ptr -> Ptr -> Ptr -> PositiveInt -> Unit

release

Release a buffer and its resources.

Ptr -> Unit

GPUError

GPU error type for typed error handling. Variants distinguish between different failure modes.

Variants

AdapterNotFound {message}
DeviceRequestFailed {message}
ShaderCompileError {message}
BufferError {message}
ComputeError {message}
TextureError {message}

buffer-usage-map-read

Buffer can be mapped for reading.

buffer-usage-map-write

Buffer can be mapped for writing.

buffer-usage-copy-src

Buffer can be used as a copy source.

buffer-usage-copy-dst

Buffer can be used as a copy destination.

buffer-usage-uniform

Buffer can be used as a uniform buffer.

buffer-usage-storage

Buffer can be used as a storage buffer.

texture-format-r8-unorm

R8Unorm texture format (1 byte per pixel, single channel).

texture-format-r32-float

R32Float texture format (4 bytes per pixel, single float channel).

texture-format-rgba8-unorm

RGBA8Unorm texture format (4 bytes per pixel, 8-bit RGBA).

texture-format-rgba8-unorm-srgb

RGBA8UnormSrgb texture format (4 bytes per pixel, sRGB RGBA).

texture-format-bgra8-unorm

BGRA8Unorm texture format (4 bytes per pixel, BGRA order).

texture-format-rgba32-float

RGBA32Float texture format (16 bytes per pixel, 32-bit float RGBA).

texture-usage-copy-src

Texture can be used as a copy source.

texture-usage-copy-dst

Texture can be used as a copy destination.

texture-usage-texture-binding

Texture can be bound as a sampled texture (for textureLoad/textureSample).

texture-usage-storage-binding

Texture can be bound as a storage texture (for textureStore).

filter-nearest

Nearest-neighbor filtering.

filter-linear

Linear interpolation filtering.

address-clamp-to-edge

Clamp texture coordinates to [0, 1].

address-repeat

Repeat texture coordinates.

address-mirror-repeat

Mirror and repeat texture coordinates.