mgui-core 0.3.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};
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 字节)
#[derive(Clone)]
pub struct ImageData {
    pub rgba: Vec<u8>,
    pub width: u32,
    pub height: u32,
}

impl ImageData {
    /// 纯色图(测试/占位用)
    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 }
    }

    /// 像素数(宽 × 高)
    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())
            .finish()
    }
}

/// 图片填充模式
#[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,
}

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),
        }
    }
}

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) {
        let d = self.dst_rect;
        if d.width <= 0.0 || d.height <= 0.0 {
            return;
        }
        // 1. 声明纹理(renderer render 开始前 drain + register_image,幂等)
        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,
        });
    }

    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