Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ptr!

Declares a WGSL pointer parameter. Used in function signatures where the function needs to read or write a variable in a specific address space.

Syntax

#![allow(unused)]
fn main() {
fn name(p: ptr!(address_space, Type)) { ... }
}

address_space is one of function, private, or workgroup.

What It Generates

Rust:

#![allow(unused)]
fn main() {
fn name(p: &mut Type) { ... }
}

WGSL:

fn name(p: ptr<address_space, Type>) { ... }

Dereference

Read or write through the pointer with *p:

#![allow(unused)]
fn main() {
pub fn increment(p: ptr!(function, f32)) {
    *p += 1.0;
}
}
fn increment(p: ptr<function, f32>) {
  *p += 1.0;
}

Example: Swap

#![allow(unused)]
fn main() {
#[wgsl]
pub mod utils {
    use wgsl_rs::std::*;

    pub fn swap(a: ptr!(function, f32), b: ptr!(function, f32)) {
        let t = *a;
        *a = *b;
        *b = t;
    }

    pub fn sort_pair(mut x: f32, mut y: f32) -> Vec2f {
        if x > y {
            swap(&mut x, &mut y);
        }
        vec2f(x, y)
    }
}
}

Notes

  • Use &mut at the call site in Rust; the macro translates this to a WGSL pointer of the declared address space.
  • function is the most common address space for local variables. Use workgroup for pointers to workgroup! variables and private for module-private variables.