Utilities

The wgpu library provides a few utilities. Note that the functions below need to be explictly imported.

wgpu.utils.get_default_device()

Get a wgpu device object. If this succeeds, it’s likely that the WGPU lib is usable on this system. If not, this call will probably exit (Rust panic). When called multiple times, returns the same global device object (useful for e.g. unit tests).

wgpu.utils.compute_with_buffers(input_arrays, output_arrays, shader, n=None)

Apply the given compute shader to the given input_arrays and return output arrays. Both input and output arrays are represented on the GPU using storage buffer objects.

Parameters:
  • input_arrays (dict) – A dict mapping int bindings to arrays. The array can be anything that supports the buffer protocol, including bytes, memoryviews, ctypes arrays and numpy arrays. The type and shape of the array does not need to match the type with which the shader will interpret the buffer data (though it probably makes your code easier to follow).
  • output_arrays (dict) – A dict mapping int bindings to output shapes. If the value is int, it represents the size (in bytes) of the buffer. If the value is a tuple, its last element specifies the format (see below), and the preceding elements specify the shape. These are used to cast() the memoryview object before it is returned. If the value is a ctypes array type, the result will be cast to that instead of a memoryview. Note that any buffer that is NOT in the output arrays dict will be considered readonly in the shader.
  • shader (str or bytes) – The shader as a string of WGSL code or SpirV bytes.
  • n (int, tuple, optional) – The dispatch counts. Can be an int or a 3-tuple of ints to specify (x, y, z). If not given or None, the length of the first output array type is used.
Returns:

A dict mapping int bindings to memoryviews.

Return type:

output (dict)

The format characters to cast a memoryview are hard to remember, so here’s a refresher:

  • “b” and “B” are signed and unsiged 8-bit ints.
  • “h” and “H” are signed and unsiged 16-bit ints.
  • “i” and “I” are signed and unsiged 32-bit ints.
  • “e” and “f” are 16-bit and 32-bit floats.