use mgui_core::paint::{BlendMode, TextureMode};
use mgui_core::Rect;
use mgui_core::{effect_flags, FramePaint, LayerEffect, LayerId, LayerPaint, PaintCommand, PaintList, RRectDef, Size};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use wgpu::util::DeviceExt;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct RectBatchUniform {
screen_size: [f32; 2], count: u32, _pad: [f32; 1], }
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct RectInstance {
rect: [f32; 4],
from: [f32; 4],
to: [f32; 4],
grad: [f32; 4],
params: [f32; 4],
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct TextBatchUniform {
screen_size: [f32; 2], count: u32, _pad: [f32; 1], }
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct TextInstance {
rect: [f32; 4], color: [f32; 4], uv: [f32; 4], mode: f32, _pad: [f32; 3], }
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct BlitUniform {
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], }
struct LayerGpuCache {
resolve_texture: wgpu::Texture,
resolve_view: wgpu::TextureView,
cached_size: (u32, u32),
}
#[derive(Clone)]
pub struct RendererShared {
rect_pipelines: [wgpu::RenderPipeline; 4],
rect_bgl: wgpu::BindGroupLayout,
text_pipeline: wgpu::RenderPipeline,
text_bgl: wgpu::BindGroupLayout,
text_pipeline_mask: wgpu::RenderPipeline,
text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
tri_pipeline: wgpu::RenderPipeline,
tri_bgl: wgpu::BindGroupLayout,
tri_pipeline_stencil_inc: wgpu::RenderPipeline,
tri_pipeline_stencil_dec: wgpu::RenderPipeline,
rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
text_pipeline_stencil_test: wgpu::RenderPipeline,
tri_pipeline_stencil_test: wgpu::RenderPipeline,
blit_pipeline: wgpu::RenderPipeline,
blit_bgl: wgpu::BindGroupLayout,
blit_sampler: wgpu::Sampler,
backdrop_pipeline: wgpu::RenderPipeline,
backdrop_bgl: wgpu::BindGroupLayout,
format: wgpu::TextureFormat,
atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
image_cache: Rc<RefCell<ImageTextureCache>>,
}
#[derive(Default)]
pub(crate) struct ImageTextureCache {
textures: HashMap<u32, ImageTextureEntry>,
clock: u64,
evict_enabled: bool,
}
impl RendererShared {
pub fn format(&self) -> wgpu::TextureFormat {
self.format
}
pub fn evict_images(&self, protected: &std::collections::HashSet<u32>) {
self.image_cache.borrow_mut().evict_to_budget(protected);
}
}
impl ImageTextureCache {
fn evict_to_budget(&mut self, protected: &std::collections::HashSet<u32>) {
let budget = IMAGE_TEXTURE_BUDGET_BYTES;
let mut total: u64 = self.textures.values().map(|e| e.bytes).sum();
if total <= budget {
return;
}
let mut candidates: Vec<(u32, u64, u64)> = self
.textures
.iter()
.filter(|(id, _)| !protected.contains(id))
.map(|(&id, e)| (id, e.last_used, e.bytes))
.collect();
candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
for (id, _, bytes) in candidates {
if total <= budget {
break;
}
self.textures.remove(&id);
total = total.saturating_sub(bytes);
}
if total > budget {
log::warn!(
target: "mgui_startup",
"shared image cache uses {} MiB (budget {} MiB); all remaining textures are in use",
total / (1024 * 1024),
budget / (1024 * 1024)
);
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RenderStats {
pub layers_painted: u32,
pub segments: u32,
pub draw_calls: u32,
pub scratch_bytes: u64,
pub layer_texture_bytes: u64,
}
pub struct Renderer {
rect_pipelines: [wgpu::RenderPipeline; 4],
rect_bgl: wgpu::BindGroupLayout,
text_pipeline: wgpu::RenderPipeline,
text_bgl: wgpu::BindGroupLayout,
text_pipeline_mask: wgpu::RenderPipeline,
text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
tri_pipeline: wgpu::RenderPipeline,
tri_bgl: wgpu::BindGroupLayout,
tri_pipeline_stencil_inc: wgpu::RenderPipeline,
tri_pipeline_stencil_dec: wgpu::RenderPipeline,
rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
text_pipeline_stencil_test: wgpu::RenderPipeline,
tri_pipeline_stencil_test: wgpu::RenderPipeline,
atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
layer_cache: HashMap<LayerId, LayerGpuCache>,
active_layer_ids: std::collections::HashSet<LayerId>,
frame_layer_sizes: HashMap<LayerId, Size>,
composition_scratch: mgui_core::CompositionScratch,
blit_pipeline: wgpu::RenderPipeline,
blit_bgl: wgpu::BindGroupLayout,
blit_sampler: wgpu::Sampler,
backdrop_pipeline: wgpu::RenderPipeline,
backdrop_bgl: wgpu::BindGroupLayout,
format: wgpu::TextureFormat,
pub gpu_profiler: Option<crate::gpu_profiler::GpuProfiler>,
batch_pools: HashMap<(LayerId, u32), LayerBatchPool>,
image_cache: Rc<RefCell<ImageTextureCache>>,
msaa_scratch: HashMap<(u32, u32), wgpu::TextureView>,
stencil_scratch: HashMap<(u32, u32), wgpu::TextureView>,
snapshot_scratch: HashMap<(u32, u32), (wgpu::Texture, wgpu::TextureView)>,
last_stats: RenderStats,
}
pub(crate) struct ImageTextureEntry {
pub _texture: wgpu::Texture,
pub view: wgpu::TextureView,
pub sampler: wgpu::Sampler,
pub last_used: u64,
pub bytes: u64,
}
pub const IMAGE_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
pub use setup::LAYER_TEXTURE_BUDGET_BYTES;
pub use crate::backend_info::ImageTextureStats;
impl Renderer {
pub fn last_stats(&self) -> RenderStats {
self.last_stats
}
pub fn image_texture_stats(&self) -> ImageTextureStats {
let cache = self.image_cache.borrow();
ImageTextureStats {
count: cache.textures.len(),
bytes: cache.textures.values().map(|e| e.bytes).sum(),
budget_bytes: IMAGE_TEXTURE_BUDGET_BYTES,
}
}
}
struct LayerBatchPool {
rect_header: Option<wgpu::Buffer>,
rect_instances: Option<wgpu::Buffer>,
text_header: Option<wgpu::Buffer>,
text_instances: Option<wgpu::Buffer>,
tri_vertex: Option<wgpu::Buffer>,
tri_index: Option<wgpu::Buffer>,
tri_uniform: Option<wgpu::Buffer>,
stencil_vertex: Option<wgpu::Buffer>,
stencil_index: Option<wgpu::Buffer>,
}
pub(crate) struct AtlasGpu {
texture: wgpu::Texture,
view: wgpu::TextureView,
sampler: wgpu::Sampler,
cached_size: (u32, u32),
}
pub(crate) struct RectBatch {
bg: wgpu::BindGroup,
}
pub(crate) struct TriBatch {
bg: wgpu::BindGroup,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct TriUniform {
screen_size: [f32; 2],
_pad0: u32,
_pad1: u32,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct BackdropUniform {
screen: [f32; 2],
_pad: [f32; 2],
rect: [f32; 4],
params: [f32; 4],
tint: [f32; 4],
}
pub(crate) struct TextBatch {
bg: wgpu::BindGroup,
count: u32,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct StencilDraw {
pub vertices: Vec<f32>,
pub indices: Vec<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct StencilAction {
pub draw: u32,
pub level: u32,
pub increment: bool,
}
pub(crate) struct StencilGpu {
pub vertex: wgpu::Buffer,
pub index: wgpu::Buffer,
pub ranges: Vec<(u32, u32)>,
pub bg: wgpu::BindGroup,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct BackdropBlurSpec {
pub rect: Rect,
pub radius: f32,
pub blur_radius: f32,
pub tint: [f32; 4],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DrawOp {
Rect(u32, u32, BlendMode),
Text(u32, u32),
Image(u32),
Mask(u32),
BackdropBlur(u32),
Tri(u32, u32),
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ClipSegment {
pub scissor: Option<[u32; 4]>,
pub ops: Vec<DrawOp>,
pub rect_range: (u32, u32),
pub text_range: (u32, u32),
pub image_range: (u32, u32),
pub stencil_level: u32,
pub stencil_actions: Vec<StencilAction>,
}
pub(crate) struct ImageGroup {
pub texture_id: u32,
pub instances: Vec<TextInstance>,
}
pub(crate) struct ImageBatchDraw {
pub(crate) batch: TextBatch,
}
fn intersect_rect(a: Rect, b: Rect) -> Rect {
let x1 = a.x.max(b.x);
let y1 = a.y.max(b.y);
let x2 = (a.x + a.width).min(b.x + b.width);
let y2 = (a.y + a.height).min(b.y + b.height);
Rect::new(x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0))
}
fn path_bounding_box(vertices: &[mgui_core::paint::Vertex]) -> Rect {
if vertices.is_empty() {
return Rect::new(0.0, 0.0, 0.0, 0.0);
}
let mut min_x = f32::INFINITY;
let mut min_y = f32::INFINITY;
let mut max_x = f32::NEG_INFINITY;
let mut max_y = f32::NEG_INFINITY;
for v in vertices {
min_x = min_x.min(v.x);
min_y = min_y.min(v.y);
max_x = max_x.max(v.x);
max_y = max_y.max(v.y);
}
Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
}
fn rect_intersects_clip(r: &Rect, clip: Option<Rect>) -> bool {
match clip {
None => true,
Some(c) => {
c.width > 0.0
&& c.height > 0.0
&& r.x < c.x + c.width
&& r.x + r.width > c.x
&& r.y < c.y + c.height
&& r.y + r.height > c.y
}
}
}
fn rounded_rect_stencil_mesh(rect: Rect, radius: f32) -> (Vec<f32>, Vec<u32>) {
if rect.width <= 0.0 || rect.height <= 0.0 {
return (Vec::new(), Vec::new());
}
let (x, y, w, h) = (rect.x, rect.y, rect.width, rect.height);
let r = radius.max(0.0).min(w.min(h) * 0.5);
let mut pts: Vec<(f32, f32)> = Vec::new();
if r <= 0.0 {
pts.extend_from_slice(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
} else {
const SEG: u32 = 8;
let arcs = [
(x + w - r, y + r, -std::f32::consts::FRAC_PI_2, 0.0),
(x + w - r, y + h - r, 0.0, std::f32::consts::FRAC_PI_2),
(x + r, y + h - r, std::f32::consts::FRAC_PI_2, std::f32::consts::PI),
(x + r, y + r, std::f32::consts::PI, 3.0 * std::f32::consts::FRAC_PI_2),
];
for &(cx, cy, a0, a1) in &arcs {
for i in 0..=SEG {
let a = a0 + (a1 - a0) * (i as f32 / SEG as f32);
pts.push((cx + r * a.cos(), cy + r * a.sin()));
}
}
if pts.len() > 1 && pts.first() == pts.last() {
pts.pop();
}
}
pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5);
let n = pts.len();
if n < 3 {
return (Vec::new(), Vec::new());
}
let mut verts = Vec::with_capacity((n + 1) * 6);
for &(px, py) in &pts {
verts.extend_from_slice(&[px, py, 1.0, 1.0, 1.0, 1.0]);
}
verts.extend_from_slice(&[x + w * 0.5, y + h * 0.5, 1.0, 1.0, 1.0, 1.0]);
let center = n as u32;
let mut indices = Vec::with_capacity(n * 3);
for i in 0..n as u32 {
indices.extend_from_slice(&[center, i, (i + 1) % n as u32]);
}
(verts, indices)
}
fn clip_to_scissor_px(r: Rect, dpr: f32, tex: (u32, u32)) -> [u32; 4] {
let d = dpr.max(0.0);
let (tw, th) = (tex.0 as f32, tex.1 as f32);
let x0 = (r.x * d).floor().clamp(0.0, tw);
let y0 = (r.y * d).floor().clamp(0.0, th);
let x1 = ((r.x + r.width) * d).ceil().clamp(0.0, tw).max(x0);
let y1 = ((r.y + r.height) * d).ceil().clamp(0.0, th).max(y0);
let x = x0 as u32;
let y = y0 as u32;
let w = (x1 as u32).saturating_sub(x);
let h = (y1 as u32).saturating_sub(y);
[x, y, w, h]
}
type CollectedInstances = (
Vec<RectInstance>,
Vec<TextInstance>,
Vec<ImageGroup>,
Vec<ClipSegment>,
Vec<f32>, Vec<u32>, Vec<StencilDraw>,
Vec<BackdropBlurSpec>,
);
pub(crate) fn collect_instances_segmented(
paint_list: &PaintList,
dpr: f32,
tex_size: (u32, u32),
) -> CollectedInstances {
let mut rects: Vec<RectInstance> = Vec::new();
let mut texts: Vec<TextInstance> = Vec::new();
let mut image_groups: Vec<ImageGroup> = Vec::new();
let mut segments: Vec<ClipSegment> = Vec::new();
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();
let mut pending_stencil: Vec<StencilAction> = Vec::new();
let mut backdrop_blurs: Vec<BackdropBlurSpec> = Vec::new();
let mut path_draw_stack: Vec<Option<u32>> = Vec::new();
let mut clip_depth: u32 = 0;
let mut blend_stack: Vec<BlendMode> = Vec::new();
let mut cur_blend = BlendMode::Normal;
let mut stack: Vec<(Option<Rect>, bool)> = Vec::new();
let mut cur_clip: Option<Rect> = None;
let (mut seg_r, mut seg_t, mut seg_i): (u32, u32, u32) = (0, 0, 0);
let mut ops: Vec<DrawOp> = Vec::new();
macro_rules! close_segment {
() => {
let r_end = rects.len() as u32;
let t_end = texts.len() as u32;
let i_end = image_groups.len() as u32;
if !ops.is_empty() {
segments.push(ClipSegment {
scissor: cur_clip.map(|c| clip_to_scissor_px(c, dpr, tex_size)),
ops: ops.clone(),
rect_range: (seg_r, r_end),
text_range: (seg_t, t_end),
image_range: (seg_i, i_end),
stencil_level: clip_depth,
stencil_actions: std::mem::take(&mut pending_stencil),
});
ops.clear();
}
seg_r = r_end;
seg_t = t_end;
seg_i = i_end;
};
}
fn push_range_op(ops: &mut Vec<DrawOp>, op: DrawOp) {
match op {
DrawOp::Rect(s, e, mode) => {
if let Some(DrawOp::Rect(_, last_end, last_mode)) = ops.last_mut() {
if *last_end == s && *last_mode == mode {
*last_end = e;
return;
}
}
}
DrawOp::Text(s, e) => {
if let Some(DrawOp::Text(_, last_end)) = ops.last_mut() {
if *last_end == s {
*last_end = e;
return;
}
}
}
DrawOp::Tri(s, e) => {
if let Some(DrawOp::Tri(_, last_end)) = ops.last_mut() {
if *last_end == s {
*last_end = e;
return;
}
}
}
DrawOp::Image(_) => {}
DrawOp::Mask(_) => {}
DrawOp::BackdropBlur(_) => {}
}
ops.push(op);
}
macro_rules! push_mask_clip {
($flat:expr, $idxs:expr, $bbox:expr) => {{
clip_depth += 1;
let flat_verts: Vec<f32> = $flat;
let idxs: &[u32] = $idxs;
let draw_index = if !flat_verts.is_empty() && !idxs.is_empty() {
let idx = stencil_draws.len() as u32;
stencil_draws.push(StencilDraw { vertices: flat_verts, indices: idxs.to_vec() });
pending_stencil.push(StencilAction { draw: idx, level: clip_depth, increment: true });
Some(idx)
} else {
None
};
path_draw_stack.push(draw_index);
let bbox: Rect = $bbox;
stack.push((cur_clip, true));
cur_clip = Some(match cur_clip {
Some(outer) => intersect_rect(outer, bbox),
None => bbox,
});
}};
}
macro_rules! pop_mask_clip {
() => {{
if let Some(Some(draw)) = path_draw_stack.pop() {
pending_stencil.push(StencilAction { draw, level: clip_depth, increment: false });
}
clip_depth = clip_depth.saturating_sub(1);
}};
}
for cmd in &paint_list.commands {
match cmd {
PaintCommand::PushBlendMode(mode) => {
blend_stack.push(cur_blend);
cur_blend = *mode;
}
PaintCommand::PopBlendMode => {
cur_blend = blend_stack.pop().unwrap_or(BlendMode::Normal);
}
PaintCommand::PushClip(r) => {
close_segment!();
stack.push((cur_clip, false));
cur_clip = Some(match cur_clip {
Some(outer) => intersect_rect(outer, *r),
None => *r,
});
}
PaintCommand::PushClipRRect { rect, radius } => {
close_segment!();
let (flat_verts, idxs) = rounded_rect_stencil_mesh(*rect, *radius);
push_mask_clip!(flat_verts, &idxs, *rect);
}
PaintCommand::PopClip => {
close_segment!();
let (prev, is_mask) = stack.pop().unwrap_or((None, false));
if is_mask {
pop_mask_clip!();
}
cur_clip = prev;
}
PaintCommand::PushClipPath { vertices, indices } => {
close_segment!();
let mut flat_verts: Vec<f32> = Vec::with_capacity(vertices.len() * 6);
for v in vertices {
flat_verts.push(v.x);
flat_verts.push(v.y);
flat_verts.push(v.color.r);
flat_verts.push(v.color.g);
flat_verts.push(v.color.b);
flat_verts.push(v.color.a);
}
push_mask_clip!(flat_verts, indices, path_bounding_box(vertices));
}
PaintCommand::PopClipPath => {
close_segment!();
let (prev, is_mask) = stack.pop().unwrap_or((None, false));
if is_mask {
pop_mask_clip!();
}
cur_clip = prev;
}
PaintCommand::Rect { rect, color, radius } => {
if rect_intersects_clip(rect, cur_clip) {
let start = rects.len() as u32;
rects.push(RectInstance {
rect: [rect.x, rect.y, rect.width, rect.height],
from: [color.r, color.g, color.b, color.a],
to: [color.r, color.g, color.b, color.a],
grad: [0.0; 4],
params: [*radius, 0.0, 0.0, 0.0],
});
push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
}
}
PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
if rect_intersects_clip(rect, cur_clip) {
let start = rects.len() as u32;
rects.push(RectInstance {
rect: [rect.x, rect.y, rect.width, rect.height],
from: [color.r, color.g, color.b, color.a],
to: [color.r, color.g, color.b, color.a],
grad: [0.0; 4],
params: [*radius, 0.0, *blur_radius, 0.0],
});
push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
}
}
PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
if rect_intersects_clip(rect, cur_clip) {
let idx = rects.len() as u32;
rects.push(RectInstance {
rect: [rect.x, rect.y, rect.width, rect.height],
from: [color.r, color.g, color.b, color.a],
to: [color.r, color.g, color.b, color.a],
grad: [0.0; 4],
params: [*radius, 3.0, *blur_radius, 0.0],
});
push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
}
}
PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
if rect_intersects_clip(rect, cur_clip) {
let idx = rects.len() as u32;
rects.push(RectInstance {
rect: [rect.x, rect.y, rect.width, rect.height],
from: [from.r, from.g, from.b, from.a],
to: [to.r, to.g, to.b, to.a],
grad: [start.x, start.y, end.x, end.y],
params: [*corner_radius, 1.0, 0.0, 0.0],
});
push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
}
}
PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
if rect_intersects_clip(rect, cur_clip) {
let idx = rects.len() as u32;
rects.push(RectInstance {
rect: [rect.x, rect.y, rect.width, rect.height],
from: [from.r, from.g, from.b, from.a],
to: [to.r, to.g, to.b, to.a],
grad: [center.x, center.y, *radial_radius, 0.0],
params: [*corner_radius, 2.0, 0.0, 0.0],
});
push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
}
}
PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
if rect_intersects_clip(rect, cur_clip) {
let idx = backdrop_blurs.len() as u32;
backdrop_blurs.push(BackdropBlurSpec {
rect: *rect,
radius: *radius,
blur_radius: *blur_radius,
tint: [tint.r, tint.g, tint.b, tint.a],
});
ops.push(DrawOp::BackdropBlur(idx));
}
}
PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
if *alpha > 0.0 && rect_intersects_clip(rect, cur_clip) {
let gi = image_groups.len() as u32;
image_groups.push(ImageGroup {
texture_id: *texture_id,
instances: vec![TextInstance {
rect: [rect.x, rect.y, rect.width, rect.height],
color: [1.0, 1.0, 1.0, alpha.clamp(0.0, 1.0)],
uv: *uv,
mode: 2.0,
_pad: [0.0; 3],
}],
});
ops.push(DrawOp::Mask(gi));
}
}
PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
if rect_intersects_clip(rect, cur_clip) {
let snap = |v: f32| (v * dpr).round() / dpr;
let inst = TextInstance {
rect: [
snap(rect.x),
snap(rect.y),
snap(rect.x + rect.width) - snap(rect.x),
snap(rect.y + rect.height) - snap(rect.y),
],
color: [color.r, color.g, color.b, color.a],
uv: *uv,
mode: match mode {
TextureMode::Mask => 0.0,
TextureMode::Color => 1.0,
},
_pad: [0.0; 3],
};
if *texture_id == 0 {
let start = texts.len() as u32;
texts.push(inst);
push_range_op(&mut ops, DrawOp::Text(start, start + 1));
} else {
let reuse_group = ops
.last()
.and_then(|op| match op {
DrawOp::Image(gi) => Some(*gi),
_ => None,
})
.filter(|&gi| image_groups[gi as usize].texture_id == *texture_id);
if let Some(gi) = reuse_group {
image_groups[gi as usize].instances.push(inst);
} else {
let gi = image_groups.len() as u32;
image_groups.push(ImageGroup { texture_id: *texture_id, instances: vec![inst] });
ops.push(DrawOp::Image(gi));
}
}
}
}
PaintCommand::Triangles { vertices, indices } => {
let idx_start = tri_indices.len() as u32;
for v in vertices {
tri_vertices.push(v.x);
tri_vertices.push(v.y);
tri_vertices.push(v.color.r);
tri_vertices.push(v.color.g);
tri_vertices.push(v.color.b);
tri_vertices.push(v.color.a);
}
for &idx in indices {
tri_indices.push(tri_base_vertex + idx);
}
tri_base_vertex += vertices.len() as u32;
if !vertices.is_empty() && !indices.is_empty() {
push_range_op(&mut ops, DrawOp::Tri(idx_start, tri_indices.len() as u32));
}
}
PaintCommand::Text { text, range, font_size, color, position, max_width } => {
let mut temp_list = PaintList::new();
crate::text::paint_text_span(text, *range, *font_size, *color, *position, &mut temp_list, *max_width);
let snap = |v: f32| (v * dpr).round() / dpr;
let start = texts.len() as u32;
for cmd in temp_list.commands {
if let PaintCommand::TexturedRect { rect, color, uv, texture_id: 0, .. } = cmd {
if rect_intersects_clip(&rect, cur_clip) {
texts.push(TextInstance {
rect: [
snap(rect.x),
snap(rect.y),
snap(rect.x + rect.width) - snap(rect.x),
snap(rect.y + rect.height) - snap(rect.y),
],
color: [color.r, color.g, color.b, color.a],
uv,
mode: 0.0,
_pad: [0.0; 3],
});
}
}
}
if texts.len() as u32 > start {
push_range_op(&mut ops, DrawOp::Text(start, texts.len() as u32));
}
}
}
}
close_segment!();
let _ = (seg_r, seg_t, seg_i);
let mut merged: Vec<ClipSegment> = Vec::with_capacity(segments.len());
for seg in segments.drain(..) {
let can_merge = merged.last().is_some_and(|prev: &ClipSegment| {
prev.scissor == seg.scissor && prev.stencil_level == seg.stencil_level && seg.stencil_actions.is_empty()
});
if can_merge {
let prev = merged.last_mut().expect("checked non-empty");
for op in &seg.ops {
push_range_op(&mut prev.ops, *op);
}
prev.rect_range.1 = seg.rect_range.1;
prev.text_range.1 = seg.text_range.1;
prev.image_range.1 = seg.image_range.1;
} else {
merged.push(seg);
}
}
(rects, texts, image_groups, merged, tri_vertices, tri_indices, stencil_draws, backdrop_blurs)
}
mod batches;
mod composition;
mod render;
mod setup;
#[cfg(test)]
mod tests;