mgui-core 0.8.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! 图片基础设施(阶段 6:图片渲染)
//!
//! 架构:
//! - core 只持有 **解码后的 RGBA 数据**(`ImageData`)与 `texture_id`
//!   (全局原子分配,0 保留给 glyph atlas)。文件 IO 与 PNG/JPEG/WebP
//!   解码在 `mgui-components::image_loader`(`image-decode` feature)完成,
//!   core 不碰文件系统与图像解码器。
//! - paint 输出复用 B2 的 `PaintCommand::TexturedRect`(uv 全图 `[0,0,1,1]`,
//!   texture_id = 图片纹理)。runtime 端按 texture_id 分段 set bind group。
//! - `BoxFit::Fill` 拉伸铺满 widget;`BoxFit::Contain` 等比缩放居中
//!   (letterbox,绘制矩形在 layout 时算好存 `dst_rect`)。
//!
//! **ImageWidget 已迁移到 mgui-components crate**。

use std::rc::Rc;
use std::sync::atomic::{AtomicU32, Ordering};

use crate::id::ElementId;
use crate::paint::{PaintCommand, PaintList, TextureFrameMeta};
use crate::render_object::{BoxConstraints, LayoutContext, RenderObject};
use crate::{Color, Point, Rect, Size};

/// 全局图片 id 分配:0 = glyph atlas,图片从 1 开始
static NEXT_IMAGE_ID: AtomicU32 = AtomicU32::new(1);

/// 分配一个全局唯一的图片 texture id
pub fn next_image_id() -> u32 {
    NEXT_IMAGE_ID.fetch_add(1, Ordering::Relaxed)
}

/// 解码后的位图(直排 RGBA8,每像素 4 字节)。
///
/// **`stride` 是一等信息,不是优化项**(0.4 §V-P0-1 / RT-01):解码器(FFmpeg 等)
/// 输出的行常带对齐 padding,`stride > width * 4` 是常态。以前没有这个字段,
/// 运行时只能假设 packed(`bytes_per_row = 4 * width`),于是每一帧都得先在 CPU 上
/// 整帧重打包一次(1080p 就是 7.9 MiB/帧)。现在两端都按 `stride` 读,直接透传即可。
#[derive(Clone)]
pub struct ImageData {
    pub rgba: Vec<u8>,
    pub width: u32,
    pub height: u32,
    /// 行距(字节)。`0` 视为 packed(`width * 4`),由 [`ImageData::row_bytes`] 归一。
    pub stride: usize,
}

impl ImageData {
    /// 从 packed(无行 padding)缓冲构造:`stride == width * 4`。
    pub fn new(rgba: Vec<u8>, width: u32, height: u32) -> Self {
        Self { rgba, width, height, stride: 0 }
    }

    /// 从带行 padding 的缓冲构造(解码器输出走这条)。
    ///
    /// 不做隐式重打包 —— 静默拷贝整帧正是我们要消掉的开销。约束违反是调用方的
    /// 编程错误,在 debug 构建里直接 panic,release 下由绘制端按 `row_bytes` 夹紧。
    pub fn with_stride(rgba: Vec<u8>, width: u32, height: u32, stride: usize) -> Self {
        debug_assert!(stride >= width as usize * 4, "stride({stride}) 小于 width*4,行会互相覆盖");
        debug_assert!(rgba.len() >= stride.saturating_mul(height as usize), "rgba 长度不足 stride*height");
        Self { rgba, width, height, stride }
    }

    /// 实际行距(字节)。`stride == 0` 表示 packed。
    pub fn row_bytes(&self) -> usize {
        if self.stride == 0 {
            (self.width as usize) * 4
        } else {
            self.stride
        }
    }

    /// 是否是 packed 缓冲(无行 padding)。
    pub fn is_packed(&self) -> bool {
        self.row_bytes() == (self.width as usize) * 4
    }

    /// 缓冲至少需要的字节数。
    pub fn min_len(&self) -> usize {
        self.row_bytes().saturating_mul(self.height as usize)
    }

    /// 第 `y` 行的字节切片;越界或缓冲不足时返回空切片(绘制端据此跳过坏行)。
    pub fn row(&self, y: usize) -> &[u8] {
        let pitch = self.row_bytes();
        let start = y.checked_mul(pitch);
        match start {
            Some(s) if s + pitch <= self.rgba.len() && y < self.height as usize => &self.rgba[s..s + pitch],
            _ => &[],
        }
    }

