Skip to main content

pebble/wgpu/
material.rs

1use crate::{
2    assets::{handle::Handle, storage::Assets, upload::Asset},
3    wgpu::{
4        backend::WGPUBackend,
5        binding::{BindGroupLayout, BindGroupLayoutBuilder, BindingEntry},
6        flags::ShaderStages,
7        texture_format::TextureFormat,
8        vertex_format::VertexBufferLayout,
9    },
10};
11
12/// A `wgpu::RenderPipeline`, opaque — built only via [`build_material`]/
13/// [`GPUMaterial`]'s `Asset::upload`. Bind it against a
14/// [`RenderPass`](super::render_pass::RenderPass) via
15/// [`RenderPass::set_pipeline`](super::render_pass::RenderPass::set_pipeline);
16/// there's no way to reach the underlying `wgpu::RenderPipeline` from
17/// outside this crate.
18pub struct RenderPipeline(wgpu::RenderPipeline);
19
20impl RenderPipeline {
21    pub(crate) fn raw(&self) -> &wgpu::RenderPipeline {
22        &self.0
23    }
24}
25
26/// Face of a vertex considered for culling — mirrors `wgpu::Face`.
27#[derive(Copy, Clone, PartialEq, Eq, Hash)]
28pub enum Face {
29    Front,
30    Back,
31}
32
33impl From<Face> for wgpu::Face {
34    fn from(value: Face) -> Self {
35        match value {
36            Face::Front => Self::Front,
37            Face::Back => Self::Back,
38        }
39    }
40}
41
42/// Rasterizer polygon mode — mirrors `wgpu::PolygonMode`.
43#[derive(Copy, Clone, PartialEq, Eq, Hash)]
44pub enum PolygonMode {
45    Fill,
46    Line,
47    Point,
48}
49
50impl From<PolygonMode> for wgpu::PolygonMode {
51    fn from(value: PolygonMode) -> Self {
52        match value {
53            PolygonMode::Fill => Self::Fill,
54            PolygonMode::Line => Self::Line,
55            PolygonMode::Point => Self::Point,
56        }
57    }
58}
59
60/// Color/alpha blend factor — mirrors `wgpu::BlendFactor`.
61#[derive(Copy, Clone, PartialEq, Eq, Hash)]
62pub enum BlendFactor {
63    Zero,
64    One,
65    Src,
66    OneMinusSrc,
67    SrcAlpha,
68    OneMinusSrcAlpha,
69    Dst,
70    OneMinusDst,
71    DstAlpha,
72    OneMinusDstAlpha,
73    SrcAlphaSaturated,
74    Constant,
75    OneMinusConstant,
76    Src1,
77    OneMinusSrc1,
78    Src1Alpha,
79    OneMinusSrc1Alpha,
80}
81
82impl From<BlendFactor> for wgpu::BlendFactor {
83    fn from(value: BlendFactor) -> Self {
84        match value {
85            BlendFactor::Zero => Self::Zero,
86            BlendFactor::One => Self::One,
87            BlendFactor::Src => Self::Src,
88            BlendFactor::OneMinusSrc => Self::OneMinusSrc,
89            BlendFactor::SrcAlpha => Self::SrcAlpha,
90            BlendFactor::OneMinusSrcAlpha => Self::OneMinusSrcAlpha,
91            BlendFactor::Dst => Self::Dst,
92            BlendFactor::OneMinusDst => Self::OneMinusDst,
93            BlendFactor::DstAlpha => Self::DstAlpha,
94            BlendFactor::OneMinusDstAlpha => Self::OneMinusDstAlpha,
95            BlendFactor::SrcAlphaSaturated => Self::SrcAlphaSaturated,
96            BlendFactor::Constant => Self::Constant,
97            BlendFactor::OneMinusConstant => Self::OneMinusConstant,
98            BlendFactor::Src1 => Self::Src1,
99            BlendFactor::OneMinusSrc1 => Self::OneMinusSrc1,
100            BlendFactor::Src1Alpha => Self::Src1Alpha,
101            BlendFactor::OneMinusSrc1Alpha => Self::OneMinusSrc1Alpha,
102        }
103    }
104}
105
106/// Color/alpha blend operation — mirrors `wgpu::BlendOperation`.
107#[derive(Copy, Clone, PartialEq, Eq, Hash)]
108pub enum BlendOperation {
109    Add,
110    Subtract,
111    ReverseSubtract,
112    Min,
113    Max,
114}
115
116impl From<BlendOperation> for wgpu::BlendOperation {
117    fn from(value: BlendOperation) -> Self {
118        match value {
119            BlendOperation::Add => Self::Add,
120            BlendOperation::Subtract => Self::Subtract,
121            BlendOperation::ReverseSubtract => Self::ReverseSubtract,
122            BlendOperation::Min => Self::Min,
123            BlendOperation::Max => Self::Max,
124        }
125    }
126}
127
128/// One color or alpha blend equation — mirrors `wgpu::BlendComponent`.
129#[derive(Copy, Clone, PartialEq, Eq, Hash)]
130pub struct BlendComponent {
131    pub src_factor: BlendFactor,
132    pub dst_factor: BlendFactor,
133    pub operation: BlendOperation,
134}
135
136impl BlendComponent {
137    /// Replaces the destination with the source outright.
138    pub const REPLACE: Self = Self {
139        src_factor: BlendFactor::One,
140        dst_factor: BlendFactor::Zero,
141        operation: BlendOperation::Add,
142    };
143
144    /// `(1 * src) + ((1 - src_alpha) * dst)`.
145    pub const OVER: Self = Self {
146        src_factor: BlendFactor::One,
147        dst_factor: BlendFactor::OneMinusSrcAlpha,
148        operation: BlendOperation::Add,
149    };
150}
151
152impl From<BlendComponent> for wgpu::BlendComponent {
153    fn from(value: BlendComponent) -> Self {
154        Self {
155            src_factor: value.src_factor.into(),
156            dst_factor: value.dst_factor.into(),
157            operation: value.operation.into(),
158        }
159    }
160}
161
162/// Blend state of a color target — mirrors `wgpu::BlendState`.
163#[derive(Copy, Clone, PartialEq, Eq, Hash)]
164pub struct BlendState {
165    pub color: BlendComponent,
166    pub alpha: BlendComponent,
167}
168
169impl BlendState {
170    /// No color blending — overwrites the target with the shader's output.
171    pub const REPLACE: Self = Self { color: BlendComponent::REPLACE, alpha: BlendComponent::REPLACE };
172
173    /// Standard alpha blending with non-premultiplied alpha.
174    pub const ALPHA_BLENDING: Self = Self {
175        color: BlendComponent {
176            src_factor: BlendFactor::SrcAlpha,
177            dst_factor: BlendFactor::OneMinusSrcAlpha,
178            operation: BlendOperation::Add,
179        },
180        alpha: BlendComponent::OVER,
181    };
182
183    /// Standard alpha blending with premultiplied alpha.
184    pub const PREMULTIPLIED_ALPHA_BLENDING: Self =
185        Self { color: BlendComponent::OVER, alpha: BlendComponent::OVER };
186}
187
188impl From<BlendState> for wgpu::BlendState {
189    fn from(value: BlendState) -> Self {
190        Self { color: value.color.into(), alpha: value.alpha.into() }
191    }
192}
193
194/// Describes the color state of a render pipeline — mirrors
195/// `wgpu::ColorTargetState`.
196#[derive(Clone, PartialEq, Eq, Hash)]
197pub struct ColorTargetState {
198    /// The format of the attachment this pipeline renders to.
199    pub format: TextureFormat,
200    /// Blending used for this target. `None` disables blending.
201    pub blend: Option<BlendState>,
202    /// Which color/alpha channels get written.
203    pub write_mask: super::flags::ColorWrites,
204}
205
206impl From<ColorTargetState> for wgpu::ColorTargetState {
207    fn from(value: ColorTargetState) -> Self {
208        Self {
209            format: value.format.into(),
210            blend: value.blend.map(Into::into),
211            write_mask: value.write_mask.into(),
212        }
213    }
214}
215
216/// A single opaque `Rgba8Unorm` color target with no blending — a
217/// ready-made value for [`Material::targets`] when you don't need
218/// anything more specific. Not applied automatically by `Default` (which
219/// leaves `targets` empty, since the right format usually depends on the
220/// surface/render target), so use it explicitly: `targets:
221/// DEFAULT_TARGET.to_vec()`.
222pub const DEFAULT_TARGET: [ColorTargetState; 1] = [ColorTargetState {
223    format: TextureFormat::Rgba8Unorm,
224    blend: None,
225    write_mask: super::flags::ColorWrites::ALL,
226}];
227
228/// Comparison function used for depth/stencil operations — mirrors
229/// `wgpu::CompareFunction`.
230#[derive(Copy, Clone, PartialEq, Eq, Hash)]
231pub enum CompareFunction {
232    Never,
233    Less,
234    Equal,
235    LessEqual,
236    Greater,
237    NotEqual,
238    GreaterEqual,
239    Always,
240}
241
242impl From<CompareFunction> for wgpu::CompareFunction {
243    fn from(value: CompareFunction) -> Self {
244        match value {
245            CompareFunction::Never => Self::Never,
246            CompareFunction::Less => Self::Less,
247            CompareFunction::Equal => Self::Equal,
248            CompareFunction::LessEqual => Self::LessEqual,
249            CompareFunction::Greater => Self::Greater,
250            CompareFunction::NotEqual => Self::NotEqual,
251            CompareFunction::GreaterEqual => Self::GreaterEqual,
252            CompareFunction::Always => Self::Always,
253        }
254    }
255}
256
257/// Operation performed on the stencil value — mirrors `wgpu::StencilOperation`.
258#[derive(Copy, Clone, PartialEq, Eq, Hash)]
259pub enum StencilOperation {
260    Keep,
261    Zero,
262    Replace,
263    Invert,
264    IncrementClamp,
265    DecrementClamp,
266    IncrementWrap,
267    DecrementWrap,
268}
269
270impl From<StencilOperation> for wgpu::StencilOperation {
271    fn from(value: StencilOperation) -> Self {
272        match value {
273            StencilOperation::Keep => Self::Keep,
274            StencilOperation::Zero => Self::Zero,
275            StencilOperation::Replace => Self::Replace,
276            StencilOperation::Invert => Self::Invert,
277            StencilOperation::IncrementClamp => Self::IncrementClamp,
278            StencilOperation::DecrementClamp => Self::DecrementClamp,
279            StencilOperation::IncrementWrap => Self::IncrementWrap,
280            StencilOperation::DecrementWrap => Self::DecrementWrap,
281        }
282    }
283}
284
285/// Per-face stencil test/operation state — mirrors `wgpu::StencilFaceState`.
286/// If you're not using stencil testing, leave this as [`Self::IGNORE`]
287/// (the [`Default`]).
288#[derive(Copy, Clone, PartialEq, Eq, Hash)]
289pub struct StencilFaceState {
290    pub compare: CompareFunction,
291    pub fail_op: StencilOperation,
292    pub depth_fail_op: StencilOperation,
293    pub pass_op: StencilOperation,
294}
295
296impl StencilFaceState {
297    pub const IGNORE: Self = Self {
298        compare: CompareFunction::Always,
299        fail_op: StencilOperation::Keep,
300        depth_fail_op: StencilOperation::Keep,
301        pass_op: StencilOperation::Keep,
302    };
303}
304
305impl Default for StencilFaceState {
306    fn default() -> Self {
307        Self::IGNORE
308    }
309}
310
311impl From<StencilFaceState> for wgpu::StencilFaceState {
312    fn from(value: StencilFaceState) -> Self {
313        Self {
314            compare: value.compare.into(),
315            fail_op: value.fail_op.into(),
316            depth_fail_op: value.depth_fail_op.into(),
317            pass_op: value.pass_op.into(),
318        }
319    }
320}
321
322/// Full stencil test state — mirrors `wgpu::StencilState`. Defaults to
323/// disabled (both faces [`StencilFaceState::IGNORE`], zero masks).
324#[derive(Copy, Clone, PartialEq, Eq, Hash, Default)]
325pub struct StencilState {
326    pub front: StencilFaceState,
327    pub back: StencilFaceState,
328    pub read_mask: u32,
329    pub write_mask: u32,
330}
331
332impl From<StencilState> for wgpu::StencilState {
333    fn from(value: StencilState) -> Self {
334        Self {
335            front: value.front.into(),
336            back: value.back.into(),
337            read_mask: value.read_mask,
338            write_mask: value.write_mask,
339        }
340    }
341}
342
343/// Depth bias ("polygon offset") state — mirrors `wgpu::DepthBiasState`.
344/// Defaults to disabled (all zero).
345#[derive(Copy, Clone, PartialEq, Default)]
346pub struct DepthBiasState {
347    pub constant: i32,
348    pub slope_scale: f32,
349    pub clamp: f32,
350}
351
352impl From<DepthBiasState> for wgpu::DepthBiasState {
353    fn from(value: DepthBiasState) -> Self {
354        Self { constant: value.constant, slope_scale: value.slope_scale, clamp: value.clamp }
355    }
356}
357
358/// Depth/stencil state of a render pipeline — mirrors `wgpu::DepthStencilState`.
359#[derive(Clone, PartialEq)]
360pub struct DepthStencilState {
361    /// Format of the depth/stencil attachment. Must match the attachment
362    /// bound at draw time.
363    pub format: TextureFormat,
364    /// Whether to write updated depth values. `None` if not depth-testing.
365    pub depth_write_enabled: Option<bool>,
366    /// Comparison function for the depth test. `None` if not depth-testing.
367    pub depth_compare: Option<CompareFunction>,
368    /// Stencil test state — [`StencilState::default()`] disables it.
369    pub stencil: StencilState,
370    /// Depth bias state — [`DepthBiasState::default()`] disables it.
371    pub bias: DepthBiasState,
372}
373
374impl From<DepthStencilState> for wgpu::DepthStencilState {
375    fn from(value: DepthStencilState) -> Self {
376        Self {
377            format: value.format.into(),
378            depth_write_enabled: value.depth_write_enabled,
379            depth_compare: value.depth_compare.map(Into::into),
380            stencil: value.stencil.into(),
381            bias: value.bias.into(),
382        }
383    }
384}
385
386/// Describes a render pipeline + its own bind group, the source type
387/// [`GPUMaterial`] is built from via [`build_material`]. Fields are private —
388/// start from [`Material::new`] and chain the setters below (or
389/// [`Material::default()`] for an opaque material with no shader source yet)
390/// rather than constructing one as a struct literal.
391pub struct Material {
392    /// Debug label, threaded through to the shader module, pipeline, and
393    /// bind group layout.
394    label: Option<&'static str>,
395    /// WGSL source for both the vertex and fragment stage.
396    shader_source: &'static str,
397    /// Vertex stage entry point. Defaults to `"vs_main"`.
398    vertex_entry: Option<&'static str>,
399    /// Fragment stage entry point. Defaults to `"fs_main"`.
400    fragment_entry: Option<&'static str>,
401    /// Vertex buffer layouts, in the order buffers will be bound at draw
402    /// time (e.g. [`Vertex::layout()`](super::mesh::Vertex::layout)).
403    vertex_layouts: Vec<VertexBufferLayout>,
404    /// This material's bind groups, in `@group(N)` order — set via
405    /// [`entries`](Self::entries), whose docs cover the full shape.
406    groups: Vec<super::layout::GroupEntry>,
407    /// Face culling mode. Defaults to `Some(Face::Back)`.
408    cull_mode: Option<Face>,
409    /// Depth/stencil state. `None` disables depth testing.
410    depth: Option<DepthStencilState>,
411    /// Color target states — one per fragment shader output. See
412    /// [`DEFAULT_TARGET`] for a ready-made single-target default.
413    targets: Vec<ColorTargetState>,
414    /// Rasterizer polygon mode. Defaults to `Fill`.
415    polygon_mode: PolygonMode,
416    /// Multisample count this pipeline renders at. Must match whatever
417    /// render pass it's used in — `1` (no MSAA, the default) for an
418    /// ordinary or offscreen target, or
419    /// [`WGPUBackend::sample_count`](super::backend::WGPUBackend::sample_count)
420    /// for a material meant to render into the (possibly MSAA) window
421    /// surface via `ColorTarget::Default`. Passes mixing sample counts in
422    /// one frame (an MSAA scene pass, a non-MSAA post-process/UI pass
423    /// reading the resolved result) need each material to declare its own.
424    sample_count: u32,
425}
426
427impl Default for Material {
428    fn default() -> Self {
429        Self {
430            label: None,
431            shader_source: "",
432            vertex_entry: Some("vs_main"),
433            fragment_entry: Some("fs_main"),
434            vertex_layouts: Vec::new(),
435            groups: Vec::new(),
436            cull_mode: Some(Face::Back),
437            depth: None,
438            targets: Vec::new(),
439            polygon_mode: PolygonMode::Fill,
440            sample_count: 1,
441        }
442    }
443}
444
445impl Material {
446    /// Start building a material with the given WGSL shader source.
447    /// All other fields are set to their defaults (see [`Default`]).
448    pub fn new(shader_source: &'static str) -> Self {
449        Self { shader_source, ..Self::default() }
450    }
451
452    pub fn label(mut self, label: &'static str) -> Self {
453        self.label = Some(label);
454        self
455    }
456
457    pub fn vertex_entry(mut self, entry: &'static str) -> Self {
458        self.vertex_entry = Some(entry);
459        self
460    }
461
462    /// Clear `vertex_entry` — let wgpu auto-detect the module's single
463    /// `@vertex` function instead of naming one. Only valid if
464    /// `shader_source` declares exactly one. The counterpart to
465    /// [`vertex_entry`](Self::vertex_entry), which can only set it to `Some`.
466    pub fn no_vertex_entry(mut self) -> Self {
467        self.vertex_entry = None;
468        self
469    }
470
471    pub fn fragment_entry(mut self, entry: &'static str) -> Self {
472        self.fragment_entry = Some(entry);
473        self
474    }
475
476    /// Clear `fragment_entry` — same rationale as
477    /// [`no_vertex_entry`](Self::no_vertex_entry), for the `@fragment` stage.
478    pub fn no_fragment_entry(mut self) -> Self {
479        self.fragment_entry = None;
480        self
481    }
482
483    pub fn vertex_layouts(mut self, layouts: Vec<VertexBufferLayout>) -> Self {
484        self.vertex_layouts = layouts;
485        self
486    }
487
488    /// This material's bind groups, in `@group(N)` order — position in `groups` *is* the
489    /// `@group(N)` index a shader must declare to match: the first element is `@group(0)`,
490    /// the second `@group(1)`, and so on. Each element is either:
491    ///
492    /// - [`GroupEntry::Own`](super::layout::GroupEntry::Own) — this material's own bind group
493    ///   entries, built into a fresh layout internally. At most one of these is allowed — the
494    ///   one group a [`GPUMaterialInstance`](super::instance::GPUMaterialInstance) binds
495    ///   concrete resources against — `build_material` panics on a second one.
496    /// - [`GroupEntry::Layout`](super::layout::GroupEntry::Layout) — an already-built layout
497    ///   occupying this position directly: a camera, lights, or anything else external, e.g.
498    ///   pulled from a [`GlobalLayoutPool`](super::layout::GlobalLayoutPool) via
499    ///   [`GlobalLayoutPool::get`](super::layout::GlobalLayoutPool::get).
500    ///
501    /// `build_material` also panics if any `Own` entry is visible to the compute stage, or if
502    /// `groups` needs more bind groups than the device's `max_bind_groups` allows (`wgpu`
503    /// guarantees only 4) — list only the groups this material's shader actually declares.
504    pub fn entries(mut self, groups: Vec<super::layout::GroupEntry>) -> Self {
505        self.groups = groups;
506        self
507    }
508
509    /// Face culling mode. Defaults to `Some(Face::Back)`.
510    pub fn cull_mode(mut self, mode: Face) -> Self {
511        self.cull_mode = Some(mode);
512        self
513    }
514
515    /// Clear `cull_mode` — render both faces (no backface culling). The
516    /// counterpart to [`cull_mode`](Self::cull_mode), which can only set it
517    /// to `Some`.
518    pub fn no_cull_mode(mut self) -> Self {
519        self.cull_mode = None;
520        self
521    }
522
523    pub fn depth(mut self, depth: DepthStencilState) -> Self {
524        self.depth = Some(depth);
525        self
526    }
527
528    pub fn targets(mut self, targets: Vec<ColorTargetState>) -> Self {
529        self.targets = targets;
530        self
531    }
532
533    pub fn polygon_mode(mut self, mode: PolygonMode) -> Self {
534        self.polygon_mode = mode;
535        self
536    }
537
538    pub fn sample_count(mut self, count: u32) -> Self {
539        self.sample_count = count;
540        self
541    }
542
543    /// Logs a WARN for likely-forgotten configuration — not fatal, since
544    /// there are legitimate reasons to leave these unset, but each is
545    /// unusual enough to be worth flagging before it turns into a confusing
546    /// wgpu validation error or a blank draw.
547    fn validate(&self) {
548        if self.targets.is_empty() {
549            tracing::warn!(
550                "Material{}: no color targets set — a render pipeline normally writes to at \
551                 least one; consider calling .targets(...) (unless this is intentionally a \
552                 depth-only pass)",
553                self.label.map(|l| format!(" '{l}'")).unwrap_or_default(),
554            );
555        }
556    }
557
558    /// Consume the builder and return the finished [`Material`] value.
559    pub fn build(self) -> Self {
560        self.validate();
561        self
562    }
563
564    /// Consume the builder, insert into `assets` under `name`, and return
565    /// the resulting [`Handle<Material>`].
566    pub fn build_asset(self, name: &str, assets: &mut Assets<Self>) -> Handle<Self> {
567        self.validate();
568        assets.insert(name, self)
569    }
570}
571
572/// Builds a render pipeline and its own bind group layout from `desc`.
573///
574/// Panics if the one [`GroupEntry::Own`](super::layout::GroupEntry::Own) in `desc.entries`
575/// (if any) is visible to the compute stage — [`BindingKind`](super::binding::BindingKind) is
576/// shared with [`Compute`](super::compute::Compute), and this is the check that catches a
577/// compute-only entry accidentally reused in a material instead of letting it fail deep inside
578/// wgpu with a less specific error. The bind group layout itself comes from
579/// [`binding::BindGroupLayoutBuilder`](super::binding::BindGroupLayoutBuilder). The pipeline
580/// layout is assembled directly from `desc.entries`, in order — position is the `@group(N)`
581/// index — panicking if `desc.entries` contains more than one `GroupEntry::Own`, or needs more
582/// bind groups than the device's `max_bind_groups` allows, turning either mistake into an
583/// immediate, specific error instead of an opaque wgpu validation failure at draw time.
584pub fn build_material(backend: &WGPUBackend, desc: &Material) -> (RenderPipeline, BindGroupLayout) {
585    build_material_raw(&backend.device, desc)
586}
587
588/// Panics if `desc.vertex_layouts`/`desc.targets` need more of a device's fixed-size pipeline
589/// resources than it actually has — `max_vertex_buffers`, `max_vertex_attributes` (summed
590/// across every vertex layout), `max_color_attachments` — turning what would otherwise be an
591/// opaque wgpu validation panic deep inside `create_render_pipeline` into a clear message with
592/// the actual count and the device's real limit.
593fn check_material_limits(device: &wgpu::Device, desc: &Material) {
594    let limits = device.limits();
595    let labeled = || desc.label.map(|l| format!(" '{l}'")).unwrap_or_default();
596
597    let buffer_count = desc.vertex_layouts.len() as u32;
598    if buffer_count > limits.max_vertex_buffers {
599        panic!(
600            "material{}: {buffer_count} vertex buffer layouts exceeds this device's \
601             max_vertex_buffers ({})",
602            labeled(),
603            limits.max_vertex_buffers
604        );
605    }
606
607    let attribute_count: u32 = desc.vertex_layouts.iter().map(|l| l.attributes.len() as u32).sum();
608    if attribute_count > limits.max_vertex_attributes {
609        panic!(
610            "material{}: {attribute_count} vertex attributes (summed across every vertex \
611             layout) exceeds this device's max_vertex_attributes ({})",
612            labeled(),
613            limits.max_vertex_attributes
614        );
615    }
616
617    let target_count = desc.targets.len() as u32;
618    if target_count > limits.max_color_attachments {
619        panic!(
620            "material{}: {target_count} color targets exceeds this device's max_color_attachments ({})",
621            labeled(),
622            limits.max_color_attachments
623        );
624    }
625}
626
627/// Internal primitive behind [`build_material`] — used directly only by
628/// tests, which have a raw `wgpu::Device` but no full [`WGPUBackend`].
629pub(crate) fn build_material_raw(
630    device: &wgpu::Device,
631    desc: &Material,
632) -> (RenderPipeline, BindGroupLayout) {
633    check_material_limits(device, desc);
634
635    let own_entries =
636        super::layout::find_own_entries(desc.label, super::layout::PipelineKind::Material, &desc.groups);
637    for entry in own_entries {
638        if entry.kind.visibility().intersects(ShaderStages::COMPUTE) {
639            panic!(
640                "material{}: entry '{}' is visible to the compute stage — material bind \
641                 group entries must not be COMPUTE-visible",
642                desc.label.map(|l| format!(" '{l}'")).unwrap_or_default(),
643                entry.name,
644            );
645        }
646    }
647
648    let layout = BindGroupLayoutBuilder::new()
649        .label(desc.label)
650        .entries(own_entries.iter().cloned())
651        .build_raw(device);
652
653    let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
654        label: desc.label,
655        source: wgpu::ShaderSource::Wgsl(desc.shader_source.into()),
656    });
657
658    let bind_group_layouts = super::layout::assemble_group_layouts(
659        desc.label,
660        &desc.groups,
661        &layout,
662        device.limits().max_bind_groups,
663    );
664
665    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
666        label: desc.label,
667        bind_group_layouts: &bind_group_layouts,
668        immediate_size: 0,
669    });
670
671    let attribute_sets: Vec<Vec<wgpu::VertexAttribute>> = desc
672        .vertex_layouts
673        .iter()
674        .map(|l| l.attributes.iter().map(|a| (*a).into()).collect())
675        .collect();
676    let vertex_buffers: Vec<wgpu::VertexBufferLayout> = desc
677        .vertex_layouts
678        .iter()
679        .zip(attribute_sets.iter())
680        .map(|(l, attrs)| wgpu::VertexBufferLayout {
681            array_stride: l.array_stride,
682            step_mode: l.step_mode.into(),
683            attributes: attrs,
684        })
685        .collect();
686
687    let targets: Vec<Option<wgpu::ColorTargetState>> =
688        desc.targets.iter().cloned().map(|t| Some(t.into())).collect();
689
690    let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
691        label: desc.label,
692        layout: Some(&pipeline_layout),
693        vertex: wgpu::VertexState {
694            module: &module,
695            entry_point: desc.vertex_entry,
696            compilation_options: Default::default(),
697            buffers: &vertex_buffers,
698        },
699        primitive: wgpu::PrimitiveState {
700            topology: wgpu::PrimitiveTopology::TriangleList,
701            strip_index_format: None,
702            front_face: wgpu::FrontFace::Ccw,
703            cull_mode: desc.cull_mode.map(Into::into),
704            unclipped_depth: false,
705            polygon_mode: desc.polygon_mode.into(),
706            conservative: false,
707        },
708        depth_stencil: desc.depth.clone().map(Into::into),
709        multisample: wgpu::MultisampleState {
710            count: desc.sample_count,
711            mask: !0,
712            alpha_to_coverage_enabled: false,
713        },
714        fragment: Some(wgpu::FragmentState {
715            module: &module,
716            entry_point: desc.fragment_entry,
717            compilation_options: Default::default(),
718            targets: &targets,
719        }),
720        multiview_mask: None,
721        cache: None,
722    });
723
724    (RenderPipeline(pipeline), layout)
725}
726
727/// A material uploaded to the GPU: a render pipeline plus the bind group
728/// layout entries it expects, ready for a
729/// [`GPUMaterialInstance`](super::instance::GPUMaterialInstance) to bind
730/// actual resources against.
731pub struct GPUMaterial {
732    pub pipeline: RenderPipeline,
733    layout: BindGroupLayout,
734    entries: Vec<BindingEntry>,
735}
736
737impl super::binding::BindGroupTarget for GPUMaterial {
738    fn bind_group_layout(&self) -> &BindGroupLayout {
739        &self.layout
740    }
741    fn binding_entries(&self) -> &[BindingEntry] {
742        &self.entries
743    }
744}
745
746impl Asset<WGPUBackend> for GPUMaterial {
747    type Source = Material;
748    type Deps<'a> = ();
749
750    fn upload<'a>(source: &Material, backend: &WGPUBackend, _deps: &()) -> Option<Self> {
751        let (pipeline, layout) = build_material(backend, source);
752        let entries =
753            super::layout::find_own_entries(source.label, super::layout::PipelineKind::Material, &source.groups)
754                .to_vec();
755
756        Some(Self { pipeline, layout, entries })
757    }
758}
759
760crate::wgpu::plugin_macros::asset_plugin! {
761    /// Registers the [`GPUMaterial`] asset pipeline (`Assets<Material>`
762    /// → `ProcessedAssets<GPUMaterial>`). Included by
763    /// [`WGPUPlugin`](super::backend::WGPUPlugin); add directly only if you're
764    /// assembling the `wgpu` module's plugins by hand.
765    MaterialPlugin, GPUMaterial
766}
767
768#[cfg(test)]
769mod tests {
770    use super::*;
771    use crate::wgpu::binding::{BindingEntry, BindingKind};
772    use crate::wgpu::test_util::with_device;
773    use crate::wgpu::vertex_format::{VertexAttribute, VertexFormat, VertexStepMode};
774
775    const MINIMAL_SHADER: &str = r#"
776        @vertex
777        fn vs_main() -> @builtin(position) vec4<f32> {
778            return vec4<f32>(0.0, 0.0, 0.0, 1.0);
779        }
780        @fragment
781        fn fs_main() -> @location(0) vec4<f32> {
782            return vec4<f32>(1.0, 1.0, 1.0, 1.0);
783        }
784    "#;
785
786    #[test]
787    fn a_compute_visible_own_entry_panics_before_touching_the_device() {
788        with_device!(device, _queue, {
789            let desc = Material::new(MINIMAL_SHADER)
790                .entries(vec![super::super::layout::GroupEntry::Own(vec![BindingEntry {
791                    name: "bad",
792                    binding: 0,
793                    kind: BindingKind::storage_buffer_read_write(ShaderStages::COMPUTE),
794                }])])
795                .targets(DEFAULT_TARGET.to_vec())
796                .build();
797            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
798                build_material_raw(&device, &desc);
799            }));
800            assert!(result.is_err(), "expected a panic for a COMPUTE-visible material entry");
801        });
802    }
803
804    #[test]
805    fn no_entries_at_all_builds_without_panicking() {
806        with_device!(device, _queue, {
807            let desc = Material::new(MINIMAL_SHADER).targets(DEFAULT_TARGET.to_vec()).build();
808            build_material_raw(&device, &desc);
809        });
810    }
811
812    #[test]
813    fn a_layout_pulled_from_the_global_pool_ends_up_in_the_pipeline_layout() {
814        with_device!(device, _queue, {
815            let mut pool = super::super::layout::GlobalLayoutPool::new();
816            pool.register("camera", crate::wgpu::binding::BindGroupLayoutBuilder::new().build_raw(&device));
817
818            let desc = Material::new(MINIMAL_SHADER)
819                .entries(vec![super::super::layout::GroupEntry::Layout(pool.get("camera").unwrap())])
820                .targets(DEFAULT_TARGET.to_vec())
821                .build();
822
823            build_material_raw(&device, &desc);
824        });
825    }
826
827    #[test]
828    fn own_and_layout_groups_are_ordered_by_position() {
829        with_device!(device, _queue, {
830            let extra = crate::wgpu::binding::BindGroupLayoutBuilder::new().build_raw(&device);
831            let desc = Material::new(MINIMAL_SHADER)
832                .entries(vec![
833                    super::super::layout::GroupEntry::Own(vec![]),
834                    super::super::layout::GroupEntry::Layout(extra),
835                ])
836                .targets(DEFAULT_TARGET.to_vec())
837                .build();
838
839            build_material_raw(&device, &desc);
840        });
841    }
842
843    #[test]
844    fn more_than_one_own_group_panics() {
845        with_device!(device, _queue, {
846            let desc = Material::new(MINIMAL_SHADER)
847                .entries(vec![
848                    super::super::layout::GroupEntry::Own(vec![]),
849                    super::super::layout::GroupEntry::Own(vec![]),
850                ])
851                .targets(DEFAULT_TARGET.to_vec())
852                .build();
853
854            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
855                build_material_raw(&device, &desc);
856            }));
857            assert!(result.is_err(), "expected a panic for more than one Own group");
858        });
859    }
860
861    #[test]
862    fn exceeding_max_bind_groups_panics() {
863        with_device!(device, _queue, {
864            // This device's real max_bind_groups is at least 4, so 5 groups always exceeds it.
865            let groups: Vec<super::super::layout::GroupEntry> = (0..5)
866                .map(|_| {
867                    super::super::layout::GroupEntry::Layout(
868                        crate::wgpu::binding::BindGroupLayoutBuilder::new().build_raw(&device),
869                    )
870                })
871                .collect();
872            let desc =
873                Material::new(MINIMAL_SHADER).entries(groups).targets(DEFAULT_TARGET.to_vec()).build();
874
875            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
876                build_material_raw(&device, &desc);
877            }));
878            assert!(result.is_err(), "expected a panic for exceeding max_bind_groups");
879        });
880    }
881
882    #[test]
883    fn exceeding_max_vertex_buffers_panics() {
884        with_device!(device, _queue, {
885            let too_many = device.limits().max_vertex_buffers + 1;
886            let layouts: Vec<VertexBufferLayout> = (0..too_many)
887                .map(|_| VertexBufferLayout { array_stride: 4, step_mode: VertexStepMode::Vertex, attributes: vec![] })
888                .collect();
889            let desc = Material::new(MINIMAL_SHADER)
890                .vertex_layouts(layouts)
891                .targets(DEFAULT_TARGET.to_vec())
892                .build();
893
894            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
895                build_material_raw(&device, &desc);
896            }));
897            assert!(result.is_err(), "expected a panic for exceeding max_vertex_buffers");
898        });
899    }
900
901    #[test]
902    fn exceeding_max_vertex_attributes_panics() {
903        with_device!(device, _queue, {
904            let too_many = device.limits().max_vertex_attributes + 1;
905            let attributes: Vec<VertexAttribute> = (0..too_many)
906                .map(|i| VertexAttribute { format: VertexFormat::Float32, offset: 0, shader_location: i })
907                .collect();
908            let desc = Material::new(MINIMAL_SHADER)
909                .vertex_layouts(vec![VertexBufferLayout {
910                    array_stride: 4,
911                    step_mode: VertexStepMode::Vertex,
912                    attributes,
913                }])
914                .targets(DEFAULT_TARGET.to_vec())
915                .build();
916
917            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
918                build_material_raw(&device, &desc);
919            }));
920            assert!(result.is_err(), "expected a panic for exceeding max_vertex_attributes");
921        });
922    }
923
924    #[test]
925    fn exceeding_max_color_attachments_panics() {
926        with_device!(device, _queue, {
927            let too_many = device.limits().max_color_attachments + 1;
928            let targets: Vec<ColorTargetState> = (0..too_many).map(|_| DEFAULT_TARGET[0].clone()).collect();
929            let desc = Material::new(MINIMAL_SHADER).targets(targets).build();
930
931            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
932                build_material_raw(&device, &desc);
933            }));
934            assert!(result.is_err(), "expected a panic for exceeding max_color_attachments");
935        });
936    }
937}