#![forbid(unsafe_code)]
mod layers;
#[cfg(feature = "present")]
mod present;
mod raster;
#[cfg(feature = "present")]
pub use present::{rgba_to_xrgb, xrgb, SoftwarePresenter};
use std::collections::HashMap;
use std::rc::Rc;
use mgui_core::composition::CompositionScratch;
use mgui_core::image::ImageData;
use mgui_core::{FramePaint, LayerId, PaintList, Size};
use tiny_skia::Pixmap;
use raster::{GlyphCacheKey, ImageTintKey};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RgbaImage {
pub width: u32,
pub height: u32,
pub data: Vec<u8>,
}
impl RgbaImage {
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
assert!(x < self.width && y < self.height, "pixel ({x},{y}) out of {}x{}", self.width, self.height);
let i = ((y * self.width + x) * 4) as usize;
[self.data[i], self.data[i + 1], self.data[i + 2], self.data[i + 3]]
}
pub fn try_pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
if x >= self.width || y >= self.height {
return None;
}
Some(self.pixel(x, y))
}
}
pub const SOFTWARE_TEXTURE_BUDGET_BYTES: u64 = 128 * 1024 * 1024;
const LAYER_POOL_MAX_BUFFERS: usize = 8;
const LAYER_POOL_MAX_BYTES: u64 = 32 * 1024 * 1024;
#[derive(Default)]
struct LayerPixmapPool {
by_size: HashMap<(u32, u32), Vec<Pixmap>>,
count: usize,
bytes: u64,
}
impl LayerPixmapPool {
fn take(&mut self, w: u32, h: u32) -> Option<Pixmap> {
let list = self.by_size.get_mut(&(w, h))?;
let mut pixmap = list.pop()?;
if list.is_empty() {
self.by_size.remove(&(w, h));
}
self.count = self.count.saturating_sub(1);
self.bytes = self.bytes.saturating_sub(pixmap_bytes(&pixmap));
pixmap.fill(tiny_skia::Color::TRANSPARENT);
Some(pixmap)
}
fn put(&mut self, pixmap: Pixmap) {
let bytes = pixmap_bytes(&pixmap);
if self.count >= LAYER_POOL_MAX_BUFFERS || self.bytes + bytes > LAYER_POOL_MAX_BYTES {
return;
}
self.by_size.entry((pixmap.width(), pixmap.height())).or_default().push(pixmap);
self.count += 1;
self.bytes += bytes;
}
}
fn pixmap_bytes(pixmap: &Pixmap) -> u64 {
pixmap.width() as u64 * pixmap.height() as u64 * 4
}
pub struct SoftwareRenderer {
textures: HashMap<u32, (Rc<ImageData>, Pixmap)>,
texture_last_used: HashMap<u32, u64>,
glyph_cache: HashMap<GlyphCacheKey, Pixmap>,
tint_cache: HashMap<ImageTintKey, Pixmap>,
atlas_generation: u64,
frame_clock: u64,
texture_budget: u64,
target: Option<Pixmap>,
layer_pool: LayerPixmapPool,
composition_scratch: CompositionScratch,
composition_sizes: HashMap<LayerId, Size>,
}
impl Default for SoftwareRenderer {
fn default() -> Self {
Self {
textures: HashMap::new(),
texture_last_used: HashMap::new(),
glyph_cache: HashMap::new(),
tint_cache: HashMap::new(),
atlas_generation: 0,
frame_clock: 0,
texture_budget: SOFTWARE_TEXTURE_BUDGET_BYTES,
target: None,
layer_pool: LayerPixmapPool::default(),
composition_scratch: CompositionScratch::default(),
composition_sizes: HashMap::new(),
}
}
}
impl SoftwareRenderer {
pub fn new() -> Self {
Self::default()
}
pub fn set_texture_budget(&mut self, bytes: u64) {
self.texture_budget = bytes;
}
pub fn register_texture(&mut self, id: u32, data: Rc<ImageData>) {
self.insert_texture(id, data);
}
pub fn render(&mut self, frame: &FramePaint, logical_size: Size, scale_factor: f32) -> RgbaImage {
let mut out = RgbaImage { width: 0, height: 0, data: Vec::new() };
self.render_into(frame, logical_size, scale_factor, &mut out);
out
}
pub fn render_into(&mut self, frame: &FramePaint, logical_size: Size, scale_factor: f32, out: &mut RgbaImage) {
let dpr = scale_factor.max(0.01);
mgui_text::text::set_text_dpr(dpr);
self.begin_frame();
for lp in &frame.sub_layers {
self.register_pending(&lp.paint_list);
}
let pw = physical(logical_size.width, dpr);
let ph = physical(logical_size.height, dpr);
let mut target = self.take_render_target(pw, ph);
self.composition_sizes.clear();
for lp in &frame.sub_layers {
self.composition_sizes.insert(lp.layer_id, layers::layer_size(lp, logical_size));
}
let mut scratch = std::mem::take(&mut self.composition_scratch);
scratch.resolve(&frame.sub_layers, &self.composition_sizes);
for lp in &frame.sub_layers {
let size = layers::layer_size(lp, logical_size);
if size.width <= 0.0 || size.height <= 0.0 {
continue;
}
let lw = physical(size.width, dpr);
let lh = physical(size.height, dpr);
let Some(mut layer_pix) = self.take_layer_pixmap(lw, lh) else { continue };
self.rasterize(&mut layer_pix, &lp.paint_list, dpr);
if let Some(comp) = scratch.get(lp.layer_id) {
let mask = layers::build_clip_mask(comp, logical_size, dpr);
layers::composite(&mut target, &layer_pix, comp, size, logical_size, dpr, mask.as_ref());
}
self.layer_pool.put(layer_pix);
}
self.composition_scratch = scratch;
self.evict_textures();
raster::pixmap_to_rgba_into(&target, &mut out.data);
out.width = pw;
out.height = ph;
self.target = Some(target);
}
pub fn render_list(&mut self, list: &PaintList, logical_size: Size, scale_factor: f32) -> RgbaImage {
let dpr = scale_factor.max(0.01);
mgui_text::text::set_text_dpr(dpr);
self.begin_frame();
self.register_pending(list);
let pw = physical(logical_size.width, dpr);
let ph = physical(logical_size.height, dpr);
let mut pix = self.take_render_target(pw, ph);
self.rasterize(&mut pix, list, dpr);
self.evict_textures();
let data = raster::pixmap_to_rgba(&pix);
self.target = Some(pix);
RgbaImage { width: pw, height: ph, data }
}
fn take_render_target(&mut self, pw: u32, ph: u32) -> Pixmap {
match self.target.take() {
Some(mut pixmap) if pixmap.width() == pw && pixmap.height() == ph => {
pixmap.fill(tiny_skia::Color::TRANSPARENT);
pixmap
}
_ => Pixmap::new(pw, ph).expect("valid render target size"),
}
}
fn take_layer_pixmap(&mut self, lw: u32, lh: u32) -> Option<Pixmap> {
self.layer_pool.take(lw, lh).or_else(|| Pixmap::new(lw, lh))
}
fn begin_frame(&mut self) {
self.frame_clock = self.frame_clock.wrapping_add(1);
}
fn rasterize(&mut self, target: &mut Pixmap, list: &PaintList, dpr: f32) {
let Self { textures, glyph_cache, tint_cache, atlas_generation, .. } = self;
let prev_generation = *atlas_generation;
let mut r = raster::Raster::new(target, dpr, textures, glyph_cache, tint_cache, *atlas_generation);
r.run(list);
*atlas_generation = r.atlas_generation;
if *atlas_generation != prev_generation {
glyph_cache.retain(|k, _| k.generation == *atlas_generation);
}
}
fn register_pending(&mut self, list: &PaintList) {
for (id, data) in &list.pending_textures {
self.insert_texture(*id, Rc::clone(data));
self.texture_last_used.insert(*id, self.frame_clock);
}
}
fn insert_texture(&mut self, id: u32, data: Rc<ImageData>) {
let needs = match self.textures.get(&id) {
Some((old, _)) => !Rc::ptr_eq(old, &data),
None => true,
};
if !needs {
return;
}
if let Some(pix) = raster::image_to_pixmap(&data) {
self.textures.insert(id, (data, pix));
self.texture_last_used.insert(id, self.frame_clock);
self.tint_cache.retain(|k, _| k.texture_id != id);
}
}
fn evict_textures(&mut self) {
let total: u64 = self.textures.values().map(|(_, pix)| pix.data().len() as u64).sum();
if total <= self.texture_budget {
return;
}
let mut candidates: Vec<(u32, u64, u64)> = self
.textures
.iter()
.filter(|(id, _)| self.texture_last_used.get(id).copied() != Some(self.frame_clock))
.map(|(&id, (_, pix))| (id, self.texture_last_used.get(&id).copied().unwrap_or(0), pix.data().len() as u64))
.collect();
candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
let mut total = total;
for (id, _, bytes) in candidates {
if total <= self.texture_budget {
break;
}
self.textures.remove(&id);
self.texture_last_used.remove(&id);
self.tint_cache.retain(|k, _| k.texture_id != id);
total = total.saturating_sub(bytes);
}
if total > self.texture_budget {
log::warn!(
target: "mgui_startup",
"software texture cache uses {} MiB (budget {} MiB); all remaining textures are in use this frame",
total / (1024 * 1024),
self.texture_budget / (1024 * 1024)
);
}
}
}
fn physical(logical: f32, dpr: f32) -> u32 {
(logical * dpr).round().max(1.0) as u32
}
pub fn render_paint_list(list: &PaintList, size: Size, scale_factor: f32) -> RgbaImage {
SoftwareRenderer::new().render_list(list, size, scale_factor)
}
#[cfg(test)]
mod tests {
use super::*;
use mgui_core::{Color, Rect};
#[test]
fn target_and_layer_pixmap_reuse_preserve_pixels() {
let mut renderer = SoftwareRenderer::new();
let mut list = PaintList::new();
list.rect(Rect::new(0.0, 0.0, 32.0, 32.0), Color::from_rgb8(10, 20, 30));
let a = renderer.render_list(&list, Size::new(32.0, 32.0), 1.0);
let b = renderer.render_list(&list, Size::new(32.0, 32.0), 1.0);
assert_eq!(a.data, b.data, "复用 target/layer 缓冲不得改变像素");
assert_eq!(a.pixel(16, 16), [10, 20, 30, 255]);
let c = renderer.render_list(&list, Size::new(16.0, 16.0), 1.0);
assert_eq!((c.width, c.height), (16, 16), "尺寸变化后 target 必须重建");
assert_eq!(c.pixel(8, 8), [10, 20, 30, 255]);
assert_eq!(a.pixel(16, 16), [10, 20, 30, 255], "旧输出不能被复用缓冲覆盖");
}
#[test]
fn layer_pixmap_pool_reuses_by_size_and_bounds_memory() {
let mut pool = LayerPixmapPool::default();
pool.put(Pixmap::new(16, 16).unwrap());
pool.put(Pixmap::new(32, 16).unwrap());
assert_eq!(pool.count, 2);
assert_eq!(pool.bytes, (16 * 16 + 32 * 16) * 4);
let a = pool.take(16, 16).expect("16x16 should be reused");
assert_eq!((a.width(), a.height()), (16, 16));
assert_eq!(pool.count, 1);
pool.put(a);
assert_eq!(pool.count, 2);
let huge = Pixmap::new(3000, 3000).unwrap();
pool.put(huge);
assert_eq!(pool.count, 2, "超预算缓冲应直接释放");
}
#[test]
fn texture_cache_evicts_unused_over_budget() {
let mut renderer = SoftwareRenderer::new();
let data = Rc::new(ImageData::solid(16, 16, Color::WHITE));
renderer.begin_frame();
renderer.insert_texture(1, Rc::clone(&data));
renderer.texture_last_used.insert(1, renderer.frame_clock);
renderer.begin_frame();
renderer.insert_texture(2, Rc::clone(&data));
renderer.texture_last_used.insert(2, renderer.frame_clock);
renderer.set_texture_budget(16 * 16 * 4);
renderer.evict_textures();
assert!(renderer.textures.contains_key(&2), "本帧使用的纹理不得淘汰");
assert!(!renderer.textures.contains_key(&1), "超预算时应淘汰未使用的旧纹理");
}
}