Top Related Projects
🐉 Making Rust a first-class language and ecosystem for GPU shaders 🚧
[maintenance mode] A low-overhead Vulkan-like GPU API for Rust.
Safe and rich Rust wrapper around the Vulkan API
Vulkan bindings for Rust
A refreshingly simple data-driven game engine built in Rust
Quick Overview
wgpu is a cross-platform, safe, and portable graphics API for Rust. It provides a modern, efficient abstraction layer over various graphics backends, including Vulkan, Metal, D3D12, and WebGPU, allowing developers to write high-performance graphics code that runs on multiple platforms.
Pros
- Cross-platform compatibility (Windows, macOS, Linux, Web)
- Safe and ergonomic Rust API
- Supports modern graphics features and performance optimizations
- Active development and community support
Cons
- Learning curve for developers new to graphics programming
- May have slightly higher overhead compared to using native APIs directly
- Documentation can be sparse in some areas
- Still evolving, which may lead to breaking changes in future versions
Code Examples
- Initializing a wgpu instance and adapter:
use wgpu;
async fn init() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions::default()).await.unwrap();
let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor::default(), None).await.unwrap();
}
- Creating a render pipeline:
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[Some(wgpu::ColorTargetState {
format: surface_config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
});
- Rendering a frame:
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: true,
},
})],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&render_pipeline);
render_pass.draw(0..3, 0..1);
}
queue.submit(std::iter::once(encoder.finish()));
Getting Started
To get started with wgpu, add it to your Cargo.toml:
[dependencies]
wgpu = "0.15"
Then, in your Rust code, import and use wgpu:
use wgpu;
async fn run() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
Competitor Comparisons
🐉 Making Rust a first-class language and ecosystem for GPU shaders 🚧
Pros of rust-gpu
- Allows writing GPU shaders directly in Rust, providing better type safety and ergonomics
- Enables sharing code between CPU and GPU, potentially reducing duplication
- Leverages Rust's powerful macro system for shader-specific optimizations
Cons of rust-gpu
- More experimental and less mature compared to wgpu
- Limited support for certain GPU features and platforms
- Steeper learning curve for developers not familiar with GPU programming concepts
Code Comparison
rust-gpu shader example:
#[spirv(fragment)]
pub fn main(
#[spirv(frag_coord)] frag_coord: Vec4,
output: &mut Vec4
) {
*output = vec4(1.0, 0.0, 0.0, 1.0);
}
wgpu shader example (WGSL):
@fragment
fn main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}
Both examples demonstrate a simple fragment shader that outputs a solid red color. The rust-gpu version uses Rust syntax with SPIR-V attributes, while the wgpu version uses WGSL, WebGPU's shader language.
[maintenance mode] A low-overhead Vulkan-like GPU API for Rust.
Pros of gfx
- More flexible and lower-level API, allowing for greater control over graphics operations
- Supports a wider range of graphics backends, including OpenGL and Metal
- Potentially better performance for specialized use cases
Cons of gfx
- Steeper learning curve due to its lower-level nature
- Less standardized API, which can lead to more complex code
- Requires more boilerplate code for common operations
Code Comparison
gfx:
let mut encoder: gfx::Encoder<_, _> = factory.create_command_buffer().into();
encoder.clear(&data.out, [0.1, 0.2, 0.3, 1.0]);
encoder.draw(&slice, &pso, &data);
encoder.flush(&mut device);
wgpu:
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
{
let _render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { /* ... */ });
}
queue.submit(std::iter::once(encoder.finish()));
The gfx code is more verbose and requires explicit management of the encoder, while wgpu provides a more streamlined API with implicit handling of command buffers.
Safe and rich Rust wrapper around the Vulkan API
Pros of Vulkano
- Direct Vulkan API access, offering more low-level control
- Comprehensive Vulkan feature support
- Stronger type safety and compile-time checks
Cons of Vulkano
- Steeper learning curve due to Vulkan complexity
- Less cross-platform compatibility (Vulkan-specific)
- Potentially more verbose code for simple operations
Code Comparison
Vulkano example:
let instance = Instance::new(None, &InstanceExtensions::none(), None)
.expect("failed to create instance");
let physical = PhysicalDevice::enumerate(&instance).next()
.expect("no device available");
let queue_family = physical.queue_families()
.find(|&q| q.supports_graphics())
.expect("couldn't find a graphical queue family");
WGPU example:
let instance = wgpu::Instance::new(wgpu::Backends::all());
let adapter = instance.request_adapter(
&wgpu::RequestAdapterOptions::default()
).await.unwrap();
let (device, queue) = adapter.request_device(
&wgpu::DeviceDescriptor::default(),
None
).await.unwrap();
WGPU provides a more abstracted and simplified API, while Vulkano offers more direct control over Vulkan features. WGPU is designed for cross-platform compatibility and ease of use, whereas Vulkano focuses on providing a comprehensive Rust interface to Vulkan.
Vulkan bindings for Rust
Pros of ash
- Lower-level API, providing more direct control over Vulkan
- Potentially better performance for specialized use cases
- Closer to native Vulkan, easier for developers familiar with the API
Cons of ash
- Steeper learning curve, requires more Vulkan knowledge
- Less abstraction, leading to more verbose code
- Fewer built-in safety features compared to wgpu
Code Comparison
ash example:
let instance = ash::Instance::new(&create_info, None)?;
let physical_device = instance.enumerate_physical_devices()?.pop().unwrap();
let device = instance.create_device(physical_device, &device_create_info, None)?;
wgpu example:
let instance = wgpu::Instance::new(wgpu::Backends::all());
let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions::default()).await?;
let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor::default(), None).await?;
ash provides a more direct interface to Vulkan, requiring explicit management of instances, physical devices, and logical devices. wgpu abstracts these details, offering a higher-level API that's easier to use but provides less fine-grained control. The choice between ash and wgpu depends on the specific requirements of your project and your familiarity with Vulkan.
A refreshingly simple data-driven game engine built in Rust
Pros of Bevy
- Higher-level game engine with a complete ecosystem for game development
- Entity Component System (ECS) architecture for efficient and modular game design
- Built-in asset management and scene system
Cons of Bevy
- Steeper learning curve for beginners due to its comprehensive feature set
- Less flexibility for low-level graphics programming compared to WGPU
- Potentially higher overhead for simple applications
Code Comparison
Bevy (creating a simple window):
use bevy::prelude::*;
fn main() {
App::new().add_plugins(DefaultPlugins).run();
}
WGPU (creating a simple window):
use winit::{event_loop::EventLoop, window::WindowBuilder};
fn main() {
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
// Additional WGPU setup required...
}
Bevy provides a more concise and higher-level API for window creation and management, while WGPU requires more manual setup but offers greater control over the rendering process.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
wgpu
wgpu is a cross-platform, safe, pure-Rust graphics API. It runs natively on Vulkan, Metal, D3D12, and OpenGL; and on top of WebGL2 and WebGPU on wasm.
The API is based on the WebGPU standard, but is a fully native Rust library. It serves as the core of the WebGPU integration in Firefox, Servo, and Deno.
Getting Started
See our examples online at https://wgpu.rs/examples/. You can see the Rust sources at examples and run them directly with cargo run --bin wgpu-examples <example>.
Learning wgpu
If you are new to wgpu and graphics programming, we recommend starting with Learn Wgpu.
Additionally, WebGPU Fundamentals is a tutorial for WebGPU which is very similar to our API, minus differences between Rust and Javascript.
Wiki
We have a wiki which has information on useful architecture patterns, debugging tips, and more getting started information.
Need Help? Want to Contribute?
The wgpu community uses Matrix and Discord to discuss.
- discussion of wgpu's development.
- discussion of using the library and the surrounding ecosystem.
- Dedicated support channel on the Rust Gamedev Discord.
Other Languages
To use wgpu in C or dozens of other languages, look at wgpu-native. These are C bindings to wgpu and has an up-to-date list of libraries bringing support to other languages.
Learn WebGPU (for C++) is a good resource for learning how to use wgpu-native from C++.
Quick Links
| Docs | Examples | Changelog |
|---|---|---|
| v28 | v28 | v28 |
trunk | trunk | trunk |
Contributors are welcome! See CONTRIBUTING.md for more information.
Supported Platforms
| API | Windows | Linux/Android | macOS/iOS | Web (wasm) |
|---|---|---|---|---|
| Vulkan | â | â | ð | |
| Metal | â | |||
| DX12 | â | |||
| OpenGL | ð (GL 3.3+) | ð (GL ES 3.0+) | ð | ð (WebGL2) |
| WebGPU | â |
â
= First Class Support
ð = Downlevel/Best Effort Support
ð = Requires the ANGLE translation layer (GL ES 3.0 only)
ð = Requires the MoltenVK translation layer
ð ï¸ = Unsupported, though open to contributions
Environment Variables
Testing, examples, and ::from_env() methods use a standardized set of environment variables to control wgpu's behavior.
WGPU_BACKENDwith a comma-separated list of the backends you want to use (vulkan,metal,dx12, orgl).WGPU_ADAPTER_NAMEwith a case-insensitive substring of the name of the adapter you want to use (ex.1080will matchNVIDIA GeForce 1080ti).WGPU_DX12_COMPILERwith the DX12 shader compiler you wish to use (dxc,static-dxc, orfxc). Note thatdxcrequiresdxcompiler.dll(min v1.8.2502) to be in the working directory, andstatic-dxcrequires thestatic-dxccrate feature to be enabled. Otherwise, it will fall back tofxc.
See the documentation for more environment variables.
When running the CTS, use the variables DENO_WEBGPU_ADAPTER_NAME, DENO_WEBGPU_BACKEND, DENO_WEBGPU_POWER_PREFERENCE.
Repo Overview
For an overview of all the components in the gfx-rs ecosystem, see the big picture.
MSRV policy
TL;DR: If you're using wgpu, our MSRV is 1.92.
Specific Details
Due to complex dependants, we have two MSRV policies:
naga,wgpu-core,wgpu-hal, andwgpu-types's MSRV is 1.82.- The rest of the workspace has an MSRV of 1.92.
It is enforced on CI (in "/.github/workflows/ci.yml") with the CORE_MSRV and REPO_MSRV variables.
This version can only be upgraded in breaking releases, though we release a breaking version every three months.
The naga, wgpu-core, wgpu-hal, and wgpu-types crates should never
require an MSRV ahead of Firefox's MSRV for nightly builds, as
determined by the value of MINIMUM_RUST_VERSION in
python/mozboot/mozboot/util.py.
Testing and Environment Variables
Information about testing, including where tests of various kinds live, and how to run the tests.
Tracking the WebGPU and WGSL draft specifications
The wgpu crate is meant to be an idiomatic Rust translation of the WebGPU API.
That specification, along with its shading language, WGSL,
are both still in the "Working Draft" phase,
and while the general outlines are stable,
details change frequently.
Until the specification is stabilized, the wgpu crate and the version of WGSL it implements
will likely differ from what is specified,
as the implementation catches up.
Exactly which WGSL features wgpu supports depends on how you are using it:
-
When running as native code,
wgpuuses Naga to translate WGSL code into the shading language of your platform's native GPU API. Naga is working on catching up to the WGSL specification, with bugs tracking various issues, but there is no concise summary of differences from the specification. -
When running in a web browser (by compilation to WebAssembly) without the
"webgl"feature enabled,wgpurelies on the browser's own WebGPU implementation. WGSL shaders are simply passed through to the browser, so that determines which WGSL features you can use. -
When running in a web browser with
wgpu's"webgl"feature enabled,wgpuuses Naga to translate WGSL programs into GLSL. This uses the same version of Naga as if you were runningwgpuas native code.
Top Related Projects
🐉 Making Rust a first-class language and ecosystem for GPU shaders 🚧
[maintenance mode] A low-overhead Vulkan-like GPU API for Rust.
Safe and rich Rust wrapper around the Vulkan API
Vulkan bindings for Rust
A refreshingly simple data-driven game engine built in Rust
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot