1use mgui_core::paint::{BlendMode, TextureMode};
2use mgui_core::Rect;
3use mgui_core::{effect_flags, FramePaint, LayerEffect, LayerId, LayerPaint, PaintCommand, PaintList, RRectDef, Size};
4use std::cell::RefCell;
5use std::collections::HashMap;
6use std::rc::Rc;
7
8use wgpu::util::DeviceExt;
9
10#[repr(C)]
13#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
14pub(crate) struct RectBatchUniform {
15 screen_size: [f32; 2], count: u32, _pad: [f32; 1], }
19
20#[repr(C)]
28#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
29pub(crate) struct RectInstance {
30 rect: [f32; 4],
31 from: [f32; 4],
32 to: [f32; 4],
33 grad: [f32; 4],
34 params: [f32; 4],
36}
37
38#[repr(C)]
40#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
41pub(crate) struct TextBatchUniform {
42 screen_size: [f32; 2], count: u32, _pad: [f32; 1], }
46
47#[repr(C)]
51#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
52pub(crate) struct TextInstance {
53 rect: [f32; 4], color: [f32; 4], uv: [f32; 4], mode: f32, _pad: [f32; 3], }
61
62#[repr(C)]
73#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
74pub(crate) struct BlitUniform {
75 offset: [f32; 2], size: [f32; 2], screen: [f32; 2], effect_flags: u32, opacity: f32, rotation: f32, scale_x: f32, translate_x: f32, translate_y: f32, clip_radius: f32, scale_y: f32, quad_offset: [f32; 2], quad_size: [f32; 2], phys_screen: [f32; 2], affine: [f32; 4], affine_translate: [f32; 2], _affine_pad: [f32; 2], clip_rect0: [f32; 4], clip_rect1: [f32; 4], clip_params: [f32; 4], }
104struct LayerGpuCache {
108 resolve_texture: wgpu::Texture,
110 resolve_view: wgpu::TextureView,
112 cached_size: (u32, u32),
114}
115
116#[derive(Clone)]
121pub struct RendererShared {
122 rect_pipelines: [wgpu::RenderPipeline; 4],
124 rect_bgl: wgpu::BindGroupLayout,
125 text_pipeline: wgpu::RenderPipeline,
126 text_bgl: wgpu::BindGroupLayout,
127 text_pipeline_mask: wgpu::RenderPipeline,
129 text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
130 tri_pipeline: wgpu::RenderPipeline,
131 tri_bgl: wgpu::BindGroupLayout,
132 tri_pipeline_stencil_inc: wgpu::RenderPipeline,
134 tri_pipeline_stencil_dec: wgpu::RenderPipeline,
135 rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
136 text_pipeline_stencil_test: wgpu::RenderPipeline,
137 tri_pipeline_stencil_test: wgpu::RenderPipeline,
138 blit_pipeline: wgpu::RenderPipeline,
139 blit_bgl: wgpu::BindGroupLayout,
140 blit_sampler: wgpu::Sampler,
141 backdrop_pipeline: wgpu::RenderPipeline,
143 backdrop_bgl: wgpu::BindGroupLayout,
144 format: wgpu::TextureFormat,
145 atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
146 image_cache: Rc<RefCell<ImageTextureCache>>,
147}
148
149#[derive(Default)]
151pub(crate) struct ImageTextureCache {
152 textures: HashMap<u32, ImageTextureEntry>,
153 clock: u64,
154 evict_enabled: bool,
156}
157
158impl RendererShared {
159 pub fn format(&self) -> wgpu::TextureFormat {
160 self.format
161 }
162
163 pub fn evict_images(&self, protected: &std::collections::HashSet<u32>) {
166 self.image_cache.borrow_mut().evict_to_budget(protected);
167 }
168}
169
170impl ImageTextureCache {
171 fn evict_to_budget(&mut self, protected: &std::collections::HashSet<u32>) {
172 let budget = IMAGE_TEXTURE_BUDGET_BYTES;
173 let mut total: u64 = self.textures.values().map(|e| e.bytes).sum();
174 if total <= budget {
175 return;
176 }
177 let mut candidates: Vec<(u32, u64, u64)> = self
178 .textures
179 .iter()
180 .filter(|(id, _)| !protected.contains(id))
181 .map(|(&id, e)| (id, e.last_used, e.bytes))
182 .collect();
183 candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
184 for (id, _, bytes) in candidates {
185 if total <= budget {
186 break;
187 }
188 self.textures.remove(&id);
189 total = total.saturating_sub(bytes);
190 }
191 if total > budget {
192 log::warn!(
193 target: "mgui_startup",
194 "shared image cache uses {} MiB (budget {} MiB); all remaining textures are in use",
195 total / (1024 * 1024),
196 budget / (1024 * 1024)
197 );
198 }
199 }
200}
201
202#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
203pub struct RenderStats {
204 pub layers_painted: u32,
206 pub segments: u32,
208 pub draw_calls: u32,
210 pub scratch_bytes: u64,
212 pub layer_texture_bytes: u64,
214}
215
216pub struct Renderer {
217 rect_pipelines: [wgpu::RenderPipeline; 4],
219 rect_bgl: wgpu::BindGroupLayout,
220 text_pipeline: wgpu::RenderPipeline,
221 text_bgl: wgpu::BindGroupLayout,
222 text_pipeline_mask: wgpu::RenderPipeline,
224 text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
225 tri_pipeline: wgpu::RenderPipeline,
227 tri_bgl: wgpu::BindGroupLayout,
228 tri_pipeline_stencil_inc: wgpu::RenderPipeline,
232 tri_pipeline_stencil_dec: wgpu::RenderPipeline,
233 rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
234 text_pipeline_stencil_test: wgpu::RenderPipeline,
235 tri_pipeline_stencil_test: wgpu::RenderPipeline,
236 atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
238 layer_cache: HashMap<LayerId, LayerGpuCache>,
240 active_layer_ids: std::collections::HashSet<LayerId>,
242 frame_layer_sizes: HashMap<LayerId, Size>,
244 composition_scratch: mgui_core::CompositionScratch,
246 blit_pipeline: wgpu::RenderPipeline,
248 blit_bgl: wgpu::BindGroupLayout,
249 blit_sampler: wgpu::Sampler,
250 backdrop_pipeline: wgpu::RenderPipeline,
252 backdrop_bgl: wgpu::BindGroupLayout,
253 format: wgpu::TextureFormat,
255 pub gpu_profiler: Option<crate::gpu_profiler::GpuProfiler>,
257 batch_pools: HashMap<(LayerId, u32), LayerBatchPool>,
266 image_cache: Rc<RefCell<ImageTextureCache>>,
268 msaa_scratch: HashMap<(u32, u32), wgpu::TextureView>,
270 stencil_scratch: HashMap<(u32, u32), wgpu::TextureView>,
271 snapshot_scratch: HashMap<(u32, u32), (wgpu::Texture, wgpu::TextureView)>,
272 last_stats: RenderStats,
274}
275
276pub(crate) struct ImageTextureEntry {
278 pub _texture: wgpu::Texture,
280 pub view: wgpu::TextureView,
281 pub sampler: wgpu::Sampler,
282 pub last_used: u64,
284 pub bytes: u64,
286}
287
288pub const IMAGE_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
290
291pub use setup::LAYER_TEXTURE_BUDGET_BYTES;
293
294pub use crate::backend_info::ImageTextureStats;
295
296impl Renderer {
297 pub fn last_stats(&self) -> RenderStats {
299 self.last_stats
300 }
301
302 pub fn image_texture_stats(&self) -> ImageTextureStats {
304 let cache = self.image_cache.borrow();
305 ImageTextureStats {
306 count: cache.textures.len(),
307 bytes: cache.textures.values().map(|e| e.bytes).sum(),
308 budget_bytes: IMAGE_TEXTURE_BUDGET_BYTES,
309 }
310 }
311}
312
313struct LayerBatchPool {
315 rect_header: Option<wgpu::Buffer>,
316 rect_instances: Option<wgpu::Buffer>,
317 text_header: Option<wgpu::Buffer>,
318 text_instances: Option<wgpu::Buffer>,
319 tri_vertex: Option<wgpu::Buffer>,
321 tri_index: Option<wgpu::Buffer>,
322 tri_uniform: Option<wgpu::Buffer>,
323 stencil_vertex: Option<wgpu::Buffer>,
326 stencil_index: Option<wgpu::Buffer>,
327}
328
329pub(crate) struct AtlasGpu {
331 texture: wgpu::Texture,
332 view: wgpu::TextureView,
333 sampler: wgpu::Sampler,
334 cached_size: (u32, u32),
336}
337
338pub(crate) struct RectBatch {
339 bg: wgpu::BindGroup,
340}
341
342pub(crate) struct TriBatch {
344 bg: wgpu::BindGroup,
345}
346
347#[repr(C)]
349#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
350struct TriUniform {
351 screen_size: [f32; 2],
352 _pad0: u32,
353 _pad1: u32,
354}
355
356#[repr(C)]
358#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
359struct BackdropUniform {
360 screen: [f32; 2],
361 _pad: [f32; 2],
362 rect: [f32; 4],
363 params: [f32; 4],
365 tint: [f32; 4],
367}
368
369pub(crate) struct TextBatch {
371 bg: wgpu::BindGroup,
372 count: u32,
373}
374
375#[derive(Debug, Clone, Default)]
381pub(crate) struct StencilDraw {
382 pub vertices: Vec<f32>,
384 pub indices: Vec<u32>,
385}
386
387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
392pub(crate) struct StencilAction {
393 pub draw: u32,
395 pub level: u32,
397 pub increment: bool,
398}
399
400pub(crate) struct StencilGpu {
402 pub vertex: wgpu::Buffer,
403 pub index: wgpu::Buffer,
404 pub ranges: Vec<(u32, u32)>,
405 pub bg: wgpu::BindGroup,
406}
407
408#[derive(Debug, Clone, Copy)]
410pub(crate) struct BackdropBlurSpec {
411 pub rect: Rect,
412 pub radius: f32,
413 pub blur_radius: f32,
414 pub tint: [f32; 4],
415}
416
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub(crate) enum DrawOp {
420 Rect(u32, u32, BlendMode),
422 Text(u32, u32),
424 Image(u32),
426 Mask(u32),
428 BackdropBlur(u32),
430 Tri(u32, u32),
432}
433
434#[derive(Debug, Clone, PartialEq)]
440pub(crate) struct ClipSegment {
441 pub scissor: Option<[u32; 4]>,
443 pub ops: Vec<DrawOp>,
445 pub rect_range: (u32, u32),
447 pub text_range: (u32, u32),
448 pub image_range: (u32, u32),
449 pub stencil_level: u32,
451 pub stencil_actions: Vec<StencilAction>,
453}
454
455pub(crate) struct ImageGroup {
458 pub texture_id: u32,
459 pub instances: Vec<TextInstance>,
460}
461
462pub(crate) struct ImageBatchDraw {
468 pub(crate) batch: TextBatch,
469}
470
471fn intersect_rect(a: Rect, b: Rect) -> Rect {
473 let x1 = a.x.max(b.x);
474 let y1 = a.y.max(b.y);
475 let x2 = (a.x + a.width).min(b.x + b.width);
476 let y2 = (a.y + a.height).min(b.y + b.height);
477 Rect::new(x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0))
478}
479
480fn path_bounding_box(vertices: &[mgui_core::paint::Vertex]) -> Rect {
482 if vertices.is_empty() {
483 return Rect::new(0.0, 0.0, 0.0, 0.0);
484 }
485 let mut min_x = f32::INFINITY;
486 let mut min_y = f32::INFINITY;
487 let mut max_x = f32::NEG_INFINITY;
488 let mut max_y = f32::NEG_INFINITY;
489 for v in vertices {
490 min_x = min_x.min(v.x);
491 min_y = min_y.min(v.y);
492 max_x = max_x.max(v.x);
493 max_y = max_y.max(v.y);
494 }
495 Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
496}
497
498fn rect_intersects_clip(r: &Rect, clip: Option<Rect>) -> bool {
500 match clip {
501 None => true,
502 Some(c) => {
504 c.width > 0.0
505 && c.height > 0.0
506 && r.x < c.x + c.width
507 && r.x + r.width > c.x
508 && r.y < c.y + c.height
509 && r.y + r.height > c.y
510 }
511 }
512}
513
514fn rounded_rect_stencil_mesh(rect: Rect, radius: f32) -> (Vec<f32>, Vec<u32>) {
519 if rect.width <= 0.0 || rect.height <= 0.0 {
520 return (Vec::new(), Vec::new());
521 }
522 let (x, y, w, h) = (rect.x, rect.y, rect.width, rect.height);
523 let r = radius.max(0.0).min(w.min(h) * 0.5);
524
525 let mut pts: Vec<(f32, f32)> = Vec::new();
526 if r <= 0.0 {
527 pts.extend_from_slice(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
528 } else {
529 const SEG: u32 = 8;
530 let arcs = [
532 (x + w - r, y + r, -std::f32::consts::FRAC_PI_2, 0.0),
533 (x + w - r, y + h - r, 0.0, std::f32::consts::FRAC_PI_2),
534 (x + r, y + h - r, std::f32::consts::FRAC_PI_2, std::f32::consts::PI),
535 (x + r, y + r, std::f32::consts::PI, 3.0 * std::f32::consts::FRAC_PI_2),
536 ];
537 for &(cx, cy, a0, a1) in &arcs {
538 for i in 0..=SEG {
539 let a = a0 + (a1 - a0) * (i as f32 / SEG as f32);
540 pts.push((cx + r * a.cos(), cy + r * a.sin()));
541 }
542 }
543 if pts.len() > 1 && pts.first() == pts.last() {
545 pts.pop();
546 }
547 }
548 pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5);
549
550 let n = pts.len();
551 if n < 3 {
552 return (Vec::new(), Vec::new());
553 }
554 let mut verts = Vec::with_capacity((n + 1) * 6);
555 for &(px, py) in &pts {
556 verts.extend_from_slice(&[px, py, 1.0, 1.0, 1.0, 1.0]);
557 }
558 verts.extend_from_slice(&[x + w * 0.5, y + h * 0.5, 1.0, 1.0, 1.0, 1.0]);
559 let center = n as u32;
560 let mut indices = Vec::with_capacity(n * 3);
561 for i in 0..n as u32 {
562 indices.extend_from_slice(&[center, i, (i + 1) % n as u32]);
563 }
564 (verts, indices)
565}
566
567fn clip_to_scissor_px(r: Rect, dpr: f32, tex: (u32, u32)) -> [u32; 4] {
569 let d = dpr.max(0.0);
570 let (tw, th) = (tex.0 as f32, tex.1 as f32);
571 let x0 = (r.x * d).floor().clamp(0.0, tw);
574 let y0 = (r.y * d).floor().clamp(0.0, th);
575 let x1 = ((r.x + r.width) * d).ceil().clamp(0.0, tw).max(x0);
576 let y1 = ((r.y + r.height) * d).ceil().clamp(0.0, th).max(y0);
577 let x = x0 as u32;
578 let y = y0 as u32;
579 let w = (x1 as u32).saturating_sub(x);
580 let h = (y1 as u32).saturating_sub(y);
581 [x, y, w, h]
582}
583
584type CollectedInstances = (
599 Vec<RectInstance>,
600 Vec<TextInstance>,
601 Vec<ImageGroup>,
602 Vec<ClipSegment>,
603 Vec<f32>, Vec<u32>, Vec<StencilDraw>,
608 Vec<BackdropBlurSpec>,
610);
611
612pub(crate) fn collect_instances_segmented(
613 paint_list: &PaintList,
614 dpr: f32,
615 tex_size: (u32, u32),
616) -> CollectedInstances {
617 let mut rects: Vec<RectInstance> = Vec::new();
618 let mut texts: Vec<TextInstance> = Vec::new();
619 let mut image_groups: Vec<ImageGroup> = Vec::new();
620 let mut segments: Vec<ClipSegment> = Vec::new();
621 let mut tri_vertices: Vec<f32> = Vec::new(); let mut tri_indices: Vec<u32> = Vec::new(); let mut tri_base_vertex: u32 = 0; let mut stencil_draws: Vec<StencilDraw> = Vec::new();
627 let mut pending_stencil: Vec<StencilAction> = Vec::new();
628 let mut backdrop_blurs: Vec<BackdropBlurSpec> = Vec::new();
629 let mut path_draw_stack: Vec<Option<u32>> = Vec::new();
630 let mut clip_depth: u32 = 0;
631 let mut blend_stack: Vec<BlendMode> = Vec::new();
633 let mut cur_blend = BlendMode::Normal;
634 let mut stack: Vec<(Option<Rect>, bool)> = Vec::new();
636 let mut cur_clip: Option<Rect> = None;
637 let (mut seg_r, mut seg_t, mut seg_i): (u32, u32, u32) = (0, 0, 0);
638 let mut ops: Vec<DrawOp> = Vec::new();
640
641 macro_rules! close_segment {
643 () => {
644 let r_end = rects.len() as u32;
645 let t_end = texts.len() as u32;
646 let i_end = image_groups.len() as u32;
647 if !ops.is_empty() {
648 segments.push(ClipSegment {
649 scissor: cur_clip.map(|c| clip_to_scissor_px(c, dpr, tex_size)),
650 ops: ops.clone(),
651 rect_range: (seg_r, r_end),
652 text_range: (seg_t, t_end),
653 image_range: (seg_i, i_end),
654 stencil_level: clip_depth,
655 stencil_actions: std::mem::take(&mut pending_stencil),
658 });
659 ops.clear();
660 }
661 seg_r = r_end;
662 seg_t = t_end;
663 seg_i = i_end;
664 };
665 }
666
667 fn push_range_op(ops: &mut Vec<DrawOp>, op: DrawOp) {
668 match op {
669 DrawOp::Rect(s, e, mode) => {
670 if let Some(DrawOp::Rect(_, last_end, last_mode)) = ops.last_mut() {
671 if *last_end == s && *last_mode == mode {
672 *last_end = e;
673 return;
674 }
675 }
676 }
677 DrawOp::Text(s, e) => {
678 if let Some(DrawOp::Text(_, last_end)) = ops.last_mut() {
679 if *last_end == s {
680 *last_end = e;
681 return;
682 }
683 }
684 }
685 DrawOp::Tri(s, e) => {
686 if let Some(DrawOp::Tri(_, last_end)) = ops.last_mut() {
687 if *last_end == s {
688 *last_end = e;
689 return;
690 }
691 }
692 }
693 DrawOp::Image(_) => {}
694 DrawOp::Mask(_) => {}
695 DrawOp::BackdropBlur(_) => {}
696 }
697 ops.push(op);
698 }
699
700 macro_rules! push_mask_clip {
702 ($flat:expr, $idxs:expr, $bbox:expr) => {{
703 clip_depth += 1;
704 let flat_verts: Vec<f32> = $flat;
705 let idxs: &[u32] = $idxs;
706 let draw_index = if !flat_verts.is_empty() && !idxs.is_empty() {
707 let idx = stencil_draws.len() as u32;
708 stencil_draws.push(StencilDraw { vertices: flat_verts, indices: idxs.to_vec() });
709 pending_stencil.push(StencilAction { draw: idx, level: clip_depth, increment: true });
710 Some(idx)
711 } else {
712 None
713 };
714 path_draw_stack.push(draw_index);
715
716 let bbox: Rect = $bbox;
717 stack.push((cur_clip, true));
718 cur_clip = Some(match cur_clip {
719 Some(outer) => intersect_rect(outer, bbox),
720 None => bbox,
721 });
722 }};
723 }
724
725 macro_rules! pop_mask_clip {
727 () => {{
728 if let Some(Some(draw)) = path_draw_stack.pop() {
729 pending_stencil.push(StencilAction { draw, level: clip_depth, increment: false });
731 }
732 clip_depth = clip_depth.saturating_sub(1);
733 }};
734 }
735
736 for cmd in &paint_list.commands {
737 match cmd {
738 PaintCommand::PushBlendMode(mode) => {
739 blend_stack.push(cur_blend);
740 cur_blend = *mode;
741 }
742 PaintCommand::PopBlendMode => {
743 cur_blend = blend_stack.pop().unwrap_or(BlendMode::Normal);
744 }
745 PaintCommand::PushClip(r) => {
746 close_segment!();
747 stack.push((cur_clip, false));
748 cur_clip = Some(match cur_clip {
749 Some(outer) => intersect_rect(outer, *r),
750 None => *r,
751 });
752 }
753 PaintCommand::PushClipRRect { rect, radius } => {
754 close_segment!();
755 let (flat_verts, idxs) = rounded_rect_stencil_mesh(*rect, *radius);
756 push_mask_clip!(flat_verts, &idxs, *rect);
757 }
758 PaintCommand::PopClip => {
759 close_segment!();
760 let (prev, is_mask) = stack.pop().unwrap_or((None, false));
761 if is_mask {
762 pop_mask_clip!();
763 }
764 cur_clip = prev;
765 }
766 PaintCommand::PushClipPath { vertices, indices } => {
768 close_segment!();
769 let mut flat_verts: Vec<f32> = Vec::with_capacity(vertices.len() * 6);
770 for v in vertices {
771 flat_verts.push(v.x);
772 flat_verts.push(v.y);
773 flat_verts.push(v.color.r);
774 flat_verts.push(v.color.g);
775 flat_verts.push(v.color.b);
776 flat_verts.push(v.color.a);
777 }
778 push_mask_clip!(flat_verts, indices, path_bounding_box(vertices));
779 }
780 PaintCommand::PopClipPath => {
781 close_segment!();
782 let (prev, is_mask) = stack.pop().unwrap_or((None, false));
783 if is_mask {
784 pop_mask_clip!();
785 }
786 cur_clip = prev;
787 }
788 PaintCommand::Rect { rect, color, radius } => {
789 if rect_intersects_clip(rect, cur_clip) {
790 let start = rects.len() as u32;
791 rects.push(RectInstance {
792 rect: [rect.x, rect.y, rect.width, rect.height],
793 from: [color.r, color.g, color.b, color.a],
794 to: [color.r, color.g, color.b, color.a],
795 grad: [0.0; 4],
796 params: [*radius, 0.0, 0.0, 0.0],
797 });
798 push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
799 }
800 }
801 PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
803 if rect_intersects_clip(rect, cur_clip) {
804 let start = rects.len() as u32;
805 rects.push(RectInstance {
806 rect: [rect.x, rect.y, rect.width, rect.height],
807 from: [color.r, color.g, color.b, color.a],
808 to: [color.r, color.g, color.b, color.a],
809 grad: [0.0; 4],
810 params: [*radius, 0.0, *blur_radius, 0.0],
811 });
812 push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
813 }
814 }
815 PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
817 if rect_intersects_clip(rect, cur_clip) {
818 let idx = rects.len() as u32;
819 rects.push(RectInstance {
820 rect: [rect.x, rect.y, rect.width, rect.height],
821 from: [color.r, color.g, color.b, color.a],
822 to: [color.r, color.g, color.b, color.a],
823 grad: [0.0; 4],
824 params: [*radius, 3.0, *blur_radius, 0.0],
825 });
826 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
827 }
828 }
829 PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
830 if rect_intersects_clip(rect, cur_clip) {
831 let idx = rects.len() as u32;
832 rects.push(RectInstance {
833 rect: [rect.x, rect.y, rect.width, rect.height],
834 from: [from.r, from.g, from.b, from.a],
835 to: [to.r, to.g, to.b, to.a],
836 grad: [start.x, start.y, end.x, end.y],
837 params: [*corner_radius, 1.0, 0.0, 0.0],
838 });
839 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
840 }
841 }
842 PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
843 if rect_intersects_clip(rect, cur_clip) {
844 let idx = rects.len() as u32;
845 rects.push(RectInstance {
846 rect: [rect.x, rect.y, rect.width, rect.height],
847 from: [from.r, from.g, from.b, from.a],
848 to: [to.r, to.g, to.b, to.a],
849 grad: [center.x, center.y, *radial_radius, 0.0],
850 params: [*corner_radius, 2.0, 0.0, 0.0],
851 });
852 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
853 }
854 }
855 PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
857 if rect_intersects_clip(rect, cur_clip) {
858 let idx = backdrop_blurs.len() as u32;
859 backdrop_blurs.push(BackdropBlurSpec {
860 rect: *rect,
861 radius: *radius,
862 blur_radius: *blur_radius,
863 tint: [tint.r, tint.g, tint.b, tint.a],
864 });
865 ops.push(DrawOp::BackdropBlur(idx));
866 }
867 }
868 PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
870 if *alpha > 0.0 && rect_intersects_clip(rect, cur_clip) {
871 let gi = image_groups.len() as u32;
872 image_groups.push(ImageGroup {
873 texture_id: *texture_id,
874 instances: vec![TextInstance {
875 rect: [rect.x, rect.y, rect.width, rect.height],
876 color: [1.0, 1.0, 1.0, alpha.clamp(0.0, 1.0)],
878 uv: *uv,
879 mode: 2.0,
880 _pad: [0.0; 3],
881 }],
882 });
883 ops.push(DrawOp::Mask(gi));
884 }
885 }
886 PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
887 if rect_intersects_clip(rect, cur_clip) {
888 let snap = |v: f32| (v * dpr).round() / dpr;
891 let inst = TextInstance {
892 rect: [
893 snap(rect.x),
894 snap(rect.y),
895 snap(rect.x + rect.width) - snap(rect.x),
896 snap(rect.y + rect.height) - snap(rect.y),
897 ],
898 color: [color.r, color.g, color.b, color.a],
899 uv: *uv,
900 mode: match mode {
901 TextureMode::Mask => 0.0,
902 TextureMode::Color => 1.0,
903 },
904 _pad: [0.0; 3],
905 };
906 if *texture_id == 0 {
907 let start = texts.len() as u32;
908 texts.push(inst);
909 push_range_op(&mut ops, DrawOp::Text(start, start + 1));
910 } else {
911 let reuse_group = ops
915 .last()
916 .and_then(|op| match op {
917 DrawOp::Image(gi) => Some(*gi),
918 _ => None,
919 })
920 .filter(|&gi| image_groups[gi as usize].texture_id == *texture_id);
921 if let Some(gi) = reuse_group {
922 image_groups[gi as usize].instances.push(inst);
923 } else {
924 let gi = image_groups.len() as u32;
925 image_groups.push(ImageGroup { texture_id: *texture_id, instances: vec![inst] });
926 ops.push(DrawOp::Image(gi));
927 }
928 }
929 }
930 }
931 PaintCommand::Triangles { vertices, indices } => {
934 let idx_start = tri_indices.len() as u32;
935 for v in vertices {
937 tri_vertices.push(v.x);
938 tri_vertices.push(v.y);
939 tri_vertices.push(v.color.r);
940 tri_vertices.push(v.color.g);
941 tri_vertices.push(v.color.b);
942 tri_vertices.push(v.color.a);
943 }
944 for &idx in indices {
946 tri_indices.push(tri_base_vertex + idx);
947 }
948 tri_base_vertex += vertices.len() as u32;
949 if !vertices.is_empty() && !indices.is_empty() {
950 push_range_op(&mut ops, DrawOp::Tri(idx_start, tri_indices.len() as u32));
951 }
952 }
953 PaintCommand::Text { text, range, font_size, color, position, max_width } => {
956 let mut temp_list = PaintList::new();
957 crate::text::paint_text_span(text, *range, *font_size, *color, *position, &mut temp_list, *max_width);
958 let snap = |v: f32| (v * dpr).round() / dpr;
960 let start = texts.len() as u32;
961 for cmd in temp_list.commands {
962 if let PaintCommand::TexturedRect { rect, color, uv, texture_id: 0, .. } = cmd {
963 if rect_intersects_clip(&rect, cur_clip) {
964 texts.push(TextInstance {
965 rect: [
966 snap(rect.x),
967 snap(rect.y),
968 snap(rect.x + rect.width) - snap(rect.x),
969 snap(rect.y + rect.height) - snap(rect.y),
970 ],
971 color: [color.r, color.g, color.b, color.a],
972 uv,
973 mode: 0.0,
975 _pad: [0.0; 3],
976 });
977 }
978 }
979 }
980 if texts.len() as u32 > start {
981 push_range_op(&mut ops, DrawOp::Text(start, texts.len() as u32));
982 }
983 }
984 }
985 }
986 close_segment!();
988 let _ = (seg_r, seg_t, seg_i); let mut merged: Vec<ClipSegment> = Vec::with_capacity(segments.len());
994 for seg in segments.drain(..) {
995 let can_merge = merged.last().is_some_and(|prev: &ClipSegment| {
996 prev.scissor == seg.scissor && prev.stencil_level == seg.stencil_level && seg.stencil_actions.is_empty()
997 });
998 if can_merge {
999 let prev = merged.last_mut().expect("checked non-empty");
1000 for op in &seg.ops {
1001 push_range_op(&mut prev.ops, *op);
1002 }
1003 prev.rect_range.1 = seg.rect_range.1;
1004 prev.text_range.1 = seg.text_range.1;
1005 prev.image_range.1 = seg.image_range.1;
1006 } else {
1007 merged.push(seg);
1008 }
1009 }
1010
1011 (rects, texts, image_groups, merged, tri_vertices, tri_indices, stencil_draws, backdrop_blurs)
1012}
1013
1014mod batches;
1027mod composition;
1028mod render;
1029mod setup;
1030#[cfg(test)]
1031mod tests;