Convert Figma logo to code with AI

gfx-rs logowgpu

A cross-platform, safe, pure-Rust graphics API.

12,131
884
12,131
827

Top Related Projects

5,351

[maintenance mode] A low-overhead Vulkan-like GPU API for Rust.

4,471

Safe and rich Rust wrapper around the Vulkan API

1,799

Vulkan bindings for Rust

35,058

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

  1. 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();
}
  1. 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,
});
  1. 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

5,351

[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.

4,471

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.

1,799

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.

35,058

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 Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

wgpu

Matrix Space Dev Matrix  User Matrix Build Status codecov.io

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. It serves as the core of the WebGPU integration in Firefox and Deno.

Repo Overview

The repository hosts the following libraries:

  • Crates.io docs.rs - User facing Rust API.
  • Crates.io docs.rs - Internal safe implementation.
  • Crates.io docs.rs - Internal unsafe GPU API abstraction layer.
  • Crates.io docs.rs - Rust types shared between all crates.
  • Crates.io docs.rs - Stand-alone shader translation library.
  • Crates.io docs.rs - Collection of thin abstractions over d3d12.
  • Crates.io - WebGPU implementation for the Deno JavaScript/TypeScript runtime

The following binaries:

  • Crates.io - Tool for translating shaders between different languages using naga.
  • Crates.io - Tool for getting information on GPUs in the system.
  • cts_runner - WebGPU Conformance Test Suite runner using deno_webgpu.
  • player - standalone application for replaying the API traces.

For an overview of all the components in the gfx-rs ecosystem, see the big picture.

Getting Started

Rust

Rust examples can be found at wgpu/examples. You can run the examples on native with cargo run --bin wgpu-examples <example>. See the list of examples.

To run the examples in a browser, run cargo xtask run-wasm. Then open http://localhost:8000 in your browser, and you can choose an example to run. Naturally, in order to display any of the WebGPU based examples, you need to make sure your browser supports it.

If you are looking for a wgpu tutorial, look at the following:

C/C++

To use wgpu in C/C++, you need wgpu-native.

If you are looking for a wgpu C++ tutorial, look at the following:

Others

If you want to use wgpu in other languages, there are many bindings to wgpu-native from languages such as Python, D, Julia, Kotlin, and more. See the list.

Community

We have the Matrix space Matrix Space with a few different rooms that form the wgpu community:

  • Wgpu Matrix - discussion of the wgpu's development.
  • Naga Matrix - discussion of the naga's development.
  • User Matrix - discussion of using the library and the surrounding ecosystem.
  • Random Matrix - discussion of everything else.

Wiki

We have a wiki that serves as a knowledge base.

Supported Platforms

APIWindowsLinux/AndroidmacOS/iOSWeb (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

Shader Support

wgpu supports shaders in WGSL, SPIR-V, and GLSL. Both HLSL and GLSL have compilers to target SPIR-V. All of these shader languages can be used with any backend as we handle all of the conversions. Additionally, support for these shader inputs is not going away.

While WebGPU does not support any shading language other than WGSL, we will automatically convert your non-WGSL shaders if you're running on WebGPU.

WGSL is always supported by default, but GLSL and SPIR-V need features enabled to compile in support.

Note that the WGSL specification is still under development, so the draft specification does not exactly describe what wgpu supports. See below for details.

To enable SPIR-V shaders, enable the spirv feature of wgpu. To enable GLSL shaders, enable the glsl feature of wgpu.

Angle

Angle is a translation layer from GLES to other backends developed by Google. We support running our GLES3 backend over it in order to reach platforms DX11 support, which aren't accessible otherwise. In order to run with Angle, the "angle" feature has to be enabled, and Angle libraries placed in a location visible to the application. These binaries can be downloaded from gfbuild-angle artifacts, manual compilation may be required on Macs with Apple silicon.

On Windows, you generally need to copy them into the working directory, in the same directory as the executable, or somewhere in your path. On Linux, you can point to them using LD_LIBRARY_PATH environment.

MSRV policy

Due to complex dependants, we have two MSRV policies:

  • d3d12, naga, wgpu-core, wgpu-hal, and wgpu-types's MSRV is 1.76, but may be lower than the rest of the workspace in the future.
  • The rest of the workspace has an MSRV of 1.76 as well right now, but may be higher than above listed crates.

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.

Environment Variables

All testing and example infrastructure share the same set of environment variables that determine which Backend/GPU it will run on.

  • WGPU_ADAPTER_NAME with a substring of the name of the adapter you want to use (ex. 1080 will match NVIDIA GeForce 1080ti).
  • WGPU_BACKEND with a comma-separated list of the backends you want to use (vulkan, metal, dx12, or gl).
  • WGPU_POWER_PREF with the power preference to choose when a specific adapter name isn't specified (high, low or none)
  • WGPU_DX12_COMPILER with the DX12 shader compiler you wish to use (dxc or fxc, note that dxc requires dxil.dll and dxcompiler.dll to be in the working directory otherwise it will fall back to fxc)
  • WGPU_GLES_MINOR_VERSION with the minor OpenGL ES 3 version number to request (0, 1, 2 or automatic).
  • WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER with a boolean whether non-compliant drivers are enumerated (0 for false, 1 for true).

When running the CTS, use the variables DENO_WEBGPU_ADAPTER_NAME, DENO_WEBGPU_BACKEND, DENO_WEBGPU_POWER_PREFERENCE.

Testing

We have multiple methods of testing, each of which tests different qualities about wgpu. We automatically run our tests on CI. The current state of CI testing:

Platform/BackendTestsNotes
Windows/DX12:heavy_check_mark:using WARP
Windows/OpenGL:heavy_check_mark:using llvmpipe
MacOS/Metal:heavy_check_mark:using hardware runner
Linux/Vulkan:heavy_check_mark:using lavapipe
Linux/OpenGL ES:heavy_check_mark:using llvmpipe
Chrome/WebGL:heavy_check_mark:using swiftshader
Chrome/WebGPU:x:not set up

Core Test Infrastructure

We use a tool called cargo nextest to run our tests. To install it, run cargo install cargo-nextest.

To run the test suite:

cargo xtask test

To run the test suite on WebGL (currently incomplete):

cd wgpu
wasm-pack test --headless --chrome --no-default-features --features webgl --workspace

This will automatically run the tests using a packaged browser. Remove --headless to run the tests with whatever browser you wish at http://localhost:8000.

If you are a user and want a way to help contribute to wgpu, we always need more help writing test cases.

WebGPU Conformance Test Suite

WebGPU includes a Conformance Test Suite to validate that implementations are working correctly. We can run this CTS against wgpu.

To run the CTS, first, you need to check it out:

git clone https://github.com/gpuweb/cts.git
cd cts
# works in bash and powershell
git checkout $(cat ../cts_runner/revision.txt)

To run a given set of tests:

# Must be inside the `cts` folder we just checked out, else this will fail
cargo run --manifest-path ../Cargo.toml -p cts_runner --bin cts_runner -- ./tools/run_deno --verbose "<test string>"

To find the full list of tests, go to the online cts viewer.

The list of currently enabled CTS tests can be found here.

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, wgpu uses the Naga crate to translate WGSL code into the shading language of your platform's native GPU API. Naga has a milestone for catching up to the WGSL specification, but in general, there is no up-to-date summary of the differences between Naga and the WGSL spec.

  • When running in a web browser (by compilation to WebAssembly) without the "webgl" feature enabled, wgpu relies 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, wgpu uses Naga to translate WGSL programs into GLSL. This uses the same version of Naga as if you were running wgpu as native code.

Coordinate Systems

wgpu uses the coordinate systems of D3D and Metal:

RenderTexture
render_coordinatestexture_coordinates