gpu crate root#
type Result<T> = core::result::Result<T, GpuError>
/// the most push-constant bytes a pipeline layout may declare (every backend guarantees it)
PUSH_CONSTANTS_MAX: u32 = 128
/// the most bind groups of a pipeline layout
BIND_GROUPS_MAX: u32 = 4
/// the most colour targets of a render pass
COLOR_TARGETS_MAX: usize = 8
enum GpuErrorwhat went wrongDisabled-- the GPU is switched off (jfgui_GPU=0)NoLoader-- the GPU API is not installed (no vulkan-1.dll or libvulkan.so.1, jfgui_GPU_DLL names a missing file, a Linux program not linked against glibc, a browser without navigator.gpu); never on macOS and iOS, where Metal is part of the system: a Mac without a Metal device gives NoAdapterNoAdapter-- no usable GPU (or jfgui_GPU_ADAPTER matched none)Unsupported(&'static str)-- the adapter or this backend lacks something (a feature, a format, the level)Invalid(&'static str)-- a call the API does not allow (sizes, alignments, states, order)OutOfMemory-- host or device memory exhaustedDeviceLost-- the device was lost (driver reset, GPU removed): recreate itSurfaceLost-- the window's surface is goneTimeout-- a wait ran out of timeNotReady-- results are not available yet (timestamps not written or not finished)Failed(i32)-- another failure of the GPU API (its code: a VkResult)
unsafe trait Pod: Copy + 'staticplain data that may be copied to and from GPU memory byte for byte: no padding, no pointers, every bit pattern validSafety#
Implemented here for the integer and float types and arrays of them.
fn bytes_of<T: Pod>(s: &[T]) -> &[u8]the bytes of a slice of plain dataenum Levelthe feature level of a device (Basis < Voll)Basis-- WebGPU / Vulkan 1.1: compute, storage buffers, single indirect draws, texture arraysVoll-- Vulkan 1.3 with bindless descriptors, indirect count, multi-draw, subgroups
enum AdapterKindwhat kind of GPUDiscreteIntegratedVirtualCpuOther
struct AdapterInfowho an adapter isname: String-- the GPU's name ("NVIDIA GeForce RTX 2070 SUPER")vendor_id: u32device_id: u32vendor: &'static str-- the vendor's name for well-known vendor ids ("NVIDIA", "AMD", "Intel", ..)kind: AdapterKinddriver: String-- the driver's name ("NVIDIA") and its information string (the version as the vendor writes it)driver_info: Stringdriver_version: String-- the driver version decoded by the vendor's schemeapi_version: (u32, u32, u32)-- the API version the device supports (major, minor, patch)backend: &'static str-- "Vulkan", later "WebGPU" / "Metal"missing: Option<&'static str>-- why the backend cannot use this adapter (None: usable)
struct Featureswhat a device can do beyond the Basis leveltimestamps: bool-- GPU timestamps on the queue (Timestamps)multi_draw_indirect: bool-- draw_indexed_indirect_multi (several draws from one buffer)draw_indirect_first_instance: bool-- a first instance other than 0 in indirect drawsdraw_indirect_count: bool-- draw_indexed_indirect_countbindless: bool-- Bindless tables (descriptor indexing, update after bind)subgroups: bool-- subgroup operations (basic, vote, ballot, arithmetic, shuffle) in compute shaderssubgroups_webgpu: bool-- what WebGPU'ssubgroupsfeature needs (lib/wgsl'senable subgroups): the operations ofsubgroupsplus relative shuffles and quad operations, in compute and fragment shaderssubgroup_stages: u32-- the stages with subgroup operations (subgroup_stage::*) and the operations (subgroup_op::*), as the device reports themsubgroup_ops: u32subgroup_size_control: bool-- Device::create_compute_pipeline_sized: a required subgroup size (WGSL @subgroup_size; Limits::subgroup_min_size ..= subgroup_max_size)subgroup_extended_types: bool-- subgroup operations on f16 values toodraw_parameters: bool-- the base vertex / base instance / draw index builtinsshader_f16: boolshader_f64: boolshader_i16: boolshader_i64: boolshader_i8: boolstorage_16bit: bool-- 16 / 8 bit values in storage buffersuniform_16bit: bool-- 16-bit values in uniform buffers and push constants too (WGSL f16 there)push_constant_16bit: booluniform_standard_layout: bool-- uniform buffers in the storage layout (uniformBufferStandardLayout: a WGSL uniform buffer whose layout is not std140, e.g. mat2x2f)demote: bool-- OpDemoteToHelperInvocation (lib/wgsl's discard at the level Voll)clip_distances: bool-- WGSL @builtin(clip_distances), @builtin(primitive_index) (geometryShader), @interpolate(.., sample) / @builtin(sample_index) (sampleRateShading)primitive_index: boolsample_shading: boolstorage_8bit: booltexture_bc: bool-- BC1 .. BC7 compressed texturesanisotropy: booldepth_clamp: boolvertex_stores: bool-- storage writes in vertex / fragment shadersfragment_stores: boolstorage_write_without_format: bool-- storage textures without a format in the shaderbuffer_address: bool-- shader access to buffers by addressswapchain: bool-- presentation to windows (Swapchain)mesh_shader: bool-- present on the adapter, not enabled yet: mesh shaders, ray queries, ray-tracing pipelinesray_query: boolray_pipeline: bool
struct Limitsthe device's limitsmax_texture_2d: u32max_texture_3d: u32max_texture_layers: u32max_storage_binding: u32-- the largest range of a storage / uniform buffer binding (bytes)max_uniform_binding: u32max_push_constants: u32-- push-constant bytes of the device (the API allows PUSH_CONSTANTS_MAX)max_bind_groups: u32max_compute_workgroup_size: [u32; 3]max_compute_invocations: u32max_compute_workgroups: [u32; 3]max_compute_shared_memory: u32min_uniform_offset_alignment: u32min_storage_offset_alignment: u32max_color_targets: u32max_vertex_buffers: u32max_vertex_attributes: u32max_draw_indirect_count: u32max_anisotropy: f32timestamp_period_ns: f32-- nanoseconds per timestamp ticksubgroup_size: u32-- threads per subgroup (0: unknown)subgroup_min_size: u32-- the subgroup sizes shaders can get (without size control: subgroup_size twice)subgroup_max_size: u32max_bindless_textures: u32-- the most slots of a Bindless table (Voll; 0 on Basis)max_bindless_samplers: u32max_bindless_buffers: u32max_bindless_storage_textures: u32device_memory: u64-- bytes of the device-local memory heaps
struct InstanceDesc<'a>Instance::withapp_name: &'a str-- the application's name for the drivervalidate: bool-- the validation layer (as jfgui_GPU_VALIDATE=1)
impl InstanceDesc<'_>
const DEFAULT: InstanceDesc<'static> = InstanceDesc { app_name: "jfgui", validate: false }struct DeviceDescAdapter::create_devicemax_level: Level-- the highest level to enable (the device gets the highest it supports up to this one)
impl DeviceDesc
const DEFAULT: DeviceDesc = DeviceDesc { max_level: Level::Voll }struct DeviceOptions(G5d) what Adapter::create_device_with sets up beyond DeviceDesc; DEFAULT is what create_device does. Fields may come in later versions: start from DEFAULTcompute_queue: bool-- a queue of its own for compute and copies (Device::compute_queue): Vulkan, where the device has a family without graphics. Then every buffer and every texture that is no render target is shared by both queues' families (concurrently), which some GPUs may pay for; off by default, and jfgui_GPU_COMPUTE=0 turns it off
impl DeviceOptions
const DEFAULT: DeviceOptions = DeviceOptions { compute_queue: false }const fn with_compute_queue(self) -> DeviceOptionsthese options with a compute queue asked forstruct SubmitId(pub u64)a submission's place on the device timeline (Device::wait)enum MemoryKindwhere a buffer's memory livesDevice-- GPU memory (fastest for the GPU; filled by copies or Queue::write_buffer)Upload-- CPU memory the GPU reads (staging, per-frame data; Buffer::write)Readback-- CPU memory the GPU writes (results; Buffer::read)
struct BufferDescDevice::create_buffersize: u64usage: BufferUsagememory: MemoryKind
enum Formattexel formatsR8UnormRg8UnormRgba8UnormRgba8SrgbBgra8UnormBgra8SrgbRgb10a2UnormRg11b10FloatR16FloatRg16FloatRgba16FloatR32UintR32SintR32FloatRg32UintRg32FloatRgba32UintRgba32FloatDepth16Depth32FloatDepth24Stencil8Depth32FloatStencil8Bc1UnormBc1SrgbBc3UnormBc3SrgbBc4UnormBc5UnormBc7UnormBc7Srgb
impl Format
const fn block_bytes(self) -> u32bytes per texel block (a texel, or a 4 x 4 block of a compressed format)const fn block_dim(self) -> u32the block's width and height in texels (4 for compressed formats, else 1)const fn is_compressed(self) -> boolconst fn is_depth(self) -> boolconst fn has_stencil(self) -> boolconst fn is_srgb(self) -> boolstruct TextureDescDevice::create_texture: a 2D texture (layers > 1: an array; cube: 6 * n layers) or a 3D one (depth > 1)width: u32height: u32depth: u32-- 1 for 2D textureslayers: u32-- 1 for a single texturemips: u32-- mip levels (1 = none)format: Formatusage: TextureUsagecube: bool-- cube faces: layers is a multiple of 6
impl TextureDesc
const fn d2(width: u32, height: u32, format: Format, usage: TextureUsage) -> TextureDesca single-level 2D textureenum ViewDima view's dimensionD2D2ArrayCubeCubeArrayD3
struct ViewDescTexture::create_view: a range of mips and layers (counts 0 = to the end)dim: ViewDimbase_mip: u32mips: u32base_layer: u32layers: u32
enum Layoutthe state a texture is in (texture_barrier, render pass attachments, write_texture)Undefined-- contents discarded; waits for earlier colour, copy and compute work (and for the swapchain image's acquisition)General-- storage textures and anything at once (slower on some GPUs)CopySrcCopyDstSampled-- sampled in shaders (also depth textures)ColorTargetDepthTargetDepthRead-- depth test without writes while shaders sample itPresent-- handed to the window (the last layout of a swapchain image)
enum FilterNearestLinear
enum AddressModeRepeatMirrorRepeatClampToEdge
enum Comparecomparison functions (depth test, comparison samplers)NeverLessEqualLessEqualGreaterNotEqualGreaterEqualAlways
struct SamplerDescDevice::create_samplermag: Filtermin: Filtermip: Filteraddress: [AddressMode; 3]-- u, v, wanisotropy: u16-- 1 = off, up to Limits::max_anisotropy (needs Features::anisotropy)compare: Option<Compare>-- a comparison sampler (shadow maps)lod_min: f32lod_max: f32
impl SamplerDesc
const LINEAR: SamplerDesc = SamplerDesc { mag: Filter::Linear, min: Filter::Linear, m ...const NEAREST: SamplerDesc = SamplerDesc { mag: Filter::Nearest, min: Filter::Nearest, ...enum BindingKindwhat a binding holdsUniformBufferStorageBuffer-- read and written by shadersStorageBufferRead-- read only (also visible to vertex shaders without Features::vertex_stores)Texture-- a sampled texture (Layout::Sampled)StorageTexture-- a storage texture (Layout::General)Sampler
struct Bindingone binding of a BindGroupLayoutbinding: u32kind: BindingKindstages: Stages
struct PipelineLayoutDesc<'a>Device::create_pipeline_layoutgroups: &'a [&'a BindGroupLayout]-- bind group g = @group(g); at most BIND_GROUPS_MAXpush_constants: u32-- push-constant bytes (a multiple of 4, at most PUSH_CONSTANTS_MAX)
enum Resource<'a>a resource bound into a BindGroupBuffer { buffer: &'a Buffer, offset: u64, size: u64 }-- a buffer range (size 0: to the end); offsets aligned to Limits::min_*_offset_alignmentTexture(&'a TextureView)StorageTexture(&'a TextureView)Sampler(&'a Sampler)
struct BindEntry<'a>binding: u32resource: Resource<'a>
struct BindGroupDesc<'a>Device::create_bind_group: one entry per binding of the layoutlayout: &'a BindGroupLayoutentries: &'a [BindEntry<'a>]
struct BindlessDescDevice::create_bindless: the slots of each kind (bindings 0 textures, 1 samplers, 2 storage buffers, 3 storage textures of one group)textures: u32samplers: u32buffers: u32storage_textures: u32
struct Constanta pipeline-overridable constant: WGSL@id(id) override, SPIR-VSpecId id. The value is an f64 as in WebGPU'sGPUProgrammableStage.constantsand is converted to the override's type the way WebGPU converts it: bool true unless 0 or NaN; i32 / u32 (and the other integers) truncated toward 0, Invalid when not finite or out of range; f32 / f16 / f64 rounded to nearest, Invalid when not finite or out of range. An id the module does not declare, or the same id twice, is Invalid (Vulkan would ignore it; WebGPU does not). Overrides the pipeline leaves out keep the module's default.id: u32value: f64
struct ShaderStage<'a>a shader entry point and its pipeline constantsmodule: &'a ShaderModuleentry: &'a strconstants: &'a [Constant]-- pipeline-overridable constants of this stage (empty: the module's defaults)
impl<'a> ShaderStage<'a>
const fn new(module: &'a ShaderModule, entry: &'a str) -> ShaderStage<'a>an entry point without pipeline constantsstruct ComputePipelineDesc<'a>Device::create_compute_pipelinelayout: &'a PipelineLayoutshader: ShaderStage<'a>
enum TopologyPointsLinesLineStripTrianglesTriangleStrip
enum CullNoneFrontBack
enum VertexFormatvertex attribute formatsF32F32x2F32x3F32x4U32U32x2U32x4Unorm8x4-- four bytes as 0 ..= 1
struct VertexAttributelocation: u32format: VertexFormatoffset: u32
struct VertexBufferLayout<'a>a vertex buffer slot (empty list: vertex pulling)stride: u32per_instance: boolattributes: &'a [VertexAttribute]
enum BlendFactorZeroOneSrcOneMinusSrcDstOneMinusDstSrcAlphaOneMinusSrcAlphaDstAlphaOneMinusDstAlpha
enum BlendOpAddSubtractReverseSubtractMinMax
struct BlendComponentsrc: BlendFactordst: BlendFactorop: BlendOp
struct Blendcolour and alpha blending of a colour targetcolor: BlendComponentalpha: BlendComponent
impl Blend
const PREMULTIPLIED: Blend = Blend { color: BlendComponent { src: BlendFactor::One, ds ...premultiplied alpha: src + dst * (1 - src.a)const ALPHA: Blend = Blend { color: BlendComponent { src: BlendFactor::SrcAlph ...straight alpha: src * src.a + dst * (1 - src.a)const ADD: Blend = Blend { color: BlendComponent { src: BlendFactor::One, ds ...additive: src + dststruct ColorTargeta colour target of a render pipelineformat: Formatblend: Option<Blend>write_mask: u32-- bits 0..3 = r, g, b, a (0xF: all)
struct DepthStatethe depth test of a render pipelineformat: Formatwrite: boolcompare: Compare
struct RenderPipelineDesc<'a>Device::create_render_pipelinelayout: &'a PipelineLayoutvertex: ShaderStage<'a>fragment: Option<ShaderStage<'a>>buffers: &'a [VertexBufferLayout<'a>]-- vertex buffer slots (empty: the vertex shader pulls its data)topology: Topologycull: Cullfront_cw: bool-- front faces are clockwise (default counter-clockwise)targets: &'a [ColorTarget]depth: Option<DepthState>
enum Loadwhat a render pass does with an attachment's old contentsKeepClearDiscard
struct ColorAttachment<'a>a colour attachment of a render pass: the view goes frombeforeto ColorTarget at the start and toafterat the endview: &'a TextureViewload: Loadclear: [f32; 4]store: boolbefore: Layoutafter: Layout
struct DepthAttachment<'a>the depth attachment of a render pass (DepthTarget during the pass)view: &'a TextureViewload: Loadclear: f32store: boolbefore: Layoutafter: Layout
struct RenderPassDesc<'d, 'a>CommandEncoder::begin_render (the slice may be a temporary: only the views are borrowed for the encoder's lifetime)color: &'d [ColorAttachment<'a>]depth: Option<DepthAttachment<'a>>
enum IndexFormatU16U32
struct TextureRegion<'a>a region of one mip of a texture: origin and size in texels (z: 3D textures), layerstexture: &'a Texturemip: u32origin: [u32; 3]size: [u32; 3]base_layer: u32layers: u32
impl<'a> TextureRegion<'a>
fn mip(texture: &'a Texture, mip: u32) -> TextureRegion<'a>all of mipmipand every layerstruct DataLayoutthe layout of texel data in a buffer or slice: rows of bytes_per_row bytes (0: tightly packed), rows_per_image rows per layer / slice (0: the region's height)offset: u64bytes_per_row: u32rows_per_image: u32
enum PresentModehow frames reach the windowFifo-- vsync: one image per refresh, never tears (always available)Mailbox-- the newest image at the refresh, older ones dropped (no tearing, low latency)Immediate-- at once (tears; for measurements)
struct SwapchainDescDevice::create_swapchainpresent: PresentModesrgb: bool-- an sRGB format (the GPU encodes gamma on writes)copy_src: bool-- the images may be copied from (read-back of the presented image)frames_in_flight: u32-- frames the CPU may record ahead of the GPU (1 ..= 3)min_images: u32-- images of the swapchain at least (0: the surface's minimum + 1)
impl SwapchainDesc
const DEFAULT: SwapchainDesc = SwapchainDesc { present: PresentMode::Fifo, srgb: false, ...
mod subgroup_stage
the bits of Features::subgroup_stages
COMPUTE: u32 = 1
FRAGMENT: u32 = 2
VERTEX: u32 = 4
mod subgroup_op
the bits of Features::subgroup_ops (the Vulkan feature bits)
BASIC: u32 = 1
VOTE: u32 = 2
ARITHMETIC: u32 = 4
BALLOT: u32 = 8
SHUFFLE: u32 = 0x10
SHUFFLE_RELATIVE: u32 = 0x20
CLUSTERED: u32 = 0x40
QUAD: u32 = 0x80