mewgpu 3.7.3-1

Maybe Easier Wgpu (mew), a thin abstraction over wgpu's chaos
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Wrapper over a
//! [`wgpu::Pipeline`](https://docs.rs/wgpu/latest/wgpu/struct.Pipeline.html).
//!
//! See [`pipeline`] for details.


use std::{
    any::TypeId,
    marker::PhantomData,
    ops::Deref,
};
use crate::wgpu;


#[cfg(all(feature = "wgpu-29", not(feature = "wgpu-30")))]
#[doc(hidden)]
#[macro_export]
macro_rules! vertices {
    ($struct:ty, $($vertexty:ty),*) => {
        use ::std::sync::LazyLock;
        static VERTICES: LazyLock<<$struct as $crate::pipeline::MewPipeline>::VertexArray<$crate::wgpu::VertexBufferLayout<'static>>> = LazyLock::new(|| {
            #[allow(unused_imports)]
            use $crate::vertexstruct::MewVertexStruct;
            [ $( <$vertexty>::vertex_layout(), )* ]
        });
    };
}

#[cfg(feature = "wgpu-30")]
#[doc(hidden)]
#[macro_export]
macro_rules! vertices {
    ($struct:ty, $($vertexty:ty),*) => {
        use ::std::sync::LazyLock;
        static VERTICES: LazyLock<<$struct as $crate::pipeline::MewPipeline>::VertexArray<Option<$crate::wgpu::VertexBufferLayout<'static>>>> = LazyLock::new(|| {
            #[allow(unused_imports)]
            use $crate::vertexstruct::MewVertexStruct;
            [ $( Some(<$vertexty>::vertex_layout()), )* ]
        });
    };
}

#[cfg(any(feature = "wgpu-29", feature = "wgpu-30"))]
pub use vertices;


