Skip to main content

wgpu/macros/
mod.rs

1//! Convenience macros
2#![cfg_attr(not(wgpu_core), expect(unused_macros, unused_imports))]
3
4#[cfg(doc)]
5use crate::{VertexAttribute, VertexBufferLayout, VertexFormat};
6
7/// Macro to produce an array of [`VertexAttribute`].
8///
9/// The input is a sequence of pairs of shader locations (expression of type [`u32`]) and
10/// variant names of [`VertexFormat`].
11///
12/// The return value has type `[VertexAttribute; N]`, where `N` is the number of inputs.
13///
14/// Offsets are calculated automatically,
15/// using the assumption that there is no padding or other data between attributes.
16///
17/// # Example
18///
19/// ```
20/// // Suppose that this is our vertex format:
21/// #[repr(C, packed)]
22/// struct Vertex {
23///     foo: [f32; 2],
24///     bar: f32,
25///     baz: [u16; 4],
26/// }
27///
28/// // Then these attributes match it:
29/// let attrs = wgpu::vertex_attr_array![
30///     0 => Float32x2,
31///     1 => Float32,
32///     2 => Uint16x4,
33/// ];
34///
35/// // Here's the full data structure the macro produced:
36/// use wgpu::{VertexAttribute as A, VertexFormat as F};
37/// assert_eq!(attrs, [
38///     A { format: F::Float32x2, offset:  0, shader_location: 0, },
39///     A { format: F::Float32,   offset:  8, shader_location: 1, },
40///     A { format: F::Uint16x4,  offset: 12, shader_location: 2, },
41/// ]);
42/// ```
43///
44/// See [`VertexBufferLayout`] for an example building on this one.
45#[macro_export]
46macro_rules! vertex_attr_array {
47    ($($location:expr => $format:ident),* $(,)?) => {
48        $crate::_vertex_attr_array_helper!([] ; 0; $($location => $format ,)*)
49    };
50}
51
52#[doc(hidden)]
53#[macro_export]
54macro_rules! _vertex_attr_array_helper {
55    ([$($t:expr,)*] ; $off:expr ;) => { [$($t,)*] };
56    ([$($t:expr,)*] ; $off:expr ; $location:expr => $format:ident, $($ll:expr => $ii:ident ,)*) => {
57        $crate::_vertex_attr_array_helper!(
58            [$($t,)*
59            $crate::VertexAttribute {
60                format: $crate::VertexFormat :: $format,
61                offset: $off,
62                shader_location: $location,
63            },];
64            $off + $crate::VertexFormat :: $format.size();
65            $($ll => $ii ,)*
66        )
67    };
68}
69
70#[macro_export]
71#[doc(hidden)]
72macro_rules! include_spirv_source {
73    ($($token:tt)*) => {
74        {
75            const SPIRV_SOURCE: [
76                u8;
77                $crate::__macro_helpers::include_bytes!($($token)*).len()
78            ] = *$crate::__macro_helpers::include_bytes!($($token)*);
79            const SPIRV_LEN: usize = SPIRV_SOURCE.len() / 4;
80            const SPIRV_WORDS: [u32; SPIRV_LEN] = $crate::util::make_spirv_const(SPIRV_SOURCE);
81            &SPIRV_WORDS
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    #[test]
89    fn test_vertex_attr_array() {
90        let attrs = vertex_attr_array![0 => Float32x2, 3 => Uint16x4];
91        // VertexAttribute does not support PartialEq, so we cannot test directly
92        assert_eq!(attrs.len(), 2);
93        assert_eq!(attrs[0].offset, 0);
94        assert_eq!(attrs[0].shader_location, 0);
95        assert_eq!(attrs[1].offset, size_of::<(f32, f32)>() as u64);
96        assert_eq!(attrs[1].shader_location, 3);
97    }
98
99    #[test]
100    fn make_spirv_le_pass() {
101        static SPIRV: &[u32] = include_spirv_source!("le-aligned.spv");
102        assert_eq!(SPIRV, &[0x07230203, 0x11223344]);
103    }
104
105    #[test]
106    fn make_spirv_be_pass() {
107        static SPIRV: &[u32] = include_spirv_source!("be-aligned.spv");
108        assert_eq!(SPIRV, &[0x07230203, 0x11223344]);
109    }
110}
111
112/// Macro to load a SPIR-V module statically.
113///
114/// It ensures the word alignment as well as the magic number.
115///
116/// Return type: [`crate::ShaderModuleDescriptor`]
117#[macro_export]
118#[cfg(feature = "spirv")]
119macro_rules! include_spirv {
120    ($($token:tt)*) => {
121        {
122            $crate::ShaderModuleDescriptor {
123                label: Some($($token)*),
124                source: $crate::ShaderSource::SpirV(
125                    $crate::__macro_helpers::Cow::Borrowed($crate::include_spirv_source!($($token)*))
126                ),
127            }
128        }
129    };
130}
131
132#[cfg(all(feature = "spirv", test))]
133#[expect(dead_code)]
134static SPIRV: crate::ShaderModuleDescriptor<'_> = include_spirv!("le-aligned.spv");
135
136/// Macro to load raw SPIR-V data statically, for use with [`Features::PASSTHROUGH_SHADERS`].
137///
138/// It ensures the word alignment as well as the magic number.
139///
140/// [`Features::PASSTHROUGH_SHADERS`]: crate::Features::PASSTHROUGH_SHADERS
141#[macro_export]
142macro_rules! include_spirv_raw {
143    ($($token:tt)*) => {
144        {
145            $crate::ShaderModuleDescriptorPassthrough {
146                label: $crate::__macro_helpers::Some($($token)*),
147                spirv: Some($crate::__macro_helpers::Cow::Borrowed($crate::include_spirv_source!($($token)*))),
148                entry_points: $crate::__macro_helpers::Cow::Borrowed(&[$crate::PassthroughShaderEntryPoint {
149                    name: $crate::__macro_helpers::Cow::Borrowed("main"),
150                    // This is unused for SPIR-V
151                    workgroup_size: (0, 0, 0),
152                }]),
153                dxil: None,
154                metallib: None,
155                msl: None,
156                hlsl: None,
157                glsl: None,
158                wgsl: None,
159            }
160        }
161    };
162}
163
164#[cfg(test)]
165#[expect(dead_code)]
166static SPIRV_RAW: crate::ShaderModuleDescriptorPassthrough<'_> =
167    include_spirv_raw!("le-aligned.spv");
168
169/// Load WGSL source code from a file at compile time.
170///
171/// The loaded path is relative to the path of the file containing the macro call, in the same way
172/// as [`include_str!`] operates.
173///
174/// ```ignore
175/// fn main() {
176///     let module: ShaderModuleDescriptor = include_wgsl!("shader.wgsl");
177/// }
178/// ```
179#[macro_export]
180macro_rules! include_wgsl {
181    ($($token:tt)*) => {
182        {
183            $crate::ShaderModuleDescriptor {
184                label: $crate::__macro_helpers::Some($($token)*),
185                source: $crate::ShaderSource::Wgsl($crate::__macro_helpers::Cow::Borrowed($crate::__macro_helpers::include_str!($($token)*))),
186            }
187        }
188    };
189}
190
191// Macros which help us generate the documentation of which hal types correspond to which backend.
192//
193// Because all backends are not compiled into the program, we cannot link to them in all situations,
194// we need to only link to the types if the backend is compiled in. These are used in #[doc] attributes
195// so cannot have more than one line, so cannot use internal cfgs.
196
197/// Helper macro to generate the documentation for dx12 hal methods, referencing the hal type.
198#[cfg(dx12)]
199macro_rules! hal_type_dx12 {
200    ($ty: literal) => {
201        concat!("- [`hal::api::Dx12`] uses [`hal::dx12::", $ty, "`]")
202    };
203}
204/// Helper macro to generate the documentation for dx12 hal methods, referencing the hal type.
205#[cfg(not(dx12))]
206macro_rules! hal_type_dx12 {
207    ($ty: literal) => {
208        concat!("- `hal::api::Dx12` uses `hal::dx12::", $ty, "`")
209    };
210}
211pub(crate) use hal_type_dx12;
212
213/// Helper macro to generate the documentation for metal hal methods, referencing the hal type.
214#[cfg(metal)]
215macro_rules! hal_type_metal {
216    ($ty: literal) => {
217        concat!("- [`hal::api::Metal`] uses [`hal::metal::", $ty, "`]")
218    };
219}
220/// Helper macro to generate the documentation for metal hal methods, referencing the hal type.
221#[cfg(not(metal))]
222macro_rules! hal_type_metal {
223    ($ty: literal) => {
224        concat!("- `hal::api::Metal` uses `hal::metal::", $ty, "`")
225    };
226}
227pub(crate) use hal_type_metal;
228
229/// Helper macro to generate the documentation for vulkan hal methods, referencing the hal type.
230#[cfg(vulkan)]
231macro_rules! hal_type_vulkan {
232    ($ty: literal) => {
233        concat!("- [`hal::api::Vulkan`] uses [`hal::vulkan::", $ty, "`]")
234    };
235}
236/// Helper macro to generate the documentation for vulkan hal methods, referencing the hal type.
237#[cfg(not(vulkan))]
238macro_rules! hal_type_vulkan {
239    ($ty: literal) => {
240        concat!("- `hal::api::Vulkan` uses `hal::vulkan::", $ty, "`")
241    };
242}
243pub(crate) use hal_type_vulkan;
244
245/// Helper macro to generate the documentation for gles hal methods, referencing the hal type.
246#[cfg(gles)]
247macro_rules! hal_type_gles {
248    ($ty: literal) => {
249        concat!("- [`hal::api::Gles`] uses [`hal::gles::", $ty, "`]")
250    };
251}
252/// Helper macro to generate the documentation for gles hal methods, referencing the hal type.
253#[cfg(not(gles))]
254macro_rules! hal_type_gles {
255    ($ty: literal) => {
256        concat!("- `hal::api::Gles` uses `hal::gles::", $ty, "`")
257    };
258}
259pub(crate) use hal_type_gles;
260
261// Reference an image from the crate's `src/documentation/images/` directory. Put
262// the expansion in a `#[doc]` attribute and reference the image by file name
263// elsewhere in the same docs:
264//
265//     #![doc = crate::macros::doc_image!("foo.png")]
266//     //! ![alt text][foo.png]
267//
268// Local builds resolve the image from the on-disk `src/documentation/images/`
269// directory (which, because it lives inside the crate, is also present when a
270// downstream user builds `wgpu`'s docs as a dependency); `docsrs` builds resolve
271// it from the repository over HTTP, pinned to the commit being built. Both base
272// URLs are set in `build.rs`. The expansion must be a single line, as it is used
273// in a `#[doc]` attribute.
274//
275// Place these attributes *before* the module's doc comment, as shown above.
276// rustdoc strips trailing blank lines from each doc fragment and joins the
277// fragments with a single newline, so a definition placed after a doc comment
278// that ends in a paragraph is swallowed by that paragraph as a lazy
279// continuation, and every image reference in the module silently fails to
280// resolve.
281
282/// Expands to a Markdown reference-style link definition for a `src/documentation/images/` image.
283#[cfg(docsrs)]
284macro_rules! doc_image {
285    ($name:literal) => {
286        concat!(
287            "[",
288            $name,
289            "]: https://raw.githubusercontent.com/gfx-rs/wgpu/",
290            env!("WGPU_DOCS_COMMIT"),
291            "/wgpu/src/documentation/images/",
292            $name
293        )
294    };
295}
296/// Expands to a Markdown reference-style link definition for a `src/documentation/images/` image.
297#[cfg(not(docsrs))]
298macro_rules! doc_image {
299    ($name:literal) => {
300        concat!("[", $name, "]: ", env!("WGPU_DOCS_URL_BASE"), "/", $name)
301    };
302}
303pub(crate) use doc_image;
304
305#[doc(hidden)]
306pub mod helpers {
307    pub use alloc::{borrow::Cow, string::String};
308    pub use core::{include_bytes, include_str};
309    pub use Some;
310}