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