use mln_gfx::color_mode::ColorMode;
use mln_gfx::cull_face_mode::CullFaceMode;
use mln_gfx::depth_mode::DepthMode;
use mln_gfx::draw_mode::DrawMode;
use mln_gfx::gfx_types::{AttributeDataType, DrawModeType, PrimitiveType};
use mln_gfx::gpu::{
BindGroupEntry, BindingsDesc, BindingsId, BufferId, DepthState, Draw, DynamicState, FixedState, GeometryDesc,
GeometryId, Gpu, GpuError, MAX_BASE_VERTEX, PipelineId, PipelineKey, SamplerId, Scissor, ShaderId, ShaderKey,
StencilState, TargetFormats, TextureId, VertexAttribute as GpuVertexAttribute, VertexBufferLayout, VertexStep,
};
use mln_gfx::shaders::bindings::{BUFFER_IDS, MAX_TEXTURES};
use mln_gfx::shaders::program::Program;
use mln_gfx::stencil_mode::StencilMode;
use mln_gfx::texture2d::SamplerState;
use mln_style::hash::HashMap;
use smallvec::SmallVec;
use crate::draw::buffer::Buffer;
use crate::draw::context::Context;
use crate::draw::identity::SimpleIdentity;
use crate::draw::indexes::DrawIndexes;
use crate::draw::owned::{Held, Owned};
use crate::draw::range::DrawRange;
use crate::draw::resources::{Device, Resources};
use crate::draw::store::{IndexBuffer, MeshKey, Shared, Texture, WeakShared};
use crate::draw::uniform_buffer::UniformBufferArray;
use crate::draw::upload::{self, AttributeBindingArray, AttributeSlots};
use crate::draw::vertex::{VertexBinding, attributes_of, replace_attributes};
use crate::draw::vertex_attribute::VertexAttributeArray;
use crate::draw::vertices::VertexBuffer;
use crate::log_target;
use crate::render::paint_parameters::{DrawTarget, PaintParameters};
pub type Textures = [Option<Texture>; MAX_TEXTURES];
const MAX_VERTEX_BUFFERS: usize = 8;
pub(crate) struct DrawGeometry {
pub(crate) vertices: VertexAttributeArray,
pub(crate) vertex_count: usize,
pub(crate) mode: DrawMode,
pub(crate) indexes: DrawIndexes,
pub(crate) ranges: Vec<DrawRange>,
pub(crate) instances: Option<VertexAttributeArray>,
}
#[must_use]
pub(crate) fn raw_vertices(
name: &'static str,
data: Vec<u8>,
count: usize,
data_type: AttributeDataType,
) -> VertexAttributeArray {
let mut attributes = VertexAttributeArray::new();
if count == 0 || data_type == AttributeDataType::Invalid || data.is_empty() {
return attributes;
}
attributes.set_own(name, data_type, data);
attributes
}
const MAX_STORAGE_VERTICES: usize = 3;
const MAX_ENTRIES: usize = BUFFER_IDS + MAX_STORAGE_VERTICES + MAX_TEXTURES;
pub(crate) struct Entries {
entries: [BindGroupEntry; MAX_ENTRIES],
len: usize,
}
impl Entries {
pub(crate) fn new() -> Entries {
let none = BindGroupEntry::Texture { slot: 0, texture: TextureId::default(), sampler: SamplerId::default() };
Entries { entries: [none; MAX_ENTRIES], len: 0 }
}
pub(crate) fn push(&mut self, entry: BindGroupEntry) {
self.entries[self.len] = entry;
self.len += 1;
}
pub(crate) fn as_slice(&self) -> &[BindGroupEntry] {
&self.entries[..self.len]
}
}
type SegmentGeometry = (usize, Owned<GeometryId>);
#[expect(clippy::too_many_arguments, reason = "the parts of a mesh that its geometry is made of")]
fn segment_geometry(
gpu: &mut dyn Gpu,
context: &Context,
shader: ShaderId,
layouts: &[VertexBufferLayout],
slots: &[VertexSlot],
index_buffer: BufferId,
index_held: Option<Held>,
start: usize,
) -> Result<Owned<GeometryId>, GpuError> {
let mut buffers = [(BufferId::default(), 0); MAX_VERTEX_BUFFERS];
for (buffer, slot) in buffers.iter_mut().zip(slots) {
let skipped = match slot.layout.step {
VertexStep::Vertex => start as u64 * u64::from(slot.layout.stride),
VertexStep::Instance => 0,
};
*buffer = (slot.buffer, slot.offset + skipped);
}
let geometry =
gpu.create_geometry(&GeometryDesc { shader, layouts, vertex_buffers: &buffers[..slots.len()], index_buffer })?;
let len = slots.iter().filter(|slot| slot.held.is_some()).count() + usize::from(index_held.is_some());
let mut held = Vec::with_capacity(len);
held.extend(slots.iter().filter_map(|slot| slot.held.clone()).chain(index_held));
Ok(context.own(geometry, held))
}
struct VertexSlot {
buffer: BufferId,
held: Option<Held>,
offset: u64,
layout: VertexBufferLayout,
}
#[derive(Clone, Copy, PartialEq)]
struct BindingsStamp {
global: u64,
storage: u64,
textures: [Option<(TextureId, SamplerId)>; MAX_TEXTURES],
}
struct MeshBindings {
mesh: WeakShared<MeshKey>,
bindings: Owned<BindingsId>,
stamp: BindingsStamp,
}
#[derive(Default)]
pub(crate) struct DrawBuffers {
buffers: UniformBufferArray,
bindings: HashMap<SimpleIdentity, MeshBindings>,
}
impl DrawBuffers {
pub(crate) fn get(&self, id: usize) -> Option<&Buffer> {
self.buffers.get(id)
}
pub(crate) fn write_pod<T: bytemuck::Pod>(&mut self, gpu: &mut dyn Gpu, id: usize, value: &T, device: &mut Device) {
let epoch = self.buffers.epoch();
let _replaced = self.buffers.write_pod(gpu, id, value, device);
self.made(epoch);
}
pub(crate) fn write_uniform(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
let epoch = self.buffers.epoch();
let _replaced = self.buffers.write_uniform(gpu, id, data, device);
self.made(epoch);
}
pub(crate) fn write_storage(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
let epoch = self.buffers.epoch();
let _replaced = self.buffers.write_storage(gpu, id, data, device);
self.made(epoch);
}
fn made(&mut self, epoch: u64) {
if self.buffers.epoch() != epoch {
self.bindings.clear();
}
}
pub(crate) fn sweep(&mut self) {
self.bindings.retain(|_, made| made.mesh.is_held());
}
fn bindings(
&mut self,
gpu: &mut dyn Gpu,
context: &mut Context,
mesh: &DrawObjects,
shader_id: ShaderId,
) -> Result<BindingsId, GpuError> {
let program = mesh.shader.program();
let mut textures = [None; MAX_TEXTURES];
for slot in sampled_slots(program) {
if let Some(texture) = mesh.textures.get(slot).and_then(Option::as_ref) {
textures[slot] = Some(context.texture_binding(gpu, texture, mesh.samplers[slot])?);
}
}
let global = context.global_uniform_buffers();
let stamp = BindingsStamp { global: global.epoch(), storage: mesh.storage_epoch, textures };
if let Some(made) = self.bindings.get(&mesh.id)
&& made.stamp == stamp
{
return Ok(made.bindings.id());
}
self.bindings.remove(&mesh.id);
let mut entries = Entries::new();
for id in 0..BUFFER_IDS {
let buffer = self.buffers.get(id).or_else(|| global.get(id));
if let Some(buffer) = buffer {
entries.push(BindGroupEntry::Buffer {
id: id as u32,
buffer: buffer.id(),
offset: 0,
size: buffer.size() as u64,
});
}
}
let mut held = Vec::new();
for (id, vertices, buffer) in &mesh.storage_vertices {
let size = context.vertices(vertices).map_or(0, |stored| stored.count() * stored.vertex_size());
if let Some(buffer) = buffer.filter(|_| size > 0) {
entries.push(BindGroupEntry::Buffer { id: *id as u32, buffer, offset: 0, size: size as u64 });
held.push(vertices.held());
}
}
for (slot, binding) in textures.iter().enumerate() {
if let Some((texture, sampler)) = *binding {
entries.push(BindGroupEntry::Texture { slot: slot as u32, texture, sampler });
}
}
held.extend(
sampled_slots(program)
.filter_map(|slot| context.gpu_texture(mesh.textures.get(slot)?.as_ref()?).cloned().map(Held::Texture)),
);
let bindings =
gpu.create_bindings(&BindingsDesc { label: program.name, shader: shader_id, entries: entries.as_slice() })?;
let made = MeshBindings { mesh: mesh.handle.clone(), bindings: context.own(bindings, held), stamp };
self.bindings.insert(mesh.id, made);
Ok(bindings)
}
#[cfg(test)]
pub(crate) fn bind(
&mut self,
gpu: &mut dyn Gpu,
context: &mut Context,
mesh: &Mesh,
) -> Result<BindingsId, GpuError> {
let objects = context.take_mesh(mesh).ok_or(GpuError::UnknownId("mesh"))?;
let bound =
context.shader(gpu, &objects.shader).and_then(|shader| self.bindings(gpu, context, &objects, shader));
context.put_mesh(mesh, objects);
bound
}
#[cfg(test)]
pub(crate) fn bound_meshes(&self) -> usize {
self.bindings.len()
}
}
#[derive(Clone, Copy, PartialEq)]
struct PipelineVariant {
primitive: DrawModeType,
depth: DepthState,
stencil: StencilState,
targets: TargetFormats,
}
pub(crate) struct DrawObjects {
id: SimpleIdentity,
handle: WeakShared<MeshKey>,
shader: ShaderKey,
vertex_attributes: VertexAttributeArray,
instance_attributes: Option<VertexAttributeArray>,
vertex_attributes_changed: bool,
instance_attributes_changed: bool,
vertex_slots_of: AttributeSlots,
instance_slots_of: AttributeSlots,
textures: Textures,
samplers: [Option<SamplerState>; MAX_TEXTURES],
storage_vertices: Vec<(usize, VertexBuffer, Option<BufferId>)>,
storage_epoch: u64,
color_mode: ColorMode,
cull_face_mode: CullFaceMode,
mode: DrawMode,
ranges: Vec<DrawRange>,
indexes: DrawIndexes,
vertex_count: usize,
attribute_bindings: AttributeBindingArray,
instance_bindings: AttributeBindingArray,
vertex_slots: Option<Vec<VertexSlot>>,
shader_id: Option<ShaderId>,
pipelines: Vec<(PipelineVariant, PipelineId)>,
pipeline_layouts: Vec<VertexBufferLayout>,
geometry: Option<(BufferId, SmallVec<[SegmentGeometry; 1]>)>,
}
impl DrawObjects {
#[must_use]
pub(crate) fn new(
shader: ShaderKey,
color_mode: ColorMode,
cull_face_mode: CullFaceMode,
geometry: DrawGeometry,
textures: Textures,
) -> Self {
let DrawGeometry { vertices, vertex_count, mode, indexes, ranges, instances } = geometry;
DrawObjects {
id: SimpleIdentity::new(),
handle: WeakShared::default(),
shader,
vertex_attributes: vertices,
instance_attributes: instances,
vertex_attributes_changed: true,
instance_attributes_changed: true,
vertex_slots_of: AttributeSlots::default(),
instance_slots_of: AttributeSlots::default(),
textures,
samplers: [None; MAX_TEXTURES],
storage_vertices: Vec::new(),
storage_epoch: 0,
color_mode,
cull_face_mode,
mode,
ranges,
indexes,
vertex_count,
attribute_bindings: Vec::new(),
instance_bindings: Vec::new(),
vertex_slots: None,
shader_id: None,
pipelines: Vec::new(),
pipeline_layouts: Vec::new(),
geometry: None,
}
}
pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
if let Err(error) = self.upload_in(gpu, context) {
context.fail(format!("Uploading {} failed: {error}", self.shader.program().name));
}
}
fn upload_in(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<(), GpuError> {
let program = self.shader.program();
if self.indexes.buffer(context).is_none() && self.indexes.len(context) == 0 {
debug_assert!(false, "a draw of {} has no index data", program.name);
return Ok(());
}
self.indexes.upload(gpu, context)?;
if self.vertex_attributes_changed
|| upload::needs_upload(context, &self.vertex_attributes, &self.vertex_slots_of)
{
let updated = upload::update_attribute_bindings(
gpu,
context,
program.attributes,
&mut self.vertex_attributes,
&mut self.vertex_slots_of,
self.vertex_count,
&mut self.attribute_bindings,
);
if !matches!(updated, Ok(false)) {
self.vertex_slots = None;
self.geometry = None;
}
updated?;
}
let changed = self.instance_attributes_changed;
if let Some(attrs) = self
.instance_attributes
.as_mut()
.filter(|attrs| changed || upload::needs_upload(context, attrs, &self.instance_slots_of))
{
let instance_count = attrs.min_count();
let updated = upload::update_attribute_bindings(
gpu,
context,
program.instance_attributes,
attrs,
&mut self.instance_slots_of,
instance_count,
&mut self.instance_bindings,
);
if !matches!(updated, Ok(false)) {
self.vertex_slots = None;
self.geometry = None;
}
updated?;
}
self.vertex_attributes_changed = false;
self.instance_attributes_changed = false;
for (_, vertices, bound) in &mut self.storage_vertices {
let buffer = context.upload_vertices(gpu, vertices)?;
if *bound != buffer {
*bound = buffer;
self.storage_epoch += 1;
}
}
for texture in self.textures.iter().flatten() {
if let Err(error) = context.upload_texture(gpu, texture) {
context.fail(format!("Uploading a texture failed: {error}"));
}
}
Ok(())
}
#[must_use]
pub(crate) fn program(&self) -> &'static Program {
self.shader.program()
}
pub(crate) fn draw(
&mut self,
gpu: &mut dyn Gpu,
parameters: &mut PaintParameters<'_>,
frame: &mut DrawBuffers,
depth_mode: DepthMode,
stencil_mode: StencilMode,
global_index: u32,
) -> bool {
let drawn = self.draw_in(gpu, parameters, frame, depth_mode, stencil_mode, global_index);
if let Err(error) = &drawn {
parameters.context.fail(format!("Drawing {} failed: {error}", self.shader.program().name));
}
drawn.is_ok()
}
fn draw_in(
&mut self,
gpu: &mut dyn Gpu,
parameters: &mut PaintParameters<'_>,
frame: &mut DrawBuffers,
depth_mode: DepthMode,
stencil_mode: StencilMode,
global_index: u32,
) -> Result<(), GpuError> {
let Some(DrawTarget { size, targets, scissor }) = parameters.draw_target() else {
return Ok(());
};
let context = &mut *parameters.context;
let Some(index_buffer) = self.indexes.buffer(context) else {
debug_assert!(
context.device().failed(),
"a draw of {} draws indexes it didn't upload",
self.shader.program().name
);
return Err(GpuError::Invalid("its indexes aren't uploaded".to_owned()));
};
let shader_id = match self.shader_id {
Some(id) => id,
None => *self.shader_id.insert(context.shader(gpu, &self.shader)?),
};
let bindings = frame.bindings(gpu, context, self, shader_id)?;
let slots = if let Some(slots) = &self.vertex_slots {
slots
} else {
let slots = vertex_slots(self.shader.program(), &self.attribute_bindings, &self.instance_bindings);
let layouts = slots.iter().map(|slot| &slot.layout);
if !layouts.clone().eq(self.pipeline_layouts.iter()) {
self.pipeline_layouts = layouts.cloned().collect();
self.pipelines.clear();
}
self.vertex_slots.insert(slots)
};
let geometries = match &mut self.geometry {
Some((indices, geometries)) if *indices == index_buffer => geometries,
geometry => &mut geometry.insert((index_buffer, SmallVec::new())).1,
};
let full = Scissor { x: 0, y: 0, width: size.width, height: size.height };
let dynamic = DynamicState {
depth_range: depth_mode.range,
scissor: scissor.unwrap_or(full),
stencil_reference: stencil_mode.ref_ as u32,
blend_constant: self.color_mode.blend_color,
line_width: 1.0,
};
let depth = DepthState::from(&depth_mode);
let stencil = StencilState::from(&stencil_mode);
let mut draws = 0;
let mode = self.mode;
for range in &self.ranges {
if range.index_count == 0 {
continue;
}
let variant = PipelineVariant { primitive: mode.type_, depth, stencil, targets };
let pipeline = if let Some(&(_, id)) = self.pipelines.iter().find(|(cached, _)| *cached == variant) {
id
} else {
let key = PipelineKey {
shader: shader_id,
vertex_buffers: self.pipeline_layouts.clone(),
state: fixed_state(variant, &self.color_mode, self.cull_face_mode),
targets,
};
let id = context.pipeline(gpu, &key)?;
self.pipelines.push((variant, id));
id
};
let line_width = if mode.primitive_type() == PrimitiveType::Line { mode.size } else { 1.0 };
let (start, base_vertex) = if range.base_vertex <= MAX_BASE_VERTEX {
(0, range.base_vertex)
} else {
(range.base_vertex as usize, 0)
};
let geometry = if let Some((_, geometry)) = geometries.iter().find(|(at, _)| *at == start) {
geometry.id()
} else {
let geometry = segment_geometry(
gpu,
context,
shader_id,
&self.pipeline_layouts,
slots,
index_buffer,
self.indexes.held(),
start,
)?;
let id = geometry.id();
geometries.push((start, geometry));
id
};
gpu.draw(&Draw {
pipeline,
bindings,
geometry,
first_index: range.first_index,
index_count: range.index_count,
base_vertex,
first_instance: range.first_instance,
instance_count: range.instance_count,
global_index,
dynamic: DynamicState { line_width, ..dynamic },
})?;
draws += 1;
}
let stats = context.rendering_stats();
stats.num_draw_calls += draws;
stats.total_draw_calls += draws;
Ok(())
}
pub(crate) fn vertex_attributes_mut(&mut self) -> &mut VertexAttributeArray {
self.vertex_attributes_changed = true;
if self.vertex_attributes.has_own() {
self.geometry = None;
}
&mut self.vertex_attributes
}
pub(crate) fn paint_attributes_mut(&mut self) -> &mut VertexAttributeArray {
let (attributes, changed) = match &mut self.instance_attributes {
Some(instances) => (instances, &mut self.instance_attributes_changed),
None => (&mut self.vertex_attributes, &mut self.vertex_attributes_changed),
};
*changed = true;
if attributes.has_own() {
self.geometry = None;
}
attributes
}
pub(crate) fn read_as_storage(&mut self, id: usize, vertices: Option<VertexBuffer>) {
debug_assert!(id >= BUFFER_IDS, "a uniform buffer's id");
self.storage_vertices.retain(|(at, ..)| *at != id);
debug_assert!(vertices.is_none() || self.storage_vertices.len() < MAX_STORAGE_VERTICES);
if let Some(vertices) = vertices {
self.storage_vertices.push((id, vertices, None));
}
self.storage_epoch += 1;
}
pub(crate) fn storage_buffer(&self, id: usize) -> Option<BufferId> {
self.storage_vertices.iter().find(|(at, ..)| *at == id).and_then(|&(_, _, buffer)| buffer)
}
#[must_use]
pub(crate) fn has_instances(&self) -> bool {
self.instance_attributes.is_some()
}
#[must_use]
pub(crate) fn texture(&self, slot: usize) -> Option<&Texture> {
self.textures[slot].as_ref()
}
pub(crate) fn set_texture(&mut self, slot: usize, texture: Option<&Texture>) {
let bound = &mut self.textures[slot];
if bound.as_ref() != texture {
*bound = texture.cloned();
}
}
pub(crate) fn set_sampler(&mut self, slot: usize, state: Option<SamplerState>) {
self.samplers[slot] = state;
}
pub(crate) fn replace_indexes(&mut self, indexes: DrawIndexes, ranges: Vec<DrawRange>) {
if let DrawIndexes::Own(_) = self.indexes {
self.geometry = None;
}
self.indexes = indexes;
self.ranges = ranges;
}
pub(crate) fn set_cull_face_mode(&mut self, cull_face_mode: CullFaceMode) {
if self.cull_face_mode != cull_face_mode {
self.cull_face_mode = cull_face_mode;
self.pipelines.clear();
}
}
}
pub struct MeshDesc {
pub shader: ShaderKey,
pub color_mode: ColorMode,
pub cull_face_mode: CullFaceMode,
pub mode: DrawMode,
pub vertices: Vec<VertexBinding>,
pub vertex_count: usize,
pub instances: Option<Vec<VertexBinding>>,
pub indexes: IndexBuffer,
pub ranges: Vec<DrawRange>,
pub textures: Textures,
}
#[derive(Clone)]
pub struct Mesh {
key: Shared<MeshKey>,
id: SimpleIdentity,
program: &'static Program,
}
impl Mesh {
#[must_use]
pub(crate) fn of(context: &mut Context, desc: MeshDesc) -> Self {
let MeshDesc {
shader,
color_mode,
cull_face_mode,
mode,
vertices,
vertex_count,
instances,
indexes,
ranges,
textures,
} = desc;
let geometry = DrawGeometry {
vertices: attributes_of(&vertices),
vertex_count,
mode,
indexes: DrawIndexes::Shared(indexes),
ranges,
instances: instances.as_deref().map(attributes_of),
};
Mesh::new(context, shader, color_mode, cull_face_mode, geometry, textures)
}
#[must_use]
pub(crate) fn new(
context: &mut Context,
shader: ShaderKey,
color_mode: ColorMode,
cull_face_mode: CullFaceMode,
geometry: DrawGeometry,
textures: Textures,
) -> Self {
let mut objects = DrawObjects::new(shader, color_mode, cull_face_mode, geometry, textures);
let (id, program) = (objects.id, objects.program());
let key = context.add_mesh_with(|key| {
objects.handle = key.downgrade();
objects
});
Mesh { key, id, program }
}
pub(crate) fn key(&self) -> &Shared<MeshKey> {
&self.key
}
#[must_use]
pub fn seq(&self) -> i64 {
self.id.get() as i64
}
#[must_use]
pub fn program(&self) -> &'static Program {
self.program
}
pub(crate) fn update<R>(
&self,
context: &mut Context,
f: impl FnOnce(&mut DrawObjects, &mut Context) -> R,
) -> Option<R> {
let mut objects = context.take_mesh(self)?;
let result = f(&mut objects, context);
context.put_mesh(self, objects);
Some(result)
}
pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
self.update(context, |objects, context| objects.upload(gpu, context));
}
pub(crate) fn vertex_attributes_mut<'c>(&self, context: &'c mut Context) -> Option<&'c mut VertexAttributeArray> {
context.mesh_mut(self).map(DrawObjects::vertex_attributes_mut)
}
pub fn set_vertices<'b>(&self, res: &mut Resources<'_>, bindings: impl IntoIterator<Item = &'b VertexBinding>) {
if let Some(attrs) = self.vertex_attributes_mut(res.context) {
replace_attributes(attrs, bindings);
}
}
pub fn set_paint(&self, res: &mut Resources<'_>, paint: &VertexBinding) {
if let Some(objects) = res.context.mesh_mut(self) {
paint.bind(objects.paint_attributes_mut());
}
}
pub fn read_as_storage(&self, res: &mut Resources<'_>, id: usize, vertices: Option<VertexBuffer>) {
if let Some(objects) = res.context.mesh_mut(self) {
objects.read_as_storage(id, vertices);
}
}
#[must_use]
pub(crate) fn storage_buffer(&self, context: &Context, id: usize) -> Option<BufferId> {
context.mesh(self)?.storage_buffer(id)
}
#[must_use]
pub fn has_instances(&self, res: &Resources<'_>) -> bool {
res.context.mesh(self).is_some_and(DrawObjects::has_instances)
}
#[must_use]
pub fn texture<'r>(&self, res: &'r Resources<'_>, slot: usize) -> Option<&'r Texture> {
res.context.mesh(self)?.texture(slot)
}
pub fn set_texture(&self, res: &mut Resources<'_>, slot: usize, texture: Option<&Texture>) {
if let Some(objects) = res.context.mesh_mut(self) {
objects.set_texture(slot, texture);
}
}
pub fn set_sampler(&self, res: &mut Resources<'_>, slot: usize, state: Option<SamplerState>) {
if let Some(objects) = res.context.mesh_mut(self) {
objects.set_sampler(slot, state);
}
}
pub fn replace_indexes(&self, res: &mut Resources<'_>, indexes: IndexBuffer, ranges: Vec<DrawRange>) {
if let Some(objects) = res.context.mesh_mut(self) {
objects.replace_indexes(DrawIndexes::Shared(indexes), ranges);
}
}
pub fn set_cull_face_mode(&self, res: &mut Resources<'_>, cull_face_mode: CullFaceMode) {
if let Some(objects) = res.context.mesh_mut(self) {
objects.set_cull_face_mode(cull_face_mode);
}
}
}
fn sampled_slots(program: &Program) -> impl Iterator<Item = usize> + use<> {
let textures = program.textures;
(0..textures.len()).filter(move |&slot| !textures[slot].is_unused())
}
fn fixed_state(variant: PipelineVariant, color_mode: &ColorMode, cull: CullFaceMode) -> FixedState {
FixedState {
primitive: variant.primitive,
cull,
blend: color_mode.blend_function,
color_mask: color_mode.mask,
depth: variant.depth,
stencil: variant.stencil,
}
}
fn vertex_slots(
program: &Program,
attributes: &AttributeBindingArray,
instances: &AttributeBindingArray,
) -> Vec<VertexSlot> {
let mut slots: Vec<VertexSlot> = Vec::new();
for (bindings, step) in [(attributes, VertexStep::Vertex), (instances, VertexStep::Instance)] {
let (count, first) = match step {
VertexStep::Vertex => (program.attributes.len(), 0),
VertexStep::Instance => (program.instance_attributes.len(), program.attributes.len()),
};
for (index, binding) in bindings.iter().enumerate().take(count) {
let buffer = &binding.buffer;
let offset = u64::from(binding.vertex_offset) * u64::from(binding.vertex_stride);
let attribute = GpuVertexAttribute {
location: (first + index) as u32,
format: binding.attribute.data_type,
offset: binding.attribute.offset,
};
let shared = slots.iter_mut().find(|slot| {
slot.buffer == *buffer
&& slot.layout.stride == binding.vertex_stride
&& slot.layout.step == step
&& slot.offset == offset
});
match shared {
Some(slot) => slot.layout.attributes.push(attribute),
None => slots.push(VertexSlot {
buffer: *buffer,
held: binding.held.clone(),
offset,
layout: VertexBufferLayout { stride: binding.vertex_stride, step, attributes: vec![attribute] },
}),
}
}
}
if slots.len() > MAX_VERTEX_BUFFERS {
log::warn!(
target: log_target::RENDER,
"{} uses {} vertex buffers, exceeding the limit of {MAX_VERTEX_BUFFERS}",
program.name,
slots.len()
);
slots.truncate(MAX_VERTEX_BUFFERS);
}
slots
}