    /// 纯色图(测试/占位用)
    pub fn solid(width: u32, height: u32, color: Color) -> Self {
        let mut rgba = Vec::with_capacity((width * height * 4) as usize);
        for _ in 0..width * height {
            rgba.extend_from_slice(&[
                (color.r * 255.0) as u8,
                (color.g * 255.0) as u8,
                (color.b * 255.0) as u8,
                (color.a * 255.0) as u8,
            ]);
        }
        Self { rgba, width, height, stride: 0 }
    }

    /// 像素数(宽 × 高)
    pub fn pixel_count(&self) -> u32 {
        self.width * self.height
    }
}

impl std::fmt::Debug for ImageData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ImageData")
            .field("width", &self.width)
            .field("height", &self.height)
            .field("bytes", &self.rgba.len())
            .field("stride", &self.row_bytes())
            .finish()
    }
}

// =================================================================
// 动态纹理更新契约(0.4 V-P0-1 / RT-01)
// =================================================================

/// 一张图片纹理在"同一个 `texture_id` 又来了一次 register"时该怎么处理。
///
/// **GPU 与软件后端必须走同一个判断**(`ROADMAP_0.4.md` §2.2 V-P0-1 的修复契约):
/// 以前 GPU 端同 id 直接 return(新帧永远传不上去),软件端却按 `Rc` 身份重建缓存,
/// 两个后端语义不一致 —— 把这段判断收进一个纯函数,不一致就没有藏身之处了。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextureUpdate {
    /// 同一份源数据、同一尺寸:纹理原样复用,什么都不做。
    Reuse,
    /// 新帧、尺寸不变:只覆盖纹理内容(不重建纹理、不换 view)。
    UpdateContent,
    /// 尺寸变了(或首次出现):重建纹理。
    Recreate,
}

/// `Rc<ImageData>` 的身份。存进缓存的同时**必须把 `Rc` 本身留住**,
/// 否则释放后地址被复用,会把"另一张图"误判成"同一帧"。
pub fn image_identity(data: &Rc<ImageData>) -> usize {
    Rc::as_ptr(data) as *const u8 as usize
}

/// 该不该更新纹理。**无 GPU、无分配,纯函数**,所以两端与单测看的是同一条规则。
///
/// - `have = None` → 首次注册,`Recreate`。
/// - 身份相同且尺寸相同 → `Reuse`。
/// - 身份相同但尺寸变了 → `Recreate`(同一份 `Rc` 被调用方就地改宽高的用法不受支持;
///   支持它需要额外的一致性保证,而视频侧本来就是每帧一个新帧对象)。
/// - 身份不同 → 尺寸相同 `UpdateContent`,尺寸不同 `Recreate`。
pub fn plan_texture_update(have: Option<(usize, u32, u32)>, want: (usize, u32, u32)) -> TextureUpdate {
    let Some((prev_id, prev_w, prev_h)) = have else {
        return TextureUpdate::Recreate;
    };
    let (_, w, h) = want;
    if prev_id == want.0 {
        // 同一份数据:只有尺寸变了才需要重建(帧内容就地被改是不被支持的用法)。
        return if prev_w == w && prev_h == h { TextureUpdate::Reuse } else { TextureUpdate::Recreate };
    }
    if prev_w == w && prev_h == h {
        TextureUpdate::UpdateContent
    } else {
        TextureUpdate::Recreate
    }
}

/// 图片填充模式
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BoxFit {
    /// 拉伸到 widget 尺寸(可能变形)
    #[default]
    Fill,
    /// 等比缩放到完全放进 widget,居中(letterbox)
    Contain,
}

// =================================================================
// ImageRenderObject
// =================================================================

/// 图片 RO:paint 输出一条 `TexturedRect`(uv 全图,texture_id 非 0)
pub struct ImageRenderObject {
    pub image: Rc<ImageData>,
    pub texture_id: u32,
    pub width: Option<f32>,
    pub height: Option<f32>,
    pub fit: BoxFit,
    pub element_id: Option<ElementId>,
    /// widget 尺寸(layout 结果)
    pub cached_size: Size,
    /// 实际绘制矩形(widget 本地坐标;Contain 时是居中后的等比矩形)
    pub dst_rect: Rect,
    /// 可选的视频帧观测元数据。静态图片恒为 `None`;视频侧在换帧时一并刷新。
    pub meta: Option<TextureFrameMeta>,
}