/// Define a render pipeline, with internal bind group and vertex types.
///
/// `bind_group` needs to be a numbered list of [`crate::bindgroup`] types,
/// mirrored in the shader.
///
/// `vertex_types` must be another numbered list of [`crate::vertexstruct`]s.
/// These are the allowed types of vertex formats for the shader (I'm not sure
/// why you would have multiple entries but _wgpu_ allows it so whatever).
///
/// `fragment_targets` is in the format
/// <code>[wgpu::BlendState](https://docs.rs/wgpu/latest/wgpu/struct.BlendState.html) [wgpu::ColorWrites](https://docs.rs/wgpu/latest/wgpu/struct.ColorWrites.html) as `ANY`/[wgpu::TextureFormat](https://docs.rs/wgpu/latest/wgpu/enum.TextureFormat.html)</code>.
/// The [`wgpu::ColorTargetState`](https://docs.rs/wgpu/latest/wgpu/struct.ColorTargetState.html) will be `Some` if the pipeline is built with
/// the same format specified here, or if it's `ANY` then always `Some` with
/// the format it's built with - otherwise it's a `None` entry in the slice.  
/// (tbh idk what the purpose of having multiple fragment targets is but I assume
/// it's supposed be used something like this)
///
/// `immediate_size` is the length of the
/// [immediate buffer](https://docs.rs/wgpu/latest/wgpu/struct.Features.html#associatedconstant.IMMEDIATES)
/// in the [`wgpu::PipelineLayoutDescriptor`](https://docs.rs/wgpu/latest/wgpu/struct.PipelineLayoutDescriptor.html).
///
/// `depth` is a
/// <code>[wgpu::TextureFormat](https://docs.rs/wgpu/latest/wgpu/enum.TextureFormat.html)</code>
/// to use in the [`wgpu::DepthStencilState`](https://docs.rs/wgpu/latest/wgpu/struct.DepthStencilState.html).
/// Said `DepthStencilState` comes default with `depth_write_enabled = true`,
/// <code>depth_compare = [wgpu::CompareFunction::Less](https://docs.rs/wgpu/latest/wgpu/enum.CompareFunction.html#variant.Less)</code>,
/// and default `stencil` and `bias`.
///
/// `cull` is the cull face, a <code>[wgpu::Face](https://docs.rs/wgpu/latest/wgpu/enum.Face.html)</code>.
///
/// The pipeline comes with some other defaults set (like 0 mipmaps), but there
/// are quite a few things to define, so to simplify the macro I've picked out
/// the most important things. If you really need to change them, copy the
/// source of this macro into your own struct and implement [`MewPipeline`]
/// yourself ~~you lazy bastard~~.
///
///
/// ```
/// pipeline! { Pipeline {
///     bind_groups: [
///         0 => BindGroup,
///         1 => AnotherBindGroup,
///     ],
///     vertex_types: [
///         0 => Vertex,
///     ],
///     fragment_targets: [
///         0 => ALPHA_BLENDING ALL as ANY,
///     ],
///     immediate_size: 0,
///     depth: Depth32Float,  // Omit for None
///     cull: Back,  // Omit for None
/// } }
///
/// let pipeline: Pipeline = render_context.new_pipeline(wgpu::Rgba8Unorm, shader, None, None);
///
/// render_pass.set_pipeline(&pipeline);
/// ```
#[macro_export]
macro_rules! pipeline {
    { $struct:ident { $($key:tt: $val:tt),* $(,)? } } => {
        $crate::pipeline! { @collect $struct {
            bind_groups: [],
            vertex_types: [],
            fragment_targets: [],
            immediate_size: 0,
            depth: None,
            cull: None,
        }; $({$key: $val} )* }
    };

    { @texturefmt $inputfmt:ident, ANY } => {
        Some($inputfmt)
    };
    { @texturefmt $format:ident, $fragmentfmt:ident } => {
        //Some($crate::wgpu::TextureFormat::$fragmentfmt)
        if $inputfmt == $fragmentfmt {
            Some($inputfmt)
        } else {
            None
        }
    };

    { @collect $struct:ident {
            bind_groups: $_:tt,
            vertex_types: $vertextypes:tt,
            fragment_targets: $fragmenttargets:tt,
            immediate_size: $immediate:tt,
            depth: $depth:tt,
            cull: $cull:tt,
        }; {bind_groups: $bindgroups:tt} $($rest:tt)* } => {
            $crate::pipeline! { @collect $struct {
                bind_groups: $bindgroups,
                vertex_types: $vertextypes,
                fragment_targets: $fragmenttargets,
                immediate_size: $immediate,
                depth: $depth,
                cull: $cull,
            }; $($rest)* }
    };
    { @collect $struct:ident {
            bind_groups: $bindgroups:tt,
            vertex_types: $_:tt,
            fragment_targets: $fragmenttargets:tt,
            immediate_size: $immediate:tt,
            depth: $depth:tt,
            cull: $cull:tt,
        }; {vertex_types: $vertextypes:tt} $($rest:tt)* } => {
            $crate::pipeline! { @collect $struct {
                bind_groups: $bindgroups,
                vertex_types: $vertextypes,
                fragment_targets: $fragmenttargets,
                immediate_size: $immediate,
                depth: $depth,
                cull: $cull,
            }; $($rest)* }
    };
    { @collect $struct:ident {
            bind_groups: $bindgroups:tt,
            vertex_types: $vertextypes:tt,
            fragment_targets: $_:tt,
            immediate_size: $immediate:tt,
            depth: $depth:tt,
            cull: $cull:tt,
        }; {fragment_targets: $fragmenttargets:tt} $($rest:tt)* } => {
            $crate::pipeline! { @collect $struct {
                bind_groups: $bindgroups,
                vertex_types: $vertextypes,
                fragment_targets: $fragmenttargets,
                immediate_size: $immediate,
                depth: $depth,
                cull: $cull,
            }; $($rest)* }
    };
    { @collect $struct:ident {
            bind_groups: $bindgroups:tt,
            vertex_types: $vertextypes:tt,
            fragment_targets: $fragmenttargets:tt,
            immediate_size: $_:tt,
            depth: $depth:tt,
            cull: $cull:tt,
        }; {immediate_size: $immediate:tt} $($rest:tt)* } => {
            $crate::pipeline! { @collect $struct {
                bind_groups: $bindgroups,
                vertex_types: $vertextypes,
                fragment_targets: $fragmenttargets,
                immediate_size: $immediate,
                depth: $depth,
                cull: $cull,
            }; $($rest)* }
    };
    { @collect $struct:ident {
            bind_groups: $bindgroups:tt,
            vertex_types: $vertextypes:tt,
            fragment_targets: $fragmenttargets:tt,
            immediate_size: $immediate:tt,
            depth: $_:tt,
            cull: $cull:tt,
        }; {depth: $depth:tt} $($rest:tt)* } => {
            $crate::pipeline! { @collect $struct {
                bind_groups: $bindgroups,
                vertex_types: $vertextypes,
                fragment_targets: $fragmenttargets,
                immediate_size: $immediate,
                depth: (Some($depth)),
                cull: $cull,
            }; $($rest)* }
    };
    { @collect $struct:ident {
            bind_groups: $bindgroups:tt,
            vertex_types: $vertextypes:tt,
            fragment_targets: $fragmenttargets:tt,
            immediate_size: $immediate:tt,
            depth: $depth:tt,
            cull: $_:tt,
        }; {cull: $cull:tt} $($rest:tt)* } => {
            $crate::pipeline! { @collect $struct {
                bind_groups: $bindgroups,
                vertex_types: $vertextypes,
                fragment_targets: $fragmenttargets,
                immediate_size: $immediate,
                depth: $depth,
                cull: (Some($cull)),
            }; $($rest)* }
    };

    { @collect $struct:ident {
        bind_groups: [
            $( $bindgroupnum:tt => $bindgroup:ty ),* $(,)?
        ],
        vertex_types: [
            $( $vertexnum:tt => $vertexty:ty ),* $(,)?
        ],
        fragment_targets: [
            $( $fragmentnum:tt => $blend:ident $mask:ident as $fragmentfmt:ident ),* $(,)?
        ],
        immediate_size: $immediate:expr,
        depth: $depth:expr,
        cull: $cull:expr,
    }; } => {
        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub struct $struct {
            pipeline: $crate::wgpu::RenderPipeline,
        }

        impl ::std::ops::Deref for $struct {
            type Target = $crate::wgpu::RenderPipeline;
            fn deref(&self) -> &Self::Target {
                &self.pipeline
            }
        }

        impl $crate::pipeline::MewPipeline for $struct {
            type BindGroupSet = ( $( $bindgroup , )* );
            type BindGroupArray<T> = [T; $crate::len! { $( $bindgroupnum )* }];
            type VertexArray<T> = [T; $crate::len! { $( $vertexnum )* }];
            type FragmentArray<T> = [T; $crate::len! { $( $fragmentnum )* }];

            fn new(pipeline: $crate::wgpu::RenderPipeline) -> Self {
                Self {
                    pipeline,
                }
            }

            fn bind_group_layout_types_array() -> Self::BindGroupArray<(::std::any::TypeId, $crate::wgpu::BindGroupLayoutDescriptor<'static>)> {
                use $crate::bindgroup::MewBindGroup;
                [ $( (
                    ::std::any::TypeId::of::<$bindgroup>(),
                    <$bindgroup>::layout_desc(),
                ), )* ]
            }

            fn map_bind_group_array<'a, A: 'a, B: 'a, F: FnMut(&'a A) -> B>(array: &'a Self::BindGroupArray<A>, f: F) -> Self::BindGroupArray<B> {
                array.each_ref().map(f)
            }

            fn layout_desc<'a>(bind_group_layouts: &'a Self::BindGroupArray<Option<&$crate::wgpu::BindGroupLayout>>) -> $crate::wgpu::PipelineLayoutDescriptor<'a> {
                $crate::wgpu::PipelineLayoutDescriptor {
                    label: Some(concat!(stringify!($struct), " Layout Descriptor")),
                    bind_group_layouts,
                    immediate_size: $immediate,
                }
            }

            fn fragment_targets(surface_fmt: $crate::wgpu::TextureFormat) -> Self::FragmentArray<Option<$crate::wgpu::ColorTargetState>> {
                [ $( $crate::pipeline! { @texturefmt surface_fmt, $fragmentfmt }.map(|format| $crate::wgpu::ColorTargetState {
                    format,
                    blend: Some($crate::wgpu::BlendState::$blend),
                    write_mask: $crate::wgpu::ColorWrites::$mask,
                }), )* ]
            }

            fn pipeline_desc<'a>(
                layout: &'a $crate::pipeline::MewPipelineLayout<Self>,
                shader: &'a $crate::wgpu::ShaderModule,
                vertex_entry: Option<&'a str>,
                fragment_entry: Option<&'a str>,
                fragment_targets: &'a Self::FragmentArray<Option<$crate::wgpu::ColorTargetState>>,
            ) -> $crate::wgpu::RenderPipelineDescriptor<'a> {
                #[allow(unused_imports)]
                use $crate::wgpu::{
                    Face::*,
                    TextureFormat::*,
                };

                $crate::pipeline::vertices!($struct, $($vertexty),*);

                $crate::wgpu::RenderPipelineDescriptor {
                    label: Some(concat!(stringify!($struct), " Descriptor")),
                    layout: Some(layout),
                    vertex: $crate::wgpu::VertexState {
                        module: shader,
                        entry_point: vertex_entry,
                        compilation_options: Default::default(),
                        buffers: &*VERTICES,
                    },
                    fragment: Some($crate::wgpu::FragmentState {
                        module: shader,
                        entry_point: fragment_entry,
                        compilation_options: Default::default(),
                        targets: fragment_targets,
                    }),
                    primitive: $crate::wgpu::PrimitiveState {
                        topology: $crate::wgpu::PrimitiveTopology::TriangleList,
                        strip_index_format: None,
                        front_face: $crate::wgpu::FrontFace::Ccw,
                        cull_mode: $cull,
                        polygon_mode: $crate::wgpu::PolygonMode::Fill,
                        unclipped_depth: false,
                        conservative: false,
                    },
                    depth_stencil: $depth.map(|format| $crate::wgpu::DepthStencilState {
                        format,
                        depth_write_enabled: Some(true),
                        depth_compare: Some($crate::wgpu::CompareFunction::Less),
                        stencil: Default::default(),
                        bias: Default::default(),
                    }),
                    multisample: $crate::wgpu::MultisampleState {
                        count: 1,
                        mask: !0,
                        // Must be false for transparency to not dither
                        alpha_to_coverage_enabled: false,
                    },
                    multiview_mask: None,
                    cache: None,
                }
            }
        }
    };
}
pub use pipeline;


