1use 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, PipelineId, PipelineKey, SamplerId, Scissor, ShaderId, ShaderKey, StencilState,
24 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_style::hash::HashMap;
30
31use crate::draw::atlas_binding::AtlasBinding;
32use crate::draw::buffer::Buffer;
33use crate::draw::context::Context;
34use crate::draw::identity::SimpleIdentity;
35use crate::draw::indexes::DrawIndexes;
36use crate::draw::owned::{Held, Owned};
37use crate::draw::resources::Device;
38use crate::draw::segment::SegmentBase;
39use crate::draw::store::{MeshKey, Shared, SharedTexture, WeakShared};
40use crate::draw::uniform_buffer::UniformBufferArray;
41use crate::draw::upload::{self, AttributeBindingArray, AttributeSlots};
42use crate::draw::vertex_attribute::VertexAttributeArray;
43use crate::draw::vertices::SharedVertices;
44use crate::log_target;
45use crate::render::paint_parameters::{DrawTarget, PaintParameters};
46
47pub type Textures = [Option<SharedTexture>; MAX_TEXTURES];
49
50const MAX_VERTEX_BUFFERS: usize = 8;
52
53pub struct DrawGeometry {
56 pub vertices: VertexAttributeArray,
58 pub vertex_count: usize,
61 pub mode: DrawMode,
63 pub indexes: DrawIndexes,
64 pub segments: Vec<SegmentBase>,
66 pub instances: Option<VertexAttributeArray>,
68}
69
70#[must_use]
73pub fn raw_vertices(
74 name: &'static str,
75 data: Vec<u8>,
76 count: usize,
77 data_type: AttributeDataType,
78) -> VertexAttributeArray {
79 let mut attributes = VertexAttributeArray::new();
80 if count == 0 || data_type == AttributeDataType::Invalid || data.is_empty() {
81 return attributes;
82 }
83 attributes.set_own(name, data_type, data);
84 attributes
85}
86
87const MAX_STORAGE_VERTICES: usize = 3;
89
90const MAX_ENTRIES: usize = BUFFER_IDS + MAX_STORAGE_VERTICES + MAX_TEXTURES;
92
93pub(crate) struct Entries {
97 entries: [BindGroupEntry; MAX_ENTRIES],
98 len: usize,
99}
100
101impl Entries {
102 pub(crate) fn new() -> Entries {
103 let none = BindGroupEntry::Texture { slot: 0, texture: TextureId::default(), sampler: SamplerId::default() };
104 Entries { entries: [none; MAX_ENTRIES], len: 0 }
105 }
106
107 pub(crate) fn push(&mut self, entry: BindGroupEntry) {
108 self.entries[self.len] = entry;
109 self.len += 1;
110 }
111
112 pub(crate) fn as_slice(&self) -> &[BindGroupEntry] {
113 &self.entries[..self.len]
114 }
115}
116
117struct VertexSlot {
120 buffer: BufferId,
121 held: Option<Held>,
122 offset: u64,
123 layout: VertexBufferLayout,
124}
125
126#[derive(Clone, Copy, PartialEq)]
131struct BindingsStamp {
132 global: u64,
133 storage: u64,
134 textures: [Option<(TextureId, SamplerId)>; MAX_TEXTURES],
135}
136
137struct MeshBindings {
139 mesh: WeakShared<MeshKey>,
140 bindings: Owned<BindingsId>,
141 stamp: BindingsStamp,
142}
143
144#[derive(Default)]
151pub(crate) struct DrawBuffers {
152 buffers: UniformBufferArray,
153 bindings: HashMap<SimpleIdentity, MeshBindings>,
154}
155
156impl DrawBuffers {
157 pub(crate) fn get(&self, id: usize) -> Option<&Buffer> {
159 self.buffers.get(id)
160 }
161
162 pub(crate) fn write_pod<T: bytemuck::Pod>(&mut self, gpu: &mut dyn Gpu, id: usize, value: &T, device: &mut Device) {
165 let epoch = self.buffers.epoch();
166 let _replaced = self.buffers.write_pod(gpu, id, value, device);
167 self.made(epoch);
168 }
169
170 pub(crate) fn write_uniform(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
173 let epoch = self.buffers.epoch();
174 let _replaced = self.buffers.write_uniform(gpu, id, data, device);
175 self.made(epoch);
176 }
177
178 pub(crate) fn write_storage(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
181 let epoch = self.buffers.epoch();
182 let _replaced = self.buffers.write_storage(gpu, id, data, device);
183 self.made(epoch);
184 }
185
186 fn made(&mut self, epoch: u64) {
189 if self.buffers.epoch() != epoch {
190 self.bindings.clear();
191 }
192 }
193
194 pub(crate) fn sweep(&mut self) {
196 self.bindings.retain(|_, made| made.mesh.is_held());
197 }
198
199 fn bindings(
204 &mut self,
205 gpu: &mut dyn Gpu,
206 context: &mut Context,
207 mesh: &DrawObjects,
208 shader_id: ShaderId,
209 ) -> Result<BindingsId, GpuError> {
210 let program = mesh.shader.program();
211 let mut textures = [None; MAX_TEXTURES];
212 for slot in sampled_slots(program) {
213 if let Some(texture) = mesh.textures.get(slot).and_then(Option::as_ref) {
214 textures[slot] = Some(context.texture_binding(gpu, texture)?);
215 }
216 }
217 let global = context.global_uniform_buffers();
218 let stamp = BindingsStamp { global: global.epoch(), storage: mesh.storage_epoch, textures };
219 if let Some(made) = self.bindings.get(&mesh.id)
220 && made.stamp == stamp
221 {
222 return Ok(made.bindings.id());
223 }
224 self.bindings.remove(&mesh.id);
225 let mut entries = Entries::new();
226 for id in 0..BUFFER_IDS {
227 let buffer = self.buffers.get(id).or_else(|| global.get(id));
229 if let Some(buffer) = buffer {
230 entries.push(BindGroupEntry::Buffer {
231 id: id as u32,
232 buffer: buffer.id(),
233 offset: 0,
234 size: buffer.size() as u64,
235 });
236 }
237 }
238 let mut held = Vec::new();
239 for (id, vertices, buffer) in &mesh.storage_vertices {
240 let size = context.vertices(vertices).map_or(0, |stored| stored.count() * stored.vertex_size());
241 if let Some(buffer) = buffer.filter(|_| size > 0) {
242 entries.push(BindGroupEntry::Buffer { id: *id as u32, buffer, offset: 0, size: size as u64 });
243 held.push(vertices.held());
244 }
245 }
246 for (slot, binding) in textures.iter().enumerate() {
247 if let Some((texture, sampler)) = *binding {
248 entries.push(BindGroupEntry::Texture { slot: slot as u32, texture, sampler });
249 }
250 }
251 held.extend(
252 sampled_slots(program)
253 .filter_map(|slot| context.gpu_texture(mesh.textures.get(slot)?.as_ref()?).cloned().map(Held::Texture)),
254 );
255 let bindings =
256 gpu.create_bindings(&BindingsDesc { label: program.name, shader: shader_id, entries: entries.as_slice() })?;
257 let made = MeshBindings { mesh: mesh.handle.clone(), bindings: context.own(bindings, held), stamp };
258 self.bindings.insert(mesh.id, made);
259 Ok(bindings)
260 }
261
262 #[cfg(test)]
264 pub(crate) fn bind(
265 &mut self,
266 gpu: &mut dyn Gpu,
267 context: &mut Context,
268 mesh: &Mesh,
269 ) -> Result<BindingsId, GpuError> {
270 let objects = context.take_mesh(mesh).ok_or(GpuError::UnknownId("mesh"))?;
271 let bound =
272 context.shader(gpu, &objects.shader).and_then(|shader| self.bindings(gpu, context, &objects, shader));
273 context.put_mesh(mesh, objects);
274 bound
275 }
276
277 #[cfg(test)]
279 pub(crate) fn bound_meshes(&self) -> usize {
280 self.bindings.len()
281 }
282}
283
284#[derive(Clone, Copy, PartialEq)]
286struct PipelineVariant {
287 primitive: DrawModeType,
288 depth: DepthState,
289 stencil: StencilState,
290 targets: TargetFormats,
291}
292
293pub(crate) struct DrawObjects {
300 id: SimpleIdentity,
303 handle: WeakShared<MeshKey>,
306 shader: ShaderKey,
307 vertex_attributes: VertexAttributeArray,
308 instance_attributes: Option<VertexAttributeArray>,
310 vertex_attributes_changed: bool,
313 instance_attributes_changed: bool,
316 vertex_slots_of: AttributeSlots,
319 instance_slots_of: AttributeSlots,
320 textures: Textures,
322 storage_vertices: Vec<(usize, SharedVertices, Option<BufferId>)>,
326 storage_epoch: u64,
328 color_mode: ColorMode,
329 cull_face_mode: CullFaceMode,
330
331 mode: DrawMode,
332 segments: Vec<SegmentBase>,
333 indexes: DrawIndexes,
334 vertex_count: usize,
335 attribute_bindings: AttributeBindingArray,
336 instance_bindings: AttributeBindingArray,
337 vertex_slots: Option<Vec<VertexSlot>>,
340 shader_id: Option<ShaderId>,
342 pipelines: Vec<(PipelineVariant, PipelineId)>,
345 pipeline_layouts: Vec<VertexBufferLayout>,
348 geometry: Option<(Owned<GeometryId>, BufferId)>,
351 atlases: Option<AtlasBinding>,
353}
354
355impl DrawObjects {
356 #[must_use]
359 pub(crate) fn new(
360 shader: ShaderKey,
361 color_mode: ColorMode,
362 cull_face_mode: CullFaceMode,
363 geometry: DrawGeometry,
364 textures: Textures,
365 ) -> Self {
366 let DrawGeometry { vertices, vertex_count, mode, indexes, segments, instances } = geometry;
367 DrawObjects {
368 id: SimpleIdentity::new(),
369 handle: WeakShared::default(),
370 shader,
371 vertex_attributes: vertices,
372 instance_attributes: instances,
373 vertex_attributes_changed: true,
374 instance_attributes_changed: true,
375 vertex_slots_of: AttributeSlots::default(),
376 instance_slots_of: AttributeSlots::default(),
377 textures,
378 storage_vertices: Vec::new(),
379 storage_epoch: 0,
380 color_mode,
381 cull_face_mode,
382 mode,
383 segments,
384 indexes,
385 vertex_count,
386 attribute_bindings: Vec::new(),
387 instance_bindings: Vec::new(),
388 vertex_slots: None,
389 shader_id: None,
390 pipelines: Vec::new(),
391 pipeline_layouts: Vec::new(),
392 geometry: None,
393 atlases: None,
394 }
395 }
396
397 pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
400 if let Err(error) = self.upload_in(gpu, context) {
401 context.fail(format!("Uploading {} failed: {error}", self.shader.program().name));
402 }
403 }
404
405 fn upload_in(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<(), GpuError> {
406 let program = self.shader.program();
407 if self.indexes.buffer(context).is_none() && self.indexes.len(context) == 0 {
408 debug_assert!(false, "a draw of {} has no index data", program.name);
409 return Ok(());
410 }
411 self.indexes.upload(gpu, context)?;
412
413 if self.vertex_attributes_changed
417 || upload::needs_upload(context, &self.vertex_attributes, &self.vertex_slots_of)
418 {
419 let updated = upload::update_attribute_bindings(
420 gpu,
421 context,
422 program.attributes,
423 &mut self.vertex_attributes,
424 &mut self.vertex_slots_of,
425 self.vertex_count,
426 &mut self.attribute_bindings,
427 );
428 if !matches!(updated, Ok(false)) {
429 self.vertex_slots = None;
430 self.geometry = None;
431 }
432 updated?;
433 }
434
435 let changed = self.instance_attributes_changed;
436 if let Some(attrs) = self
437 .instance_attributes
438 .as_mut()
439 .filter(|attrs| changed || upload::needs_upload(context, attrs, &self.instance_slots_of))
440 {
441 let instance_count = attrs.min_count();
442 let updated = upload::update_attribute_bindings(
443 gpu,
444 context,
445 program.instance_attributes,
446 attrs,
447 &mut self.instance_slots_of,
448 instance_count,
449 &mut self.instance_bindings,
450 );
451 if !matches!(updated, Ok(false)) {
452 self.vertex_slots = None;
453 self.geometry = None;
454 }
455 updated?;
456 }
457
458 self.vertex_attributes_changed = false;
459 self.instance_attributes_changed = false;
460
461 for (_, vertices, bound) in &mut self.storage_vertices {
462 let buffer = context.upload_vertices(gpu, vertices)?;
463 if *bound != buffer {
464 *bound = buffer;
465 self.storage_epoch += 1;
466 }
467 }
468
469 for texture in self.textures.iter().flatten() {
470 if let Err(error) = context.upload_texture(gpu, texture) {
471 context.fail(format!("Uploading a texture failed: {error}"));
472 }
473 }
474
475 Ok(())
476 }
477
478 #[must_use]
480 pub(crate) fn program(&self) -> &'static Program {
481 self.shader.program()
482 }
483
484 pub(crate) fn draw(
491 &mut self,
492 gpu: &mut dyn Gpu,
493 parameters: &mut PaintParameters<'_>,
494 frame: &mut DrawBuffers,
495 depth_mode: DepthMode,
496 stencil_mode: StencilMode,
497 global_index: u32,
498 ) -> bool {
499 if let Some(atlases) = self.atlases.take() {
500 atlases.bind(self, parameters);
501 self.atlases = Some(atlases);
502 }
503 let drawn = self.draw_in(gpu, parameters, frame, depth_mode, stencil_mode, global_index);
504 if let Err(error) = &drawn {
505 parameters.context.fail(format!("Drawing {} failed: {error}", self.shader.program().name));
506 }
507 drawn.is_ok()
508 }
509
510 fn draw_in(
511 &mut self,
512 gpu: &mut dyn Gpu,
513 parameters: &mut PaintParameters<'_>,
514 frame: &mut DrawBuffers,
515 depth_mode: DepthMode,
516 stencil_mode: StencilMode,
517 global_index: u32,
518 ) -> Result<(), GpuError> {
519 let Some(DrawTarget { size, targets, scissor }) = parameters.draw_target() else {
520 return Ok(());
521 };
522 let context = &mut *parameters.context;
523 let Some(index_buffer) = self.indexes.buffer(context) else {
524 debug_assert!(
527 context.device().failed(),
528 "a draw of {} draws indexes it didn't upload",
529 self.shader.program().name
530 );
531 return Err(GpuError::Invalid("its indexes aren't uploaded".to_owned()));
532 };
533
534 let shader_id = match self.shader_id {
535 Some(id) => id,
536 None => *self.shader_id.insert(context.shader(gpu, &self.shader)?),
537 };
538 let bindings = frame.bindings(gpu, context, self, shader_id)?;
539 let slots = if let Some(slots) = &self.vertex_slots {
540 slots
541 } else {
542 let slots = vertex_slots(self.shader.program(), &self.attribute_bindings, &self.instance_bindings);
543 let layouts = slots.iter().map(|slot| &slot.layout);
546 if !layouts.clone().eq(self.pipeline_layouts.iter()) {
547 self.pipeline_layouts = layouts.cloned().collect();
548 self.pipelines.clear();
549 }
550 self.vertex_slots.insert(slots)
551 };
552 let geometry = match &self.geometry {
553 Some((geometry, indices)) if *indices == index_buffer => geometry.id(),
554 _ => {
555 self.geometry = None;
556 let mut buffers = [(BufferId::default(), 0); MAX_VERTEX_BUFFERS];
558 for (buffer, slot) in buffers.iter_mut().zip(slots) {
559 *buffer = (slot.buffer, slot.offset);
560 }
561 let geometry = gpu.create_geometry(&GeometryDesc {
562 shader: shader_id,
563 layouts: &self.pipeline_layouts,
564 vertex_buffers: &buffers[..slots.len()],
565 index_buffer,
566 })?;
567 let index_held = self.indexes.held();
568 let len = slots.iter().filter(|slot| slot.held.is_some()).count() + usize::from(index_held.is_some());
570 let mut held = Vec::with_capacity(len);
571 held.extend(slots.iter().filter_map(|slot| slot.held.clone()).chain(index_held));
572 self.geometry = Some((context.own(geometry, held), index_buffer));
573 geometry
574 }
575 };
576
577 let full = Scissor { x: 0, y: 0, width: size.width, height: size.height };
578 let dynamic = DynamicState {
579 depth_range: depth_mode.range,
580 scissor: scissor.unwrap_or(full),
581 stencil_reference: stencil_mode.ref_ as u32,
582 blend_constant: self.color_mode.blend_color,
583 line_width: 1.0,
584 };
585 let depth = DepthState::from(&depth_mode);
586 let stencil = StencilState::from(&stencil_mode);
587 let mut draws = 0;
588 let mode = self.mode;
589 for segment in &self.segments {
590 if segment.index_length == 0 {
591 continue;
592 }
593 let variant = PipelineVariant { primitive: mode.type_, depth, stencil, targets };
594 let pipeline = if let Some(&(_, id)) = self.pipelines.iter().find(|(cached, _)| *cached == variant) {
595 id
596 } else {
597 let key = PipelineKey {
598 shader: shader_id,
599 vertex_buffers: self.pipeline_layouts.clone(),
600 state: fixed_state(variant, &self.color_mode, self.cull_face_mode),
601 targets,
602 };
603 let id = context.pipeline(gpu, &key)?;
604 self.pipelines.push((variant, id));
605 id
606 };
607 let line_width = if mode.primitive_type() == PrimitiveType::Line { mode.size } else { 1.0 };
608 gpu.draw(&Draw {
609 pipeline,
610 bindings,
611 geometry,
612 first_index: segment.index_offset as u32,
613 index_count: segment.index_length as u32,
614 base_vertex: segment.vertex_offset as i32,
615 first_instance: segment.base_instance as u32,
616 instance_count: segment.instance_count as u32,
617 global_index,
618 dynamic: DynamicState { line_width, ..dynamic },
619 })?;
620 draws += 1;
621 }
622 let stats = context.rendering_stats();
623 stats.num_draw_calls += draws;
624 stats.total_draw_calls += draws;
625 Ok(())
626 }
627
628 pub(crate) fn vertex_attributes_mut(&mut self) -> &mut VertexAttributeArray {
632 self.vertex_attributes_changed = true;
633 if self.vertex_attributes.has_own() {
634 self.geometry = None;
635 }
636 &mut self.vertex_attributes
637 }
638
639 pub(crate) fn paint_attributes_mut(&mut self) -> &mut VertexAttributeArray {
643 let (attributes, changed) = match &mut self.instance_attributes {
644 Some(instances) => (instances, &mut self.instance_attributes_changed),
645 None => (&mut self.vertex_attributes, &mut self.vertex_attributes_changed),
646 };
647 *changed = true;
648 if attributes.has_own() {
649 self.geometry = None;
650 }
651 attributes
652 }
653
654 pub(crate) fn read_as_storage(&mut self, id: usize, vertices: Option<SharedVertices>) {
659 debug_assert!(id >= BUFFER_IDS, "a uniform buffer's id");
660 self.storage_vertices.retain(|(at, ..)| *at != id);
661 debug_assert!(vertices.is_none() || self.storage_vertices.len() < MAX_STORAGE_VERTICES);
662 if let Some(vertices) = vertices {
663 self.storage_vertices.push((id, vertices, None));
664 }
665 self.storage_epoch += 1;
666 }
667
668 pub(crate) fn storage_buffer(&self, id: usize) -> Option<BufferId> {
671 self.storage_vertices.iter().find(|(at, ..)| *at == id).and_then(|&(_, _, buffer)| buffer)
672 }
673
674 #[must_use]
676 pub(crate) fn has_instances(&self) -> bool {
677 self.instance_attributes.is_some()
678 }
679
680 #[must_use]
682 pub(crate) fn texture(&self, slot: usize) -> Option<&SharedTexture> {
683 self.textures[slot].as_ref()
684 }
685
686 pub(crate) fn set_texture(&mut self, slot: usize, texture: Option<&SharedTexture>) {
689 let bound = &mut self.textures[slot];
690 if bound.as_ref() != texture {
691 *bound = texture.cloned();
692 }
693 }
694
695 pub(crate) fn replace_indexes(&mut self, indexes: DrawIndexes, segments: Vec<SegmentBase>) {
697 if let DrawIndexes::Own(_) = self.indexes {
698 self.geometry = None;
699 }
700 self.indexes = indexes;
701 self.segments = segments;
702 }
703
704 pub(crate) fn set_cull_face_mode(&mut self, cull_face_mode: CullFaceMode) {
706 if self.cull_face_mode != cull_face_mode {
707 self.cull_face_mode = cull_face_mode;
708 self.pipelines.clear();
710 }
711 }
712
713 #[must_use]
714 pub(crate) fn shader(&self) -> &ShaderKey {
715 &self.shader
716 }
717}
718
719#[derive(Clone)]
729pub struct Mesh {
730 key: Shared<MeshKey>,
731 id: SimpleIdentity,
732 program: &'static Program,
733}
734
735impl Mesh {
736 #[must_use]
739 pub fn new(
740 context: &mut Context,
741 shader: ShaderKey,
742 color_mode: ColorMode,
743 cull_face_mode: CullFaceMode,
744 geometry: DrawGeometry,
745 textures: Textures,
746 ) -> Self {
747 let mut objects = DrawObjects::new(shader, color_mode, cull_face_mode, geometry, textures);
748 let (id, program) = (objects.id, objects.program());
749 let key = context.add_mesh_with(|key| {
750 objects.handle = key.downgrade();
751 objects
752 });
753 Mesh { key, id, program }
754 }
755
756 pub(crate) fn key(&self) -> &Shared<MeshKey> {
758 &self.key
759 }
760
761 #[must_use]
764 pub fn seq(&self) -> i64 {
765 self.id.get() as i64
766 }
767
768 #[must_use]
770 pub(crate) fn program(&self) -> &'static Program {
771 self.program
772 }
773
774 pub(crate) fn update<R>(
777 &self,
778 context: &mut Context,
779 f: impl FnOnce(&mut DrawObjects, &mut Context) -> R,
780 ) -> Option<R> {
781 let mut objects = context.take_mesh(self)?;
782 let result = f(&mut objects, context);
783 context.put_mesh(self, objects);
784 Some(result)
785 }
786
787 pub fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
789 self.update(context, |objects, context| objects.upload(gpu, context));
790 }
791
792 pub fn update_vertex_attributes<R>(
796 &self,
797 context: &mut Context,
798 f: impl FnOnce(&mut VertexAttributeArray, &mut Context) -> R,
799 ) -> Option<R> {
800 self.update(context, |objects, context| f(objects.vertex_attributes_mut(), context))
801 }
802
803 pub(crate) fn vertex_attributes_mut<'c>(&self, context: &'c mut Context) -> Option<&'c mut VertexAttributeArray> {
805 context.mesh_mut(self).map(DrawObjects::vertex_attributes_mut)
806 }
807
808 pub fn paint_attributes_mut<'c>(&self, context: &'c mut Context) -> Option<&'c mut VertexAttributeArray> {
810 context.mesh_mut(self).map(DrawObjects::paint_attributes_mut)
811 }
812
813 pub fn read_as_storage(&self, context: &mut Context, id: usize, vertices: Option<SharedVertices>) {
815 if let Some(objects) = context.mesh_mut(self) {
816 objects.read_as_storage(id, vertices);
817 }
818 }
819
820 #[must_use]
822 pub fn storage_buffer(&self, context: &Context, id: usize) -> Option<BufferId> {
823 context.mesh(self)?.storage_buffer(id)
824 }
825
826 #[must_use]
828 pub fn has_instances(&self, context: &Context) -> bool {
829 context.mesh(self).is_some_and(DrawObjects::has_instances)
830 }
831
832 pub fn share_vertex_attributes(&self, context: &mut Context, other: &Mesh) {
835 if self.key == other.key {
836 return;
837 }
838 let Some(copy) = context.mesh(other).map(|other| copy_shared_attributes(&other.vertex_attributes)) else {
839 return;
840 };
841 if let Some(objects) = context.mesh_mut(self) {
842 *objects.vertex_attributes_mut() = copy;
843 }
844 }
845
846 #[must_use]
848 pub fn texture<'c>(&self, context: &'c Context, slot: usize) -> Option<&'c SharedTexture> {
849 context.mesh(self)?.texture(slot)
850 }
851
852 pub fn set_texture(&self, context: &mut Context, slot: usize, texture: Option<&SharedTexture>) {
854 if let Some(objects) = context.mesh_mut(self) {
855 objects.set_texture(slot, texture);
856 }
857 }
858
859 pub fn replace_indexes(&self, context: &mut Context, indexes: DrawIndexes, segments: Vec<SegmentBase>) {
861 if let Some(objects) = context.mesh_mut(self) {
862 objects.replace_indexes(indexes, segments);
863 }
864 }
865
866 pub fn set_cull_face_mode(&self, context: &mut Context, cull_face_mode: CullFaceMode) {
868 if let Some(objects) = context.mesh_mut(self) {
869 objects.set_cull_face_mode(cull_face_mode);
870 }
871 }
872
873 pub fn set_atlases(&self, context: &mut Context, atlases: Option<AtlasBinding>) {
876 if let Some(objects) = context.mesh_mut(self) {
877 objects.atlases = atlases;
878 }
879 }
880}
881
882fn sampled_slots(program: &Program) -> impl Iterator<Item = usize> + use<> {
884 let textures = program.textures;
885 (0..textures.len()).filter(move |&slot| !textures[slot].is_unused())
886}
887
888#[must_use]
892pub fn copy_shared_attributes(attrs: &VertexAttributeArray) -> VertexAttributeArray {
893 let mut copy = VertexAttributeArray::new();
894 for (name, attr) in attrs.iter() {
895 debug_assert!(attr.shared().is_some(), "a copied attribute has values of its own");
896 if let Some(shared) = attr.shared() {
897 copy.set_shared(name, shared.clone());
898 }
899 }
900 copy
901}
902
903fn fixed_state(variant: PipelineVariant, color_mode: &ColorMode, cull: CullFaceMode) -> FixedState {
904 FixedState {
905 primitive: variant.primitive,
906 cull,
907 blend: color_mode.blend_function,
908 color_mask: color_mode.mask,
909 depth: variant.depth,
910 stencil: variant.stencil,
911 }
912}
913
914fn vertex_slots(
921 program: &Program,
922 attributes: &AttributeBindingArray,
923 instances: &AttributeBindingArray,
924) -> Vec<VertexSlot> {
925 let mut slots: Vec<VertexSlot> = Vec::new();
926 for (bindings, step) in [(attributes, VertexStep::Vertex), (instances, VertexStep::Instance)] {
927 let (count, first) = match step {
928 VertexStep::Vertex => (program.attributes.len(), 0),
929 VertexStep::Instance => (program.instance_attributes.len(), program.attributes.len()),
930 };
931 for (index, binding) in bindings.iter().enumerate().take(count) {
932 let buffer = &binding.buffer;
933 let offset = u64::from(binding.vertex_offset) * u64::from(binding.vertex_stride);
934 let attribute = GpuVertexAttribute {
935 location: (first + index) as u32,
936 format: binding.attribute.data_type,
937 offset: binding.attribute.offset,
938 };
939 let shared = slots.iter_mut().find(|slot| {
940 slot.buffer == *buffer
941 && slot.layout.stride == binding.vertex_stride
942 && slot.layout.step == step
943 && slot.offset == offset
944 });
945 match shared {
946 Some(slot) => slot.layout.attributes.push(attribute),
947 None => slots.push(VertexSlot {
948 buffer: *buffer,
949 held: binding.held.clone(),
950 offset,
951 layout: VertexBufferLayout { stride: binding.vertex_stride, step, attributes: vec![attribute] },
952 }),
953 }
954 }
955 }
956 if slots.len() > MAX_VERTEX_BUFFERS {
957 log::warn!(
958 target: log_target::RENDER,
959 "{} uses {} vertex buffers, exceeding the limit of {MAX_VERTEX_BUFFERS}",
960 program.name,
961 slots.len()
962 );
963 slots.truncate(MAX_VERTEX_BUFFERS);
964 }
965 slots
966}