Skip to main content

mln_engine/draw/
objects.rs

1//! Meshes, the GPU objects of what a draw draws, which the renderer keeps
2//! between frames and makes again only when what they are made of changes,
3//! and the buffers a frame's draws bind with the bindings made of them.
4//!
5//! A mesh owns what is its own, its own indexes and attribute data, and
6//! holds what it shares with other meshes, its textures and the indexes and
7//! vertices of buckets and static geometry, through handles of the context's
8//! stores (`store`), which keep them while the mesh lasts. It binds no
9//! uniform buffers: the frame that draws it does ([`DrawBuffers`]), so that
10//! frames with buffers of their own can draw one mesh.
11//!
12//! A shader reads vertices as attributes, or, where the device binds vertex
13//! buffers (`Caps::binds_vertex_buffers`), as a storage buffer that it
14//! indexes itself (`Mesh::read_as_storage`).
15
16use mln_gfx::color_mode::ColorMode;
17use mln_gfx::cull_face_mode::CullFaceMode;
18use mln_gfx::depth_mode::DepthMode;
19use mln_gfx::draw_mode::DrawMode;
20use mln_gfx::gfx_types::{AttributeDataType, DrawModeType, PrimitiveType};
21use mln_gfx::gpu::{
22    BindGroupEntry, BindingsDesc, BindingsId, BufferId, DepthState, Draw, DynamicState, FixedState, GeometryDesc,
23    GeometryId, Gpu, GpuError, MAX_BASE_VERTEX, PipelineId, PipelineKey, SamplerId, Scissor, ShaderId, ShaderKey,
24    StencilState, TargetFormats, TextureId, VertexAttribute as GpuVertexAttribute, VertexBufferLayout, VertexStep,
25};
26use mln_gfx::shaders::bindings::{BUFFER_IDS, MAX_TEXTURES};
27use mln_gfx::shaders::program::Program;
28use mln_gfx::stencil_mode::StencilMode;
29use mln_gfx::texture2d::SamplerState;
30use mln_style::hash::HashMap;
31use smallvec::SmallVec;
32
33use crate::draw::buffer::Buffer;
34use crate::draw::context::Context;
35use crate::draw::identity::SimpleIdentity;
36use crate::draw::indexes::DrawIndexes;
37use crate::draw::owned::{Held, Owned};
38use crate::draw::range::DrawRange;
39use crate::draw::resources::{Device, Resources};
40use crate::draw::store::{IndexBuffer, MeshKey, Shared, Texture, WeakShared};
41use crate::draw::uniform_buffer::UniformBufferArray;
42use crate::draw::upload::{self, AttributeBindingArray, AttributeSlots};
43use crate::draw::vertex::{VertexBinding, attributes_of, replace_attributes};
44use crate::draw::vertex_attribute::VertexAttributeArray;
45use crate::draw::vertices::VertexBuffer;
46use crate::log_target;
47use crate::render::paint_parameters::{DrawTarget, PaintParameters};
48
49/// The textures a draw binds, by the slots of its program's textures.
50pub type Textures = [Option<Texture>; MAX_TEXTURES];
51
52/// The most vertex buffers a draw binds, WebGPU's default limit.
53const MAX_VERTEX_BUFFERS: usize = 8;
54
55/// What a mesh draws: its vertices, and the primitives its draw calls draw
56/// of them.
57pub(crate) struct DrawGeometry {
58    /// The vertex attributes, by the names of the program's attributes.
59    pub(crate) vertices: VertexAttributeArray,
60    /// How many vertices the attributes hold, which an attribute the
61    /// shader reads and the draw lacks gets default values for.
62    pub(crate) vertex_count: usize,
63    /// The primitive the draw calls draw.
64    pub(crate) mode: DrawMode,
65    pub(crate) indexes: DrawIndexes,
66    /// What each draw call draws.
67    pub(crate) ranges: Vec<DrawRange>,
68    /// The attributes of each instance, for a draw of instances.
69    pub(crate) instances: Option<VertexAttributeArray>,
70}
71
72/// `count` vertices of `data_type` in `data` as the vertex attribute `name`,
73/// none where there are no vertices.
74#[must_use]
75pub(crate) fn raw_vertices(
76    name: &'static str,
77    data: Vec<u8>,
78    count: usize,
79    data_type: AttributeDataType,
80) -> VertexAttributeArray {
81    let mut attributes = VertexAttributeArray::new();
82    if count == 0 || data.is_empty() {
83        return attributes;
84    }
85    attributes.set_own(name, data_type, data);
86    attributes
87}
88
89/// The most vertices a draw's shader reads as storage buffers.
90const MAX_STORAGE_VERTICES: usize = 3;
91
92/// The most entries bindings have.
93const MAX_ENTRIES: usize = BUFFER_IDS + MAX_STORAGE_VERTICES + MAX_TEXTURES;
94
95/// The entries of bindings, on the stack: at most a buffer at each uniform
96/// buffer id, one of each of the vertices read as storage buffers, and a
97/// texture at each texture slot.
98pub(crate) struct Entries {
99    entries: [BindGroupEntry; MAX_ENTRIES],
100    len: usize,
101}
102
103impl Entries {
104    pub(crate) fn new() -> Entries {
105        let none = BindGroupEntry::Texture { slot: 0, texture: TextureId::default(), sampler: SamplerId::default() };
106        Entries { entries: [none; MAX_ENTRIES], len: 0 }
107    }
108
109    pub(crate) fn push(&mut self, entry: BindGroupEntry) {
110        self.entries[self.len] = entry;
111        self.len += 1;
112    }
113
114    pub(crate) fn as_slice(&self) -> &[BindGroupEntry] {
115        &self.entries[..self.len]
116    }
117}
118
119/// The vertex that a geometry's per-vertex buffers start at
120/// ([`segment_geometry`]), and the geometry. Ranges that start within
121/// [`MAX_BASE_VERTEX`] draw the geometry from vertex 0 at their base vertex;
122/// one that starts past it draws a geometry from its first vertex at base
123/// vertex 0.
124type SegmentGeometry = (usize, Owned<GeometryId>);
125
126/// The shader, layouts, vertex slots, and index buffer that [`segment_geometry`]
127/// binds into a GPU geometry.
128struct GeometryParts<'a> {
129    shader: ShaderId,
130    layouts: &'a [VertexBufferLayout],
131    slots: &'a [VertexSlot],
132    index_buffer: BufferId,
133    index_held: Option<Held>,
134}
135
136/// The geometry of `parts.slots`, with `parts.index_buffer`, whose per-vertex
137/// buffers start `start` vertices into theirs, holding what it is made of.
138fn segment_geometry(
139    gpu: &mut dyn Gpu,
140    context: &Context,
141    parts: GeometryParts<'_>,
142    start: usize,
143) -> Result<Owned<GeometryId>, GpuError> {
144    let GeometryParts { shader, layouts, slots, index_buffer, index_held } = parts;
145    // On the stack: the geometry's handles take the allocation.
146    let mut buffers = [(BufferId::default(), 0); MAX_VERTEX_BUFFERS];
147    for (buffer, slot) in buffers.iter_mut().zip(slots) {
148        let skipped = match slot.layout.step {
149            VertexStep::Vertex => start as u64 * u64::from(slot.layout.stride),
150            VertexStep::Instance => 0,
151        };
152        *buffer = (slot.buffer, slot.offset + skipped);
153    }
154    let geometry =
155        gpu.create_geometry(&GeometryDesc { shader, layouts, vertex_buffers: &buffers[..slots.len()], index_buffer })?;
156    // Of the exact length: geometry is made as tiles come.
157    let len = slots.iter().filter(|slot| slot.held.is_some()).count() + usize::from(index_held.is_some());
158    let mut held = Vec::with_capacity(len);
159    held.extend(slots.iter().filter_map(|slot| slot.held.clone()).chain(index_held));
160    Ok(context.own(geometry, held))
161}
162
163/// A vertex buffer a draw binds, what keeps it where others share it, and
164/// how its pipeline reads it.
165struct VertexSlot {
166    buffer: BufferId,
167    held: Option<Held>,
168    offset: u64,
169    layout: VertexBufferLayout,
170}
171
172/// What a mesh's bindings were made of besides its frame's buffers: the
173/// epoch of the global uniform buffers, how often the buffers of the
174/// vertices the mesh reads as storage buffers changed, and the texture and
175/// sampler it bound at each texture slot.
176#[derive(Clone, Copy, PartialEq)]
177struct BindingsStamp {
178    global: u64,
179    storage: u64,
180    textures: [Option<(TextureId, SamplerId)>; MAX_TEXTURES],
181}
182
183/// The bindings a frame made of a mesh, while the mesh lasts.
184struct MeshBindings {
185    mesh: WeakShared<MeshKey>,
186    bindings: Owned<BindingsId>,
187    stamp: BindingsStamp,
188}
189
190/// The uniform and storage buffers that a frame's draws bind, by id, and
191/// the bindings of each mesh the draws drew, made of them, of the context's
192/// global buffers and of the mesh's textures and vertices read as storage
193/// buffers. The bindings of a mesh go when the mesh drops, by the next
194/// [`sweep`](Self::sweep), and all of them when a buffer is made or
195/// replaced, before the buffer they were made of goes.
196#[derive(Default)]
197pub(crate) struct DrawBuffers {
198    buffers: UniformBufferArray,
199    bindings: HashMap<SimpleIdentity, MeshBindings>,
200}
201
202impl DrawBuffers {
203    /// The buffer `id`, if the frame has one.
204    pub(crate) fn get(&self, id: usize) -> Option<&Buffer> {
205        self.buffers.get(id)
206    }
207
208    /// Writes `value` to the uniform buffer `id`, as
209    /// [`UniformBufferArray::write_pod`] does.
210    pub(crate) fn write_pod<T: bytemuck::Pod>(&mut self, gpu: &mut dyn Gpu, id: usize, value: &T, device: &mut Device) {
211        let epoch = self.buffers.epoch();
212        let _replaced = self.buffers.write_pod(gpu, id, value, device);
213        self.made(epoch);
214    }
215
216    /// Writes `data`, the bytes of a block, to the uniform buffer `id`, as
217    /// [`UniformBufferArray::write_uniform`] does.
218    pub(crate) fn write_uniform(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
219        let epoch = self.buffers.epoch();
220        let _replaced = self.buffers.write_uniform(gpu, id, data, device);
221        self.made(epoch);
222    }
223
224    /// Writes `data` to the storage buffer `id`, as
225    /// [`UniformBufferArray::write_storage`] does.
226    pub(crate) fn write_storage(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
227        let epoch = self.buffers.epoch();
228        let _replaced = self.buffers.write_storage(gpu, id, data, device);
229        self.made(epoch);
230    }
231
232    /// Drops the bindings where a write since the buffers were at `epoch`
233    /// made or replaced a buffer, which they don't bind.
234    fn made(&mut self, epoch: u64) {
235        if self.buffers.epoch() != epoch {
236            self.bindings.clear();
237        }
238    }
239
240    /// Drops the bindings of the meshes that dropped.
241    pub(crate) fn sweep(&mut self) {
242        self.bindings.retain(|_, made| made.mesh.is_held());
243    }
244
245    /// The bindings of what `mesh`'s shader, `shader_id` on `gpu`, reads of
246    /// the context's global buffers, the frame's buffers, and the mesh's
247    /// textures and vertices read as storage buffers, made again where one
248    /// of them changed since the frame last drew the mesh.
249    fn bindings(
250        &mut self,
251        gpu: &mut dyn Gpu,
252        context: &mut Context,
253        mesh: &DrawObjects,
254        shader_id: ShaderId,
255    ) -> Result<BindingsId, GpuError> {
256        let program = mesh.shader.program();
257        let mut textures = [None; MAX_TEXTURES];
258        for slot in sampled_slots(program) {
259            if let Some(texture) = mesh.textures.get(slot).and_then(Option::as_ref) {
260                textures[slot] = Some(context.texture_binding(gpu, texture, mesh.samplers[slot])?);
261            }
262        }
263        let global = context.global_uniform_buffers();
264        let stamp = BindingsStamp { global: global.epoch(), storage: mesh.storage_epoch, textures };
265        if let Some(made) = self.bindings.get(&mesh.id)
266            && made.stamp == stamp
267        {
268            return Ok(made.bindings.id());
269        }
270        self.bindings.remove(&mesh.id);
271        let mut entries = Entries::new();
272        for id in 0..BUFFER_IDS {
273            // The frame's buffer wins over the global one.
274            let buffer = self.buffers.get(id).or_else(|| global.get(id));
275            if let Some(buffer) = buffer {
276                entries.push(BindGroupEntry::Buffer {
277                    id: id as u32,
278                    buffer: buffer.id(),
279                    offset: 0,
280                    size: buffer.size() as u64,
281                });
282            }
283        }
284        let mut held = Vec::new();
285        for (id, vertices, buffer) in &mesh.storage_vertices {
286            let size = context.vertices(vertices).map_or(0, |stored| stored.count() * stored.vertex_size());
287            if let Some(buffer) = buffer.filter(|_| size > 0) {
288                entries.push(BindGroupEntry::Buffer { id: *id as u32, buffer, offset: 0, size: size as u64 });
289                held.push(vertices.held());
290            }
291        }
292        for (slot, binding) in textures.iter().enumerate() {
293            if let Some((texture, sampler)) = *binding {
294                entries.push(BindGroupEntry::Texture { slot: slot as u32, texture, sampler });
295            }
296        }
297        held.extend(
298            sampled_slots(program)
299                .filter_map(|slot| context.gpu_texture(mesh.textures.get(slot)?.as_ref()?).cloned().map(Held::Texture)),
300        );
301        let bindings =
302            gpu.create_bindings(&BindingsDesc { label: program.name, shader: shader_id, entries: entries.as_slice() })?;
303        let made = MeshBindings { mesh: mesh.handle.clone(), bindings: context.own(bindings, held), stamp };
304        self.bindings.insert(mesh.id, made);
305        Ok(bindings)
306    }
307
308    /// The frame's bindings of `mesh`, as a draw of it binds them.
309    #[cfg(test)]
310    pub(crate) fn bind(
311        &mut self,
312        gpu: &mut dyn Gpu,
313        context: &mut Context,
314        mesh: &Mesh,
315    ) -> Result<BindingsId, GpuError> {
316        let objects = context.take_mesh(mesh).ok_or(GpuError::UnknownId("mesh"))?;
317        let bound =
318            context.shader(gpu, &objects.shader).and_then(|shader| self.bindings(gpu, context, &objects, shader));
319        context.put_mesh(mesh, objects);
320        bound
321    }
322
323    /// How many meshes the frame keeps bindings of.
324    #[cfg(test)]
325    pub(crate) fn bound_meshes(&self) -> usize {
326        self.bindings.len()
327    }
328}
329
330/// What, besides the draw's own state, a draw's pipeline depends on.
331#[derive(Clone, Copy, PartialEq)]
332struct PipelineVariant {
333    primitive: DrawModeType,
334    depth: DepthState,
335    stencil: StencilState,
336    targets: TargetFormats,
337}
338
339/// Geometry drawn with one program, and the GPU objects that draw it: its
340/// vertices, indexes and the ranges it draws of them, the textures it binds, the color and cull
341/// modes it draws with, and the shader, pipelines and geometry it made of
342/// them on the context's `Gpu`, which it makes again when what they are made
343/// of changes. The frames that draw it bind it with their buffers
344/// ([`DrawBuffers`]).
345pub(crate) struct DrawObjects {
346    /// Tells the mesh apart from the others, and orders it after those made
347    /// before it.
348    id: SimpleIdentity,
349    /// The mesh's handles, which the frames' bindings of it last while one
350    /// does.
351    handle: WeakShared<MeshKey>,
352    shader: ShaderKey,
353    vertex_attributes: VertexAttributeArray,
354    /// The attributes of each instance, for a draw of instances.
355    instance_attributes: Option<VertexAttributeArray>,
356    /// Whether the vertex attributes changed since the last upload, which
357    /// then binds them all again; true until the first.
358    vertex_attributes_changed: bool,
359    /// Whether the instance attributes changed since the last upload, as
360    /// `vertex_attributes_changed` says of the vertex attributes.
361    instance_attributes_changed: bool,
362    /// Where the program's vertex and instance attributes are in the
363    /// attribute arrays.
364    vertex_slots_of: AttributeSlots,
365    instance_slots_of: AttributeSlots,
366    /// The textures it binds, by slot.
367    textures: Textures,
368    /// The states it samples them with, by slot, in place of the textures'
369    /// own.
370    samplers: [Option<SamplerState>; MAX_TEXTURES],
371    /// The vertices the shader reads as storage buffers, each with the
372    /// buffer id it binds at, past the uniform buffers' ids, and its buffer
373    /// as of the last upload.
374    storage_vertices: Vec<(usize, VertexBuffer, Option<BufferId>)>,
375    /// How often a buffer of `storage_vertices` changed.
376    storage_epoch: u64,
377    color_mode: ColorMode,
378    cull_face_mode: CullFaceMode,
379
380    mode: DrawMode,
381    ranges: Vec<DrawRange>,
382    indexes: DrawIndexes,
383    vertex_count: usize,
384    attribute_bindings: AttributeBindingArray,
385    instance_bindings: AttributeBindingArray,
386    /// The vertex buffers of the bindings, `None` until a draw after either
387    /// changes computes them.
388    vertex_slots: Option<Vec<VertexSlot>>,
389    /// The context's shader of the draw's, once it drew.
390    shader_id: Option<ShaderId>,
391    /// The pipelines it drew with, for its shader, `pipeline_layouts`, color
392    /// and cull modes as they are.
393    pipelines: Vec<(PipelineVariant, PipelineId)>,
394    /// The vertex buffer layouts of the vertex slots the pipelines were made
395    /// for.
396    pipeline_layouts: Vec<VertexBufferLayout>,
397    /// The index buffer its geometry was made with, and the geometry of its
398    /// vertex slots from vertex 0 and from each vertex past
399    /// [`MAX_BASE_VERTEX`] that a range starts at. Inline for the one from
400    /// vertex 0: most meshes draw nothing past it.
401    geometry: Option<(BufferId, SmallVec<[SegmentGeometry; 1]>)>,
402}
403
404impl DrawObjects {
405    /// The objects of `geometry`, drawn with `shader` in `color_mode` and
406    /// `cull_face_mode`, binding `textures`.
407    #[must_use]
408    pub(crate) fn new(
409        shader: ShaderKey,
410        color_mode: ColorMode,
411        cull_face_mode: CullFaceMode,
412        geometry: DrawGeometry,
413        textures: Textures,
414    ) -> Self {
415        let DrawGeometry { vertices, vertex_count, mode, indexes, ranges, instances } = geometry;
416        DrawObjects {
417            id: SimpleIdentity::new(),
418            handle: WeakShared::default(),
419            shader,
420            vertex_attributes: vertices,
421            instance_attributes: instances,
422            vertex_attributes_changed: true,
423            instance_attributes_changed: true,
424            vertex_slots_of: AttributeSlots::default(),
425            instance_slots_of: AttributeSlots::default(),
426            textures,
427            samplers: [None; MAX_TEXTURES],
428            storage_vertices: Vec::new(),
429            storage_epoch: 0,
430            color_mode,
431            cull_face_mode,
432            mode,
433            ranges,
434            indexes,
435            vertex_count,
436            attribute_bindings: Vec::new(),
437            instance_bindings: Vec::new(),
438            vertex_slots: None,
439            shader_id: None,
440            pipelines: Vec::new(),
441            pipeline_layouts: Vec::new(),
442            geometry: None,
443        }
444    }
445
446    /// Uploads the indexes, vertex attributes, vertices read as storage
447    /// buffers and textures, where they changed since the last upload.
448    pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
449        if let Err(error) = self.upload_in(gpu, context) {
450            context.fail(format!("Uploading {} failed: {error}", self.shader.program().name));
451        }
452    }
453
454    fn upload_in(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<(), GpuError> {
455        let program = self.shader.program();
456        if self.indexes.buffer(context).is_none() && self.indexes.len(context) == 0 {
457            debug_assert!(false, "a draw of {} has no index data", program.name);
458            return Ok(());
459        }
460        self.indexes.upload(gpu, context)?;
461
462        // An attribute binds again where its array changed, or where the
463        // upload writes what it reads, which may be new. A failed upload
464        // leaves the attributes changed, so the next binds them again.
465        if self.vertex_attributes_changed
466            || upload::needs_upload(context, &self.vertex_attributes, &self.vertex_slots_of)
467        {
468            let updated = upload::update_attribute_bindings(
469                gpu,
470                context,
471                &self.shader,
472                program.attributes,
473                self.vertex_count,
474                upload::AttributeBindingState {
475                    overrides: &mut self.vertex_attributes,
476                    slots: &mut self.vertex_slots_of,
477                    bindings: &mut self.attribute_bindings,
478                },
479            );
480            if !matches!(updated, Ok(false)) {
481                self.vertex_slots = None;
482                self.geometry = None;
483            }
484            updated?;
485        }
486
487        let changed = self.instance_attributes_changed;
488        if let Some(attrs) = self
489            .instance_attributes
490            .as_mut()
491            .filter(|attrs| changed || upload::needs_upload(context, attrs, &self.instance_slots_of))
492        {
493            let instance_count = attrs.min_count();
494            let updated = upload::update_attribute_bindings(
495                gpu,
496                context,
497                &self.shader,
498                program.instance_attributes,
499                instance_count,
500                upload::AttributeBindingState {
501                    overrides: attrs,
502                    slots: &mut self.instance_slots_of,
503                    bindings: &mut self.instance_bindings,
504                },
505            );
506            if !matches!(updated, Ok(false)) {
507                self.vertex_slots = None;
508                self.geometry = None;
509            }
510            updated?;
511        }
512
513        self.vertex_attributes_changed = false;
514        self.instance_attributes_changed = false;
515
516        for (_, vertices, bound) in &mut self.storage_vertices {
517            let buffer = context.upload_vertices(gpu, vertices)?;
518            if *bound != buffer {
519                *bound = buffer;
520                self.storage_epoch += 1;
521            }
522        }
523
524        for texture in self.textures.iter().flatten() {
525            if let Err(error) = context.upload_texture(gpu, texture) {
526                context.fail(format!("Uploading a texture failed: {error}"));
527            }
528        }
529
530        Ok(())
531    }
532
533    /// The program the mesh draws with.
534    #[must_use]
535    pub(crate) fn program(&self) -> &'static Program {
536        self.shader.program()
537    }
538
539    /// Draws the ranges into `parameters`' open pass on `gpu`, the
540    /// context's, with `depth_mode` and `stencil_mode`, binding the buffers
541    /// of the draws in `frame`. Shaders read the draw's entries in those
542    /// storage buffers at `global_index`. Returns whether it didn't fail; a
543    /// draw that fails fails the frame
544    /// ([`Context::fail`](crate::draw::context::Context::fail)).
545    pub(crate) fn draw(
546        &mut self,
547        gpu: &mut dyn Gpu,
548        parameters: &mut PaintParameters<'_>,
549        frame: &mut DrawBuffers,
550        depth_mode: DepthMode,
551        stencil_mode: StencilMode,
552        global_index: u32,
553    ) -> bool {
554        let drawn = self.draw_in(gpu, parameters, frame, depth_mode, stencil_mode, global_index);
555        if let Err(error) = &drawn {
556            parameters.context.fail(format!("Drawing {} failed: {error}", self.shader.program().name));
557        }
558        drawn.is_ok()
559    }
560
561    fn draw_in(
562        &mut self,
563        gpu: &mut dyn Gpu,
564        parameters: &mut PaintParameters<'_>,
565        frame: &mut DrawBuffers,
566        depth_mode: DepthMode,
567        stencil_mode: StencilMode,
568        global_index: u32,
569    ) -> Result<(), GpuError> {
570        let Some(DrawTarget { size, targets, scissor }) = parameters.draw_target() else {
571            return Ok(());
572        };
573        let context = &mut *parameters.context;
574        let Some(index_buffer) = self.indexes.buffer(context) else {
575            // Only a failed upload, which failed the frame, leaves a draw
576            // without its indexes.
577            debug_assert!(
578                context.device().failed(),
579                "a draw of {} draws indexes it didn't upload",
580                self.shader.program().name
581            );
582            return Err(GpuError::Invalid("its indexes aren't uploaded".to_owned()));
583        };
584
585        let shader_id = match self.shader_id {
586            Some(id) => id,
587            None => *self.shader_id.insert(context.shader(gpu, &self.shader)?),
588        };
589        let bindings = frame.bindings(gpu, context, self, shader_id)?;
590        let slots = if let Some(slots) = &self.vertex_slots {
591            slots
592        } else {
593            let slots = vertex_slots(self.shader.program(), &self.attribute_bindings, &self.instance_bindings);
594            // New buffers in the layouts of the old ones keep the
595            // pipelines.
596            let layouts = slots.iter().map(|slot| &slot.layout);
597            if !layouts.clone().eq(self.pipeline_layouts.iter()) {
598                self.pipeline_layouts = layouts.cloned().collect();
599                self.pipelines.clear();
600            }
601            self.vertex_slots.insert(slots)
602        };
603        let geometries = match &mut self.geometry {
604            Some((indices, geometries)) if *indices == index_buffer => geometries,
605            geometry => &mut geometry.insert((index_buffer, SmallVec::new())).1,
606        };
607        let full = Scissor { x: 0, y: 0, width: size.width, height: size.height };
608        let dynamic = DynamicState {
609            depth_range: depth_mode.range,
610            scissor: scissor.unwrap_or(full),
611            stencil_reference: stencil_mode.ref_ as u32,
612            blend_constant: self.color_mode.blend_color,
613            line_width: 1.0,
614        };
615        let depth = DepthState::from(&depth_mode);
616        let stencil = StencilState::from(&stencil_mode);
617        let mut draws = 0;
618        let mode = self.mode;
619        for range in &self.ranges {
620            if range.index_count == 0 {
621                continue;
622            }
623            let variant = PipelineVariant { primitive: mode.kind, depth, stencil, targets };
624            let pipeline = if let Some(&(_, id)) = self.pipelines.iter().find(|(cached, _)| *cached == variant) {
625                id
626            } else {
627                let key = PipelineKey {
628                    shader: shader_id,
629                    vertex_buffers: self.pipeline_layouts.clone(),
630                    state: fixed_state(variant, &self.color_mode, self.cull_face_mode),
631                    targets,
632                };
633                let id = context.pipeline(gpu, &key)?;
634                self.pipelines.push((variant, id));
635                id
636            };
637            let line_width = if mode.primitive_type() == PrimitiveType::Line { mode.size } else { 1.0 };
638            let (start, base_vertex) = if range.base_vertex <= MAX_BASE_VERTEX {
639                (0, range.base_vertex)
640            } else {
641                (range.base_vertex as usize, 0)
642            };
643            let geometry = if let Some((_, geometry)) = geometries.iter().find(|(at, _)| *at == start) {
644                geometry.id()
645            } else {
646                let geometry = segment_geometry(
647                    gpu,
648                    context,
649                    GeometryParts {
650                        shader: shader_id,
651                        layouts: &self.pipeline_layouts,
652                        slots,
653                        index_buffer,
654                        index_held: self.indexes.held(),
655                    },
656                    start,
657                )?;
658                let id = geometry.id();
659                geometries.push((start, geometry));
660                id
661            };
662            gpu.draw(&Draw {
663                pipeline,
664                bindings,
665                geometry,
666                first_index: range.first_index,
667                index_count: range.index_count,
668                base_vertex,
669                first_instance: range.first_instance,
670                instance_count: range.instance_count,
671                global_index,
672                dynamic: DynamicState { line_width, ..dynamic },
673            })?;
674            draws += 1;
675        }
676        let stats = context.rendering_stats();
677        stats.num_draw_calls += draws;
678        stats.total_draw_calls += draws;
679        Ok(())
680    }
681
682    /// The vertex attributes, to change, which the next upload binds again.
683    /// The draw drops its geometry where they have values of their own,
684    /// whose buffers a change may drop.
685    pub(crate) fn vertex_attributes_mut(&mut self) -> &mut VertexAttributeArray {
686        self.vertex_attributes_changed = true;
687        if self.vertex_attributes.has_own() {
688            self.geometry = None;
689        }
690        &mut self.vertex_attributes
691    }
692
693    /// The attributes the paint values are read into, to change, which the
694    /// next upload binds again: the instance attributes of a draw of
695    /// instances, else the vertex attributes.
696    pub(crate) fn paint_attributes_mut(&mut self) -> &mut VertexAttributeArray {
697        let (attributes, changed) = match &mut self.instance_attributes {
698            Some(instances) => (instances, &mut self.instance_attributes_changed),
699            None => (&mut self.vertex_attributes, &mut self.vertex_attributes_changed),
700        };
701        *changed = true;
702        if attributes.has_own() {
703            self.geometry = None;
704        }
705        attributes
706    }
707
708    /// Makes `vertices` what the shader reads as the storage buffer `id`,
709    /// an id past the uniform buffers', on a device that binds vertex
710    /// buffers; nothing with `None`. The next upload writes them, and the
711    /// draws after it bind their buffer.
712    pub(crate) fn read_as_storage(&mut self, id: usize, vertices: Option<VertexBuffer>) {
713        debug_assert!(id >= BUFFER_IDS, "a uniform buffer's id");
714        self.storage_vertices.retain(|(at, ..)| *at != id);
715        debug_assert!(vertices.is_none() || self.storage_vertices.len() < MAX_STORAGE_VERTICES);
716        if let Some(vertices) = vertices {
717            self.storage_vertices.push((id, vertices, None));
718        }
719        self.storage_epoch += 1;
720    }
721
722    /// The buffer the draws bind as the storage buffer `id`, of the
723    /// vertices read there as of the last upload.
724    pub(crate) fn storage_buffer(&self, id: usize) -> Option<BufferId> {
725        self.storage_vertices.iter().find(|(at, ..)| *at == id).and_then(|&(_, _, buffer)| buffer)
726    }
727
728    /// Whether the draw draws instances.
729    #[must_use]
730    pub(crate) fn has_instances(&self) -> bool {
731        self.instance_attributes.is_some()
732    }
733
734    /// The texture it binds at its program's texture slot `slot`.
735    #[must_use]
736    pub(crate) fn texture(&self, slot: usize) -> Option<&Texture> {
737        self.textures[slot].as_ref()
738    }
739
740    /// Makes `texture` the one it binds at its program's texture slot
741    /// `slot`.
742    pub(crate) fn set_texture(&mut self, slot: usize, texture: Option<&Texture>) {
743        let bound = &mut self.textures[slot];
744        if bound.as_ref() != texture {
745            *bound = texture.cloned();
746        }
747    }
748
749    /// Samples the texture at its program's texture slot `slot` with
750    /// `state`, or with the texture's own state with `None`.
751    pub(crate) fn set_sampler(&mut self, slot: usize, state: Option<SamplerState>) {
752        self.samplers[slot] = state;
753    }
754
755    /// Replaces the indexes and the ranges drawn of them.
756    pub(crate) fn replace_indexes(&mut self, indexes: DrawIndexes, ranges: Vec<DrawRange>) {
757        if let DrawIndexes::Own(_) = self.indexes {
758            self.geometry = None;
759        }
760        self.indexes = indexes;
761        self.ranges = ranges;
762    }
763
764    /// Culls faces as `cull_face_mode` says from the next draw on.
765    pub(crate) fn set_cull_face_mode(&mut self, cull_face_mode: CullFaceMode) {
766        if self.cull_face_mode != cull_face_mode {
767            self.cull_face_mode = cull_face_mode;
768            // The pipelines bake the culling in.
769            self.pipelines.clear();
770        }
771    }
772}
773
774/// What a mesh is made of ([`Resources::mesh`]): `vertex_count` vertices
775/// that its `vertices` bindings read, the attributes of each instance that
776/// its `instances` bindings read, for a draw of instances, and the
777/// primitives of `mode` that its `ranges` draw of `indexes`, drawn with
778/// `shader` in `color_mode` and `cull_face_mode`, binding `textures`. An
779/// attribute the shader reads that no binding has reads its default value.
780///
781/// [`Resources::mesh`]: crate::draw::Resources::mesh
782pub struct MeshDesc {
783    pub shader: ShaderKey,
784    pub color_mode: ColorMode,
785    pub cull_face_mode: CullFaceMode,
786    pub mode: DrawMode,
787    pub vertices: Vec<VertexBinding>,
788    pub vertex_count: usize,
789    pub instances: Option<Vec<VertexBinding>>,
790    pub indexes: IndexBuffer,
791    pub ranges: Vec<DrawRange>,
792    pub textures: Textures,
793}
794
795/// A handle of a mesh, the GPU objects of what a draw draws
796/// (`DrawObjects`), which the context's store keeps while a clone of the
797/// handle lasts (`Context::mesh`). A layer keeps its meshes' handles, in
798/// its tile values or its own state, and the draws it pushes name them
799/// ([`Group::push`]), so that the engine uploads and draws them after the
800/// layer made its draws. Clones of a handle are the same mesh. A mesh
801/// changes through the [`Resources`] that the methods here take.
802///
803/// [`Group::push`]: crate::draw::draws::Group::push
804#[derive(Clone)]
805pub struct Mesh {
806    key: Shared<MeshKey>,
807    id: SimpleIdentity,
808    program: &'static Program,
809}
810
811impl Mesh {
812    /// The mesh that `desc` describes, in `context`'s store.
813    #[must_use]
814    pub(crate) fn of(context: &mut Context, desc: MeshDesc) -> Self {
815        let MeshDesc {
816            shader,
817            color_mode,
818            cull_face_mode,
819            mode,
820            vertices,
821            vertex_count,
822            instances,
823            indexes,
824            ranges,
825            textures,
826        } = desc;
827        let geometry = DrawGeometry {
828            vertices: attributes_of(&vertices),
829            vertex_count,
830            mode,
831            indexes: DrawIndexes::Shared(indexes),
832            ranges,
833            instances: instances.as_deref().map(attributes_of),
834        };
835        Mesh::new(context, shader, color_mode, cull_face_mode, geometry, textures)
836    }
837
838    /// The mesh of `geometry`, drawn with `shader` in `color_mode` and
839    /// `cull_face_mode`, binding `textures`, in `context`'s store.
840    #[must_use]
841    pub(crate) fn new(
842        context: &mut Context,
843        shader: ShaderKey,
844        color_mode: ColorMode,
845        cull_face_mode: CullFaceMode,
846        geometry: DrawGeometry,
847        textures: Textures,
848    ) -> Self {
849        let mut objects = DrawObjects::new(shader, color_mode, cull_face_mode, geometry, textures);
850        let (id, program) = (objects.id, objects.program());
851        let key = context.add_mesh_with(|key| {
852            objects.handle = key.downgrade();
853            objects
854        });
855        Mesh { key, id, program }
856    }
857
858    /// The handle of the mesh's entry in the context's store.
859    pub(crate) fn key(&self) -> &Shared<MeshKey> {
860        &self.key
861    }
862
863    /// The place of the mesh among the meshes, by when they were made, as a
864    /// draw's order ([`Draw::order`](crate::draw::draws::Draw::order)).
865    #[must_use]
866    pub fn seq(&self) -> i64 {
867        self.id.get() as i64
868    }
869
870    /// The program the mesh draws with.
871    #[must_use]
872    pub fn program(&self) -> &'static Program {
873        self.program
874    }
875
876    /// Runs `f` with the mesh's objects, taken out of `context`'s store
877    /// while it runs, and the context; `None` without them.
878    pub(crate) fn update<R>(
879        &self,
880        context: &mut Context,
881        f: impl FnOnce(&mut DrawObjects, &mut Context) -> R,
882    ) -> Option<R> {
883        let mut objects = context.take_mesh(self)?;
884        let result = f(&mut objects, context);
885        context.put_mesh(self, objects);
886        Some(result)
887    }
888
889    /// See `DrawObjects::upload`.
890    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
891        self.update(context, |objects, context| objects.upload(gpu, context));
892    }
893
894    /// See [`DrawObjects::vertex_attributes_mut`].
895    pub(crate) fn vertex_attributes_mut<'c>(&self, context: &'c mut Context) -> Option<&'c mut VertexAttributeArray> {
896        context.mesh_mut(self).map(DrawObjects::vertex_attributes_mut)
897    }
898
899    /// Makes `bindings` what the mesh reads its vertices from, in place of
900    /// what it read; the next upload binds them.
901    pub fn set_vertices<'b>(&self, res: &mut Resources<'_>, bindings: impl IntoIterator<Item = &'b VertexBinding>) {
902        if let Some(attrs) = self.vertex_attributes_mut(res.context) {
903            replace_attributes(attrs, bindings);
904        }
905    }
906
907    /// Binds `binding`'s vertex attributes on the mesh without replacing
908    /// unrelated attributes; the next upload binds them.
909    pub fn bind_vertices(&self, res: &mut Resources<'_>, binding: &VertexBinding) {
910        if let Some(attrs) = self.vertex_attributes_mut(res.context) {
911            binding.bind(attrs);
912        }
913    }
914
915    /// Makes `paint`, the vertices of a layer's data-driven paint values
916    /// ([`PaintAttributes`](crate::layer::binders::PaintAttributes)), what
917    /// the mesh reads the attributes of its layout from: of its instances,
918    /// for a draw of instances, else of its vertices. The next upload binds
919    /// them.
920    pub fn set_paint(&self, res: &mut Resources<'_>, paint: &VertexBinding) {
921        if let Some(objects) = res.context.mesh_mut(self) {
922            paint.bind(objects.paint_attributes_mut());
923        }
924    }
925
926    /// See `DrawObjects::read_as_storage`.
927    pub fn read_as_storage(&self, res: &mut Resources<'_>, id: usize, vertices: Option<VertexBuffer>) {
928        if let Some(objects) = res.context.mesh_mut(self) {
929            objects.read_as_storage(id, vertices);
930        }
931    }
932
933    /// See `DrawObjects::storage_buffer`.
934    #[must_use]
935    pub(crate) fn storage_buffer(&self, context: &Context, id: usize) -> Option<BufferId> {
936        context.mesh(self)?.storage_buffer(id)
937    }
938
939    /// See `DrawObjects::has_instances`.
940    #[must_use]
941    pub fn has_instances(&self, res: &Resources<'_>) -> bool {
942        res.context.mesh(self).is_some_and(DrawObjects::has_instances)
943    }
944
945    /// See `DrawObjects::texture`.
946    #[must_use]
947    pub fn texture<'r>(&self, res: &'r Resources<'_>, slot: usize) -> Option<&'r Texture> {
948        res.context.mesh(self)?.texture(slot)
949    }
950
951    /// See `DrawObjects::set_texture`.
952    pub fn set_texture(&self, res: &mut Resources<'_>, slot: usize, texture: Option<&Texture>) {
953        if let Some(objects) = res.context.mesh_mut(self) {
954            objects.set_texture(slot, texture);
955        }
956    }
957
958    /// See `DrawObjects::set_sampler`.
959    pub fn set_sampler(&self, res: &mut Resources<'_>, slot: usize, state: Option<SamplerState>) {
960        if let Some(objects) = res.context.mesh_mut(self) {
961            objects.set_sampler(slot, state);
962        }
963    }
964
965    /// Replaces the mesh's indexes and the ranges drawn of them.
966    pub fn replace_indexes(&self, res: &mut Resources<'_>, indexes: IndexBuffer, ranges: Vec<DrawRange>) {
967        if let Some(objects) = res.context.mesh_mut(self) {
968            objects.replace_indexes(DrawIndexes::Shared(indexes), ranges);
969        }
970    }
971
972    /// See `DrawObjects::set_cull_face_mode`.
973    pub fn set_cull_face_mode(&self, res: &mut Resources<'_>, cull_face_mode: CullFaceMode) {
974        if let Some(objects) = res.context.mesh_mut(self) {
975            objects.set_cull_face_mode(cull_face_mode);
976        }
977    }
978}
979
980/// The slots of the textures `program` samples.
981fn sampled_slots(program: &Program) -> impl Iterator<Item = usize> + use<> {
982    let textures = program.textures;
983    (0..textures.len()).filter(move |&slot| !textures[slot].is_unused())
984}
985
986fn fixed_state(variant: PipelineVariant, color_mode: &ColorMode, cull: CullFaceMode) -> FixedState {
987    FixedState {
988        primitive: variant.primitive,
989        cull,
990        blend: color_mode.blend_function,
991        color_mask: color_mode.mask,
992        depth: variant.depth,
993        stencil: variant.stencil,
994    }
995}
996
997/// The vertex buffers of a draw's attribute and instance bindings, which
998/// hold an attribute for each of those the shader reads, in the program's
999/// order.
1000/// Attributes that read one buffer with one stride from one offset share a
1001/// slot; attributes of a buffer at different vertex offsets (a fill
1002/// extrusion wall's outline vertex and the next one) read it through slots
1003/// of their own, since an attribute's offset must stay within the stride.
1004fn vertex_slots(
1005    program: &Program,
1006    attributes: &AttributeBindingArray,
1007    instances: &AttributeBindingArray,
1008) -> Vec<VertexSlot> {
1009    let mut slots: Vec<VertexSlot> = Vec::new();
1010    for (bindings, step) in [(attributes, VertexStep::Vertex), (instances, VertexStep::Instance)] {
1011        let (count, first) = match step {
1012            VertexStep::Vertex => (program.attributes.len(), 0),
1013            VertexStep::Instance => (program.instance_attributes.len(), program.attributes.len()),
1014        };
1015        for (index, binding) in bindings.iter().enumerate().take(count) {
1016            let Some(binding) = binding else { continue };
1017            let buffer = &binding.buffer;
1018            let offset = u64::from(binding.vertex_offset) * u64::from(binding.vertex_stride);
1019            let attribute = GpuVertexAttribute {
1020                location: (first + index) as u32,
1021                format: binding.attribute.data_type,
1022                offset: binding.attribute.offset,
1023            };
1024            let shared = slots.iter_mut().find(|slot| {
1025                slot.buffer == *buffer
1026                    && slot.layout.stride == binding.vertex_stride
1027                    && slot.layout.step == step
1028                    && slot.offset == offset
1029            });
1030            match shared {
1031                Some(slot) => slot.layout.attributes.push(attribute),
1032                None => slots.push(VertexSlot {
1033                    buffer: *buffer,
1034                    held: binding.held.clone(),
1035                    offset,
1036                    layout: VertexBufferLayout { stride: binding.vertex_stride, step, attributes: vec![attribute] },
1037                }),
1038            }
1039        }
1040    }
1041    if slots.len() > MAX_VERTEX_BUFFERS {
1042        tracing::warn!(
1043            target: log_target::RENDER,
1044            program = program.name,
1045            count = slots.len(),
1046            expected = MAX_VERTEX_BUFFERS,
1047            "A program uses more vertex buffers than the limit"
1048        );
1049        slots.truncate(MAX_VERTEX_BUFFERS);
1050    }
1051    slots
1052}