/// Trait for pipeline wrapper types, to get layouts and descriptors about the
/// inner pipeline.
///
/// The number of internal bind groups must be defined in the generic parameter,
/// because associated `const`s are "uNsTAbLe", apparently.
///
/// Ideally, avoid using this directly - it's horribly designed, so just look
/// away and use the [`pipeline`] macro.
pub trait MewPipeline {
    /// A tuple of the pipeline's internal bind groups (max of 4).
    type BindGroupSet;
    /// A generic array the length of the number of bind groups
    /// (literally `[T; N]`).
    type BindGroupArray<T>;
    /// A generic array the length of the number of vertex types
    /// (literally `[T; N]`).
    type VertexArray<T>;
    /// A generic array the length of the number of fragment targets
    /// (literally `[T; N]`).
    type FragmentArray<T>;

    /// Build this pipeline type from a
    /// [`wgpu::RenderPipeline`](https://docs.rs/wgpu/latest/wgpu/struct.RenderPipeline.html).
    fn new(pipeline: wgpu::RenderPipeline) -> Self;

    /// Get an array of the internal bind groups' type IDs &
    /// [`wgpu::BindGroupLayoutDescriptor`](https://docs.rs/wgpu/latest/wgpu/struct.BindGroupLayoutDescriptor.html)s.
    fn bind_group_layout_types_array() -> Self::BindGroupArray<(TypeId, wgpu::BindGroupLayoutDescriptor<'static>)>;
    /// Run a closure on each element in an array the lenth of the number of bind groups ([`Self::BindGroupArray`]).
    ///
    /// This is only necessary because of a limitation with Rust's generics in traits.
    /// Take a look at the above [`Self::BindGroupArray`], [`Self::VertexArray`], &
    /// [`Self::FragmentArray`] - the compiler has no way of knowing those are just
    /// supposed to be primitive `array`s with a generic `const` length. Ideally I'd
    /// just specify a `const usize` in the trait, but nooOOoo you're not allowed to
    /// do that, so I have to make do with this.
    ///
    /// Primitive `array`s also aren't distinguishable by any sort of trait to narrow down
    /// the type (really all I need is a [`std::iter::Map`]), but I don't want to import any
    /// bloat libraries & writing something is probably overkill for how I'm using it
    /// (purely internally).
    fn map_bind_group_array<'a, A: 'a, B: 'a, F: FnMut(&'a A) -> B>(array: &'a Self::BindGroupArray<A>, f: F) -> Self::BindGroupArray<B>;

    /// Get the [`wgpu::PipelineLayoutDescriptor`](https://docs.rs/wgpu/latest/wgpu/struct.PipelineLayoutDescriptor.html)
    /// to build the pipeline. Requires an array of references of its internal bind groups'
    /// <code>&[BindGroupLayout](https://docs.rs/wgpu/latest/wgpu/struct.BindGroupLayout.html)</code>s
    /// which are mappable from [`Self::bind_group_layout_types_array`].  
    /// Need to do it separately like this because `const fn`s in traits are "uNsTAbLe",
    /// apparently, and lifetimes exist.
    fn layout_desc<'a>(bind_group_layouts: &'a Self::BindGroupArray<Option<&wgpu::BindGroupLayout>>) -> wgpu::PipelineLayoutDescriptor<'a>;