impl ImageRenderObject {
    pub fn new(image: Rc<ImageData>, texture_id: u32, width: Option<f32>, height: Option<f32>, fit: BoxFit) -> Self {
        Self {
            image,
            texture_id,
            width,
            height,
            fit,
            element_id: None,
            cached_size: Size::ZERO,
            dst_rect: Rect::new(0.0, 0.0, 0.0, 0.0),
            meta: None,
        }
    }

    /// 视频专用:paint 时把共享格当前最新帧号一起带进元数据。
    ///
    /// 为什么另开一个方法而不是改 `RenderObject::paint` 的签名:trait 方法是 `&self`,
    /// 静态图片 / SVG 不需要这一格,也不该为它引入 `Cell`。视频 RO 在 paint 前读一次
    /// 共享格,就能让 `TextureFrameMeta.latest_seq` 与声明出去的 `sequence` 形成对照。
    pub fn paint_with_latest_seq(&self, offset: Point, painter: &mut PaintList, latest_seq: u64) {
        self.paint_impl(offset, painter, Some(latest_seq));
    }

    fn paint_impl(&self, offset: Point, painter: &mut PaintList, latest_seq: Option<u64>) {
        let d = self.dst_rect;
        if d.width <= 0.0 || d.height <= 0.0 {
            return;
        }
        // 1. 声明纹理(renderer render 开始前 drain + register_image,幂等)
        let meta = self.meta.map(|mut m| {
            if let Some(s) = latest_seq {
                m.latest_seq = s;
            }
            m
        });
        match meta {
            Some(m) => painter.push_texture_with_meta(self.texture_id, Rc::clone(&self.image), m),
            None => painter.push_texture(self.texture_id, Rc::clone(&self.image)),
        }
        // 2. TexturedRect quad 绘制
        painter.push(PaintCommand::TexturedRect {
            rect: Rect::new(offset.x + d.x, offset.y + d.y, d.width, d.height),
            color: Color::WHITE,
            uv: [0.0, 0.0, 1.0, 1.0],
            texture_id: self.texture_id,
            mode: crate::paint::TextureMode::Color,
        });
    }
}

impl RenderObject for ImageRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
        let natural_w = self.image.width as f32;
        let natural_h = self.image.height as f32;
        let want = Size::new(self.width.unwrap_or(natural_w), self.height.unwrap_or(natural_h));
        self.cached_size = constraints.constrain(want);

        // 绘制矩形依 fit(全在 widget 本地坐标)
        self.dst_rect = match self.fit {
            BoxFit::Fill => Rect::new(0.0, 0.0, self.cached_size.width, self.cached_size.height),
            BoxFit::Contain => {
                if natural_w <= 0.0
                    || natural_h <= 0.0
                    || self.cached_size.width <= 0.0
                    || self.cached_size.height <= 0.0
                {
                    Rect::new(0.0, 0.0, 0.0, 0.0)
                } else {
                    let scale = (self.cached_size.width / natural_w).min(self.cached_size.height / natural_h);
                    let dw = natural_w * scale;
                    let dh = natural_h * scale;
                    Rect::new((self.cached_size.width - dw) / 2.0, (self.cached_size.height - dh) / 2.0, dw, dh)
                }
            }
        };
        self.cached_size
    }

    fn content_size(&self) -> Size {
        self.cached_size
    }

    fn paint(&self, offset: Point, painter: &mut PaintList) {
        self.paint_impl(offset, painter, None);
    }

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        // 命中 = 绘制矩形内(Contain 的 letterbox 区域不算)
        let rect = Rect::new(
            offset.x + self.dst_rect.x,
            offset.y + self.dst_rect.y,
            self.dst_rect.width,
            self.dst_rect.height,
        );
        if rect.contains(position) {
            self.element_id
        } else {
            None
        }
    }

    fn set_element_id(&mut self, id: ElementId) {
        self.element_id = Some(id);
    }

    fn element_id(&self) -> Option<ElementId> {
        self.element_id
    }

    fn children_count(&self) -> usize {
        0
    }
}

// #[cfg(test)] 已迁到 crates/mgui-test/tests/image.rs