Skip to main content

mln_engine/render/
layer_composite.rs

1//! Layers drawn as a whole: a layer with `fill-layer-opacity` or
2//! `line-layer-opacity` below 1, or with a `*-layer-blend` other than
3//! `normal`, draws into a texture of the frame's size, which is then
4//! composited onto the frame with that opacity and blend. Its features
5//! overlap within the texture as they would on the frame, so the opacity and
6//! blend apply once to the layer rather than to each feature.
7//!
8//! A translucent fill extrusion layer draws the same way, opaque, where the
9//! texture's pass can test and write the frame's depth: the nearest of its
10//! surfaces then covers each pixel once, behind and in front of the other
11//! layers' 3D geometry as on the frame.
12//!
13//! `screen` and `plus-lighter` are blend functions. The other blends are
14//! computed in the shader against the backdrop, which a pass can't sample
15//! while it draws into it: a frame with such a layer draws into a texture of
16//! its own, copied into a second texture before each such layer and onto the
17//! frame's target at the end.
18
19use mln_gfx::color_mode::{BlendFunction, LinearBlend};
20use mln_gfx::gpu::{
21    BindGroupEntry, BindingsDesc, BindingsId, BufferUsage, ColorAttachment, DepthState, DepthStencilAttachment, Draw,
22    DynamicState, FixedState, GeometryDesc, GeometryId, Gpu, GpuError, LoadOp, PipelineKey, SamplerId, Scissor,
23    ShaderId, ShaderKey, StencilState, TargetFormats, TextureDesc, TextureFormat, TextureId, TextureUsage,
24    VertexAttribute, VertexBufferLayout, VertexStep,
25};
26use mln_gfx::projection_variant::ProjectionVariant;
27use mln_gfx::shaders::bindings::{BUFFER_IDS, PROJECTION_ID};
28use mln_gfx::shaders::layer_ubo::ProjectionUBO;
29use mln_gfx::texture2d::SamplerState;
30use mln_gfx::types::ColorBlendFactorType;
31use mln_gfx::{AttributeDataType, ColorMode, CullFaceMode, DepthMode, DrawModeType, Rgba, Size, StencilMode};
32use mln_style::types::LayerBlendType;
33
34use crate::draw::buffer::Buffer;
35use crate::draw::context::Context;
36use crate::draw::identity::SimpleIdentity;
37use crate::draw::objects::Entries;
38use crate::draw::owned::Owned;
39use crate::draw::resources::{GpuTexture, attachment_bytes};
40use crate::draw::vertex_attribute::Uniforms;
41use crate::render::paint_parameters::{DrawTarget, OpenPass};
42use crate::render::static_data::RenderStaticData;
43use crate::shaders::programs;
44use crate::shaders::ubo::{LayerCompositeBlendMode, LayerCompositeUBO};
45
46/// The ids of the buffers that the draws bind.
47const PROPS_ID: usize = programs::LAYER_COMPOSITE.buffer_id("props");
48
49/// The format of the texture a composited layer draws into: its colors are
50/// premultiplied, as the frame's are.
51const COLOR: TextureFormat = TextureFormat::Rgba8Unorm;
52/// The format of its depth and stencil, which the layer's tile clipping and
53/// depth tests read as they would the frame's.
54const DEPTH_STENCIL: TextureFormat = TextureFormat::Depth24PlusStencil8;
55
56/// The slots of the layer's texture and of the frame's behind it.
57const IMAGE_SLOT: usize = programs::LAYER_COMPOSITE.texture_slot("image");
58const BACKDROP_SLOT: usize = programs::LAYER_COMPOSITE.texture_slot("backdrop");
59
60/// The vertex layout of the quad that covers the frame: a corner of the unit
61/// square in two shorts.
62fn layout() -> VertexBufferLayout {
63    VertexBufferLayout {
64        stride: 4,
65        step: VertexStep::Vertex,
66        attributes: vec![VertexAttribute {
67            location: const { programs::LAYER_COMPOSITE.location("pos") as u32 },
68            format: AttributeDataType::Short2,
69            offset: 0,
70        }],
71    }
72}
73
74/// How a draw group's draws composite onto the frame, after they draw
75/// into a texture of their own.
76#[derive(Clone, Copy, Debug, PartialEq)]
77pub struct Composite {
78    pub opacity: f32,
79    pub blend: LayerBlendType,
80    /// Whether the draws test and write the frame's depth and stencil rather
81    /// than the texture's own, as a 3D layer's do: they and the other
82    /// layers' 3D draws then hide each other as they would on the frame.
83    pub frame_depth: bool,
84}
85
86impl Composite {
87    /// How a layer with the layer opacity `opacity` and the layer blend
88    /// `blend` composites, with a depth and stencil of its own: `None` for
89    /// an opaque layer of the `normal` blend, which draws straight onto the
90    /// frame.
91    #[must_use]
92    pub fn of(opacity: f32, blend: LayerBlendType) -> Option<Composite> {
93        let composites = opacity < 1.0 || blend != LayerBlendType::Normal;
94        composites.then_some(Composite { opacity, blend, frame_depth: false })
95    }
96
97    /// The blend the shader computes: none for the blends a blend function
98    /// expresses.
99    fn shader_blend(self) -> LayerCompositeBlendMode {
100        match self.blend {
101            LayerBlendType::Normal | LayerBlendType::Screen | LayerBlendType::PlusLighter => {
102                LayerCompositeBlendMode::None
103            }
104            LayerBlendType::Multiply => LayerCompositeBlendMode::Multiply,
105            LayerBlendType::Overlay => LayerCompositeBlendMode::Overlay,
106            LayerBlendType::Color => LayerCompositeBlendMode::Color,
107            LayerBlendType::Luminosity => LayerCompositeBlendMode::Luminosity,
108        }
109    }
110
111    /// Whether the shader blends with the backdrop, a copy of the frame.
112    fn reads_backdrop(self) -> bool {
113        reads_backdrop(self.blend)
114    }
115
116    /// The blend function that composites the shader's color: on premultiplied
117    /// colors, and a replacement where the shader blends with the backdrop.
118    fn blend_function(self) -> BlendFunction {
119        let add = |dst_factor| BlendFunction::Add(LinearBlend { src_factor: ColorBlendFactorType::One, dst_factor });
120        match self.blend {
121            LayerBlendType::Normal => add(ColorBlendFactorType::OneMinusSrcAlpha),
122            LayerBlendType::Screen => add(ColorBlendFactorType::OneMinusSrcColor),
123            LayerBlendType::PlusLighter => add(ColorBlendFactorType::One),
124            LayerBlendType::Multiply | LayerBlendType::Overlay | LayerBlendType::Color | LayerBlendType::Luminosity => {
125                BlendFunction::Replace
126            }
127        }
128    }
129}
130
131/// Whether a layer that composites with `blend` blends with the backdrop,
132/// a copy of the frame beneath it, in the shader.
133pub(crate) fn reads_backdrop(blend: LayerBlendType) -> bool {
134    Composite { opacity: 1.0, blend, frame_depth: false }.shader_blend() != LayerCompositeBlendMode::None
135}
136
137/// A texture that passes draw into and draws sample, with the sampler
138/// they sample it with.
139struct Texture {
140    texture: GpuTexture,
141    sampler: SamplerId,
142}
143
144impl Texture {
145    fn new(gpu: &mut dyn Gpu, context: &mut Context, size: Size, format: TextureFormat) -> Result<Texture, GpuError> {
146        let usage = TextureUsage { sampled: true, render_target: true, copy_src: true };
147        let desc = TextureDesc { label: "render target", size, format, usage, mipmapped: false };
148        let bytes = size.width as usize * size.height as usize * format.bytes_per_texel().unwrap_or(4) as usize;
149        let texture = context.device().texture(gpu, &desc, Some(bytes))?;
150        Ok(Texture { texture, sampler: context.sampler(gpu, SamplerState::default())? })
151    }
152
153    fn id(&self) -> TextureId {
154        self.texture.id()
155    }
156}
157
158/// The textures a composited layer draws into, of one size.
159struct Target {
160    size: Size,
161    color: Texture,
162    /// The depth and stencil of the layers that don't draw with the frame's,
163    /// from the first frame that composites one.
164    depth_stencil: Option<GpuTexture>,
165}
166
167/// The textures of a frame with a layer that blends in the shader: the
168/// frame draws into `frame`, which is copied into `backdrop` for each such
169/// layer and onto the frame's target at the end.
170struct FrameCopy {
171    format: TextureFormat,
172    frame: Texture,
173    backdrop: Texture,
174}
175
176/// The quad that covers the frame.
177struct Quad {
178    vertices: Buffer,
179    indices: Buffer,
180    geometry: Option<Owned<GeometryId>>,
181}
182
183/// The texture that the frame's composited layers draw into, one after
184/// another, and the draw that composites one onto the frame.
185#[derive(Default)]
186pub(crate) struct LayerComposite {
187    shader: Option<ShaderKey>,
188    shader_id: Option<ShaderId>,
189    target: Option<Target>,
190    frame: Option<FrameCopy>,
191    quad: Option<Quad>,
192    /// The draw groups composited in the frame, by id, in the order of their
193    /// slots of `uniforms`.
194    groups: Vec<(SimpleIdentity, Composite)>,
195    /// Each group's `LayerCompositeUBO`, at an offset the GPU can bind, and
196    /// then the copy's: one write a frame.
197    uniforms: Option<Buffer>,
198    /// The bytes of `uniforms`, kept between frames.
199    bytes: Vec<u8>,
200    /// A projection the shader doesn't read, for the block that OpenGL's
201    /// prelude declares, which WebGL2 rejects a draw without a buffer for.
202    projection: Option<Buffer>,
203    /// The bindings of each slot of `uniforms`, and what they were made of:
204    /// the epoch of the frame's buffers, the textures and the number of
205    /// slots, the last of which is the copy's. The composite drops them
206    /// when it replaces a buffer or texture they bind.
207    bindings: Vec<Owned<BindingsId>>,
208    bindings_made: Option<(u64, TextureId, Option<TextureId>, usize)>,
209}
210
211impl LayerComposite {
212    /// Makes what the frame composites `groups` with, each a draw group and
213    /// how it composites, onto a frame of `size` whose color is of `format`,
214    /// and drops it where there are none. Without `format`, every group
215    /// that blends in the shader blends as `normal`.
216    pub(crate) fn update(
217        &mut self,
218        gpu: &mut dyn Gpu,
219        context: &mut Context,
220        size: Size,
221        format: Option<TextureFormat>,
222        groups: &[(SimpleIdentity, Composite)],
223    ) {
224        self.groups.clear();
225        if groups.is_empty() || size.is_empty() {
226            self.drop_textures();
227            self.quad = None;
228            return;
229        }
230        self.shader.get_or_insert_with(|| {
231            context.shader_key(&programs::LAYER_COMPOSITE, Uniforms::default(), ProjectionVariant::Mercator)
232        });
233        for &(group, mut composite) in groups {
234            if format.is_none() && composite.reads_backdrop() {
235                composite.blend = LayerBlendType::Normal;
236            }
237            self.groups.push((group, composite));
238        }
239        let frame_format = format.filter(|_| self.groups.iter().any(|(_, c)| c.reads_backdrop()));
240        if let Err(error) = self.make(gpu, context, size, frame_format) {
241            context.fail(format!("Making the layer composite's textures failed: {error}"));
242            self.groups.clear();
243            self.drop_textures();
244            return;
245        }
246
247        let size = size_of::<LayerCompositeUBO>();
248        let stride = size.next_multiple_of(context.caps().buffer_offset_alignment as usize);
249        let copy = Composite { opacity: 1.0, blend: LayerBlendType::Normal, frame_depth: false };
250        self.bytes.clear();
251        self.bytes.resize((self.groups.len() + 1) * stride, 0);
252        for (slot, composite) in self.groups.iter().map(|&(_, composite)| composite).chain([copy]).enumerate() {
253            let ubo = LayerCompositeUBO {
254                opacity: composite.opacity,
255                blend: composite.shader_blend() as i32,
256                ..LayerCompositeUBO::default()
257            };
258            self.bytes[slot * stride..][..size].copy_from_slice(bytemuck::bytes_of(&ubo));
259        }
260        if context.device().write_uniforms(gpu, &mut self.uniforms, &self.bytes, false) {
261            self.drop_bindings();
262        }
263        if self.projection.is_none() {
264            let projection = ProjectionUBO::default();
265            context.device().write_uniforms(gpu, &mut self.projection, bytemuck::bytes_of(&projection), false);
266        }
267    }
268
269    /// Drops the textures and the bindings that read them.
270    fn drop_textures(&mut self) {
271        self.target = None;
272        self.frame = None;
273        self.drop_bindings();
274    }
275
276    fn drop_bindings(&mut self) {
277        self.bindings.clear();
278        self.bindings_made = None;
279    }
280
281    /// Makes the target of `size`, unless it is made, with a depth and
282    /// stencil of its own where a group draws with them, the frame copy of
283    /// `frame_format` where there is one, and the quad.
284    fn make(
285        &mut self,
286        gpu: &mut dyn Gpu,
287        context: &mut Context,
288        size: Size,
289        frame_format: Option<TextureFormat>,
290    ) -> Result<(), GpuError> {
291        if self.target.as_ref().is_none_or(|target| target.size != size) {
292            self.drop_textures();
293            let color = Texture::new(gpu, context, size, COLOR)?;
294            self.target = Some(Target { size, color, depth_stencil: None });
295        }
296        if let Some(target) = self.target.as_mut().filter(|target| target.depth_stencil.is_none())
297            && self.groups.iter().any(|(_, composite)| !composite.frame_depth)
298        {
299            target.depth_stencil =
300                Some(context.device().attachment(gpu, "layer composite depth and stencil", size, DEPTH_STENCIL)?);
301        }
302        match frame_format {
303            None => {
304                if self.frame.take().is_some() {
305                    self.drop_bindings();
306                }
307            }
308            Some(format) if self.frame.as_ref().is_none_or(|frame| frame.format != format) => {
309                self.frame = None;
310                self.drop_bindings();
311                let frame = Texture::new(gpu, context, size, format)?;
312                let backdrop = Texture::new(gpu, context, size, format)?;
313                self.frame = Some(FrameCopy { format, frame, backdrop });
314            }
315            Some(_) => {}
316        }
317        if self.quad.is_none() {
318            let vertices: [[i16; 2]; 4] = [[0, 0], [1, 0], [0, 1], [1, 1]];
319            let indices = RenderStaticData::quad_triangle_indices();
320            self.quad = Some(Quad {
321                vertices: context.device().buffer(gpu, BufferUsage::Vertex, bytemuck::cast_slice(&vertices))?,
322                indices: context.device().buffer(gpu, BufferUsage::Index, bytemuck::cast_slice(&indices))?,
323                geometry: None,
324            });
325        }
326        Ok(())
327    }
328
329    /// The bytes of its textures: its target's color, depth and stencil,
330    /// and the frame and backdrop of a frame with a layer that blends in
331    /// the shader.
332    pub(crate) fn bytes(&self) -> u64 {
333        let Some(target) = &self.target else { return 0 };
334        let depth_stencil = target.depth_stencil.as_ref().map_or(0, |_| attachment_bytes(target.size, DEPTH_STENCIL));
335        let frame = self.frame.as_ref().map_or(0, |frame| 2 * attachment_bytes(target.size, frame.format));
336        attachment_bytes(target.size, COLOR) + depth_stencil + frame
337    }
338
339    /// The texture the frame draws into rather than its target's, where a
340    /// layer of the frame blends in the shader.
341    #[must_use]
342    pub(crate) fn frame_texture(&self) -> Option<TextureId> {
343        self.frame.as_ref().map(|frame| frame.frame.id())
344    }
345
346    /// The texture a pass whose draw groups are `groups` draws into rather
347    /// than its own target: the frame copy's, where one of them blends in the
348    /// shader in this frame; `None` otherwise.
349    #[must_use]
350    pub(crate) fn frame_texture_for(&self, groups: &[(SimpleIdentity, Composite)]) -> Option<TextureId> {
351        let reads_backdrop = |group: &SimpleIdentity| {
352            self.groups.iter().any(|(id, composite)| id == group && composite.reads_backdrop())
353        };
354        self.frame_texture().filter(|_| groups.iter().any(|(group, _)| reads_backdrop(group)))
355    }
356
357    /// The pass that copies the frame's texture into the backdrop before the
358    /// draw group `group` composites: `None` where it doesn't blend in the
359    /// shader.
360    #[must_use]
361    pub(crate) fn backdrop_pass(&self, group: SimpleIdentity) -> Option<OpenPass> {
362        let frame = self.frame.as_ref()?;
363        let target = self.target.as_ref()?;
364        let (_, composite) = self.groups.iter().find(|(id, _)| *id == group)?;
365        composite.reads_backdrop().then_some(OpenPass {
366            label: "layer composite backdrop",
367            color: Some(ColorAttachment {
368                texture: frame.backdrop.id(),
369                load: LoadOp::Clear(Rgba::new(0.0, 0.0, 0.0, 0.0)),
370            }),
371            depth_stencil: None,
372            size: target.size,
373            targets: TargetFormats { color: Some(frame.format), depth_stencil: None },
374        })
375    }
376
377    /// Whether the draw group `group` draws into the texture in this frame.
378    #[must_use]
379    pub(crate) fn composites(&self, group: SimpleIdentity) -> bool {
380        self.target.is_some() && self.groups.iter().any(|(id, _)| *id == group)
381    }
382
383    /// Whether the draw group `group` draws into the texture with the
384    /// frame's depth and stencil rather than the texture's own.
385    #[must_use]
386    pub(crate) fn draws_with_frame_depth(&self, group: SimpleIdentity) -> bool {
387        self.groups.iter().any(|(id, composite)| *id == group && composite.frame_depth)
388    }
389
390    /// The pass that draws the draw group `group` into the texture, cleared
391    /// to transparent: with the texture's depth cleared to 1 and its stencil
392    /// to 0, or with the depth and stencil of `frame`, the frame's pass, as
393    /// they are, where the group draws with those. `None` without a target.
394    pub(crate) fn pass(&self, group: SimpleIdentity, frame: &OpenPass) -> Option<OpenPass> {
395        let target = self.target.as_ref()?;
396        let (depth_stencil, format) = if self.draws_with_frame_depth(group) {
397            let loaded =
398                |attachment| DepthStencilAttachment { depth: LoadOp::Load, stencil: LoadOp::Load, ..attachment };
399            (frame.depth_stencil.map(loaded), frame.targets.depth_stencil)
400        } else {
401            let own = DepthStencilAttachment {
402                texture: target.depth_stencil.as_ref()?.id(),
403                depth: LoadOp::Clear(1.0),
404                stencil: LoadOp::Clear(0),
405            };
406            (Some(own), Some(DEPTH_STENCIL))
407        };
408        Some(OpenPass {
409            label: "layer composite",
410            color: Some(ColorAttachment {
411                texture: target.color.id(),
412                load: LoadOp::Clear(Rgba::new(0.0, 0.0, 0.0, 0.0)),
413            }),
414            depth_stencil,
415            size: target.size,
416            targets: TargetFormats { color: Some(COLOR), depth_stencil: format },
417        })
418    }
419
420    /// Composites the texture onto the open pass, as the draw group `group`
421    /// does, testing `depth`.
422    pub(crate) fn draw(
423        &mut self,
424        gpu: &mut dyn Gpu,
425        target: DrawTarget,
426        depth: DepthMode,
427        context: &mut Context,
428        group: SimpleIdentity,
429    ) {
430        let Some(slot) = self.groups.iter().position(|(id, _)| *id == group) else {
431            return;
432        };
433        let blend = self.groups[slot].1.blend_function();
434        if let Err(error) = self.draw_quad(gpu, target, context, slot, blend, depth) {
435            context.fail(format!("Compositing a layer failed: {error}"));
436        }
437    }
438
439    /// Copies the frame's texture onto the open pass, over what it holds.
440    pub(crate) fn copy_frame(
441        &mut self,
442        gpu: &mut dyn Gpu,
443        target: DrawTarget,
444        context: &mut Context,
445    ) -> Result<(), GpuError> {
446        if self.frame.is_none() {
447            return Ok(());
448        }
449        let slot = self.groups.len();
450        self.draw_quad(gpu, target, context, slot, BlendFunction::Replace, DepthMode::disabled())
451    }
452
453    /// Draws the quad with the uniforms of `slot`: a group's, which reads the
454    /// layer's texture, or the copy's after them, which reads the frame's.
455    fn draw_quad(
456        &mut self,
457        gpu: &mut dyn Gpu,
458        draw_target: DrawTarget,
459        context: &mut Context,
460        slot: usize,
461        blend: BlendFunction,
462        depth: DepthMode,
463    ) -> Result<(), GpuError> {
464        let (Some(shader), Some(target), Some(quad), Some(uniforms), Some(projection)) =
465            (&self.shader, &self.target, &mut self.quad, &self.uniforms, &self.projection)
466        else {
467            return Ok(());
468        };
469        let DrawTarget { size, targets, scissor } = draw_target;
470        let shader_id = match self.shader_id {
471            Some(id) => id,
472            None => *self.shader_id.insert(context.shader(gpu, shader)?),
473        };
474
475        let layer = &target.color;
476        let frame = self.frame.as_ref();
477        let slots = self.groups.len() + 1;
478        let made = (context.global_uniform_buffers().epoch(), layer.id(), frame.map(|frame| frame.frame.id()), slots);
479        if self.bindings_made != Some(made) {
480            self.bindings.clear();
481            self.bindings_made = None;
482            let global = context.global_uniform_buffers();
483            let size = size_of::<LayerCompositeUBO>();
484            let stride = size.next_multiple_of(context.caps().buffer_offset_alignment as usize);
485            for slot in 0..slots {
486                // A group's image is the layer's texture and its backdrop the
487                // frame's copy; the copy's image is the frame's texture.
488                let (image, backdrop) = match frame {
489                    Some(frame) if slot + 1 == slots => (&frame.frame, &frame.frame),
490                    Some(frame) => (layer, &frame.backdrop),
491                    None => (layer, layer),
492                };
493                let mut entries = Entries::new();
494                for id in 0..BUFFER_IDS {
495                    let (buffer, offset, size) = match id {
496                        PROPS_ID => (uniforms, (slot * stride) as u64, size as u64),
497                        PROJECTION_ID => (projection, 0, projection.size() as u64),
498                        _ => match global.get(id) {
499                            Some(buffer) => (buffer, 0, buffer.size() as u64),
500                            None => continue,
501                        },
502                    };
503                    entries.push(BindGroupEntry::Buffer { id: id as u32, buffer: buffer.id(), offset, size });
504                }
505                for (slot, texture) in [(IMAGE_SLOT, image), (BACKDROP_SLOT, backdrop)] {
506                    entries.push(BindGroupEntry::Texture {
507                        slot: slot as u32,
508                        texture: texture.id(),
509                        sampler: texture.sampler,
510                    });
511                }
512                let bindings = gpu.create_bindings(&BindingsDesc {
513                    label: "layer composite",
514                    shader: shader_id,
515                    entries: entries.as_slice(),
516                })?;
517                self.bindings.push(context.own(bindings, Vec::new()));
518            }
519            self.bindings_made = Some(made);
520        }
521        let Some(bindings) = self.bindings.get(slot) else {
522            return Ok(());
523        };
524
525        let geometry = if let Some(geometry) = &quad.geometry {
526            geometry.id()
527        } else {
528            let geometry = gpu.create_geometry(&GeometryDesc {
529                shader: shader_id,
530                layouts: &[layout()],
531                vertex_buffers: &[(quad.vertices.id(), 0)],
532                index_buffer: quad.indices.id(),
533            })?;
534            quad.geometry = Some(context.own(geometry, Vec::new()));
535            geometry
536        };
537
538        let pipeline = context.pipeline(
539            gpu,
540            &PipelineKey {
541                shader: shader_id,
542                vertex_buffers: vec![layout()],
543                state: FixedState {
544                    primitive: DrawModeType::Triangles,
545                    cull: CullFaceMode::disabled(),
546                    blend,
547                    color_mask: ColorMode::alpha_blended().mask,
548                    depth: DepthState::from(&depth),
549                    stencil: StencilState::from(&StencilMode::disabled()),
550                },
551                targets,
552            },
553        )?;
554        let full = Scissor { x: 0, y: 0, width: size.width, height: size.height };
555        gpu.draw(&Draw {
556            pipeline,
557            bindings: bindings.id(),
558            geometry,
559            first_index: 0,
560            index_count: 6,
561            base_vertex: 0,
562            first_instance: 0,
563            instance_count: 1,
564            global_index: 0,
565            dynamic: DynamicState {
566                depth_range: depth.range,
567                scissor: scissor.unwrap_or(full),
568                stencil_reference: 0,
569                blend_constant: Rgba::default(),
570                line_width: 1.0,
571            },
572        })?;
573        let stats = context.rendering_stats();
574        stats.num_draw_calls += 1;
575        stats.total_draw_calls += 1;
576        Ok(())
577    }
578}