    /// Get an array of
    /// <code>Option<[wgpu::ColorTargetState](https://docs.rs/wgpu/latest/wgpu/struct.ColorTargetState.html)></code>s.
    ///
    /// If a specific colour format was specified for this state in the macro, it will
    /// only be `Some` if the passed surface
    /// [`wgpu::TextureFormat`](https://docs.rs/wgpu/latest/wgpu/enum.TextureFormat.html)
    /// matches. If it was set to `ANY`, then for that entry it will always return
    /// `Some` with the passed-in format.
    ///
    /// tbh I'm not sure if this is how it's intended to be used but yolo
    fn fragment_targets(surface_fmt: wgpu::TextureFormat) -> Self::FragmentArray<Option<wgpu::ColorTargetState>>;

    /// Get a [`wgpu::RenderPipelineDescriptor`](https://docs.rs/wgpu/latest/wgpu/struct.RenderPipelineDescriptor.html)
    /// from a layout for this specific type of pipeline, plus a shader and the
    /// fragment targets array from [`Self::fragment_targets`].
    fn pipeline_desc<'a>(
        layout: &'a MewPipelineLayout<Self>,
        shader: &'a wgpu::ShaderModule,
        vertex_entry: Option<&'a str>,
        fragment_entry: Option<&'a str>,
        fragment_targets: &'a Self::FragmentArray<Option<wgpu::ColorTargetState>>,
    ) -> wgpu::RenderPipelineDescriptor<'a>;
}


/// Wrapper for the layout of some pipeline, so that the compiler will scream
/// at you if you mix up pipelines.
pub struct MewPipelineLayout<PIPE: ?Sized> {
    layout: wgpu::PipelineLayout,
    _marker: PhantomData<PIPE>,
}
impl<PIPE: ?Sized> Deref for MewPipelineLayout<PIPE> {
    type Target = wgpu::PipelineLayout;
    fn deref(&self) -> &Self::Target {
        &self.layout
    }
}
impl<PIPE: ?Sized> MewPipelineLayout<PIPE> {
    /// Wrap a [`wgpu::PipelineLayout`](https://docs.rs/wgpu/latest/wgpu/struct.PipelineLayout.html).
    pub fn new(layout: wgpu::PipelineLayout) -> Self {
        Self {
            layout,
            _marker: PhantomData,
        }
    }
}