Skip to main content

mgui_core/
image.rs

1//! 图片基础设施(阶段 6:图片渲染)
2//!
3//! 架构:
4//! - core 只持有 **解码后的 RGBA 数据**(`ImageData`)与 `texture_id`
5//!   (全局原子分配,0 保留给 glyph atlas)。文件 IO 与 PNG/JPEG/WebP
6//!   解码在 `mgui-components::image_loader`(`image-decode` feature)完成,
7//!   core 不碰文件系统与图像解码器。
8//! - paint 输出复用 B2 的 `PaintCommand::TexturedRect`(uv 全图 `[0,0,1,1]`,
9//!   texture_id = 图片纹理)。runtime 端按 texture_id 分段 set bind group。
10//! - `BoxFit::Fill` 拉伸铺满 widget;`BoxFit::Contain` 等比缩放居中
11//!   (letterbox,绘制矩形在 layout 时算好存 `dst_rect`)。
12//!
13//! **ImageWidget 已迁移到 mgui-components crate**。
14
15use std::rc::Rc;
16use std::sync::atomic::{AtomicU32, Ordering};
17
18use crate::id::ElementId;
19use crate::paint::{PaintCommand, PaintList};
20use crate::render_object::{BoxConstraints, LayoutContext, RenderObject};
21use crate::{Color, Point, Rect, Size};
22
23/// 全局图片 id 分配:0 = glyph atlas,图片从 1 开始
24static NEXT_IMAGE_ID: AtomicU32 = AtomicU32::new(1);
25
26/// 分配一个全局唯一的图片 texture id
27pub fn next_image_id() -> u32 {
28    NEXT_IMAGE_ID.fetch_add(1, Ordering::Relaxed)
29}
30
31/// 解码后的位图(直排 RGBA8,每像素 4 字节)
32#[derive(Clone)]
33pub struct ImageData {
34    pub rgba: Vec<u8>,
35    pub width: u32,
36    pub height: u32,
37}
38
39impl ImageData {
40    /// 纯色图(测试/占位用)
41    pub fn solid(width: u32, height: u32, color: Color) -> Self {
42        let mut rgba = Vec::with_capacity((width * height * 4) as usize);
43        for _ in 0..width * height {
44            rgba.extend_from_slice(&[
45                (color.r * 255.0) as u8,
46                (color.g * 255.0) as u8,
47                (color.b * 255.0) as u8,
48                (color.a * 255.0) as u8,
49            ]);
50        }
51        Self { rgba, width, height }
52    }
53
54    /// 像素数(宽 × 高)
55    pub fn pixel_count(&self) -> u32 {
56        self.width * self.height
57    }
58}
59
60impl std::fmt::Debug for ImageData {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        f.debug_struct("ImageData")
63            .field("width", &self.width)
64            .field("height", &self.height)
65            .field("bytes", &self.rgba.len())
66            .finish()
67    }
68}
69
70/// 图片填充模式
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72pub enum BoxFit {
73    /// 拉伸到 widget 尺寸(可能变形)
74    #[default]
75    Fill,
76    /// 等比缩放到完全放进 widget,居中(letterbox)
77    Contain,
78}
79
80// =================================================================
81// ImageRenderObject
82// =================================================================
83
84/// 图片 RO:paint 输出一条 `TexturedRect`(uv 全图,texture_id 非 0)
85pub struct ImageRenderObject {
86    pub image: Rc<ImageData>,
87    pub texture_id: u32,
88    pub width: Option<f32>,
89    pub height: Option<f32>,
90    pub fit: BoxFit,
91    pub element_id: Option<ElementId>,
92    /// widget 尺寸(layout 结果)
93    pub cached_size: Size,
94    /// 实际绘制矩形(widget 本地坐标;Contain 时是居中后的等比矩形)
95    pub dst_rect: Rect,
96}
97
98impl ImageRenderObject {
99    pub fn new(image: Rc<ImageData>, texture_id: u32, width: Option<f32>, height: Option<f32>, fit: BoxFit) -> Self {
100        Self {
101            image,
102            texture_id,
103            width,
104            height,
105            fit,
106            element_id: None,
107            cached_size: Size::ZERO,
108            dst_rect: Rect::new(0.0, 0.0, 0.0, 0.0),
109        }
110    }
111}
112
113impl RenderObject for ImageRenderObject {
114    fn layout(&mut self, constraints: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
115        let natural_w = self.image.width as f32;
116        let natural_h = self.image.height as f32;
117        let want = Size::new(self.width.unwrap_or(natural_w), self.height.unwrap_or(natural_h));
118        self.cached_size = constraints.constrain(want);
119
120        // 绘制矩形依 fit(全在 widget 本地坐标)
121        self.dst_rect = match self.fit {
122            BoxFit::Fill => Rect::new(0.0, 0.0, self.cached_size.width, self.cached_size.height),
123            BoxFit::Contain => {
124                if natural_w <= 0.0
125                    || natural_h <= 0.0
126                    || self.cached_size.width <= 0.0
127                    || self.cached_size.height <= 0.0
128                {
129                    Rect::new(0.0, 0.0, 0.0, 0.0)
130                } else {
131                    let scale = (self.cached_size.width / natural_w).min(self.cached_size.height / natural_h);
132                    let dw = natural_w * scale;
133                    let dh = natural_h * scale;
134                    Rect::new((self.cached_size.width - dw) / 2.0, (self.cached_size.height - dh) / 2.0, dw, dh)
135                }
136            }
137        };
138        self.cached_size
139    }
140
141    fn content_size(&self) -> Size {
142        self.cached_size
143    }
144
145    fn paint(&self, offset: Point, painter: &mut PaintList) {
146        let d = self.dst_rect;
147        if d.width <= 0.0 || d.height <= 0.0 {
148            return;
149        }
150        // 1. 声明纹理(renderer render 开始前 drain + register_image,幂等)
151        painter.push_texture(self.texture_id, Rc::clone(&self.image));
152        // 2. TexturedRect quad 绘制
153        painter.push(PaintCommand::TexturedRect {
154            rect: Rect::new(offset.x + d.x, offset.y + d.y, d.width, d.height),
155            color: Color::WHITE,
156            uv: [0.0, 0.0, 1.0, 1.0],
157            texture_id: self.texture_id,
158            mode: crate::paint::TextureMode::Color,
159        });
160    }
161
162    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
163        // 命中 = 绘制矩形内(Contain 的 letterbox 区域不算)
164        let rect = Rect::new(
165            offset.x + self.dst_rect.x,
166            offset.y + self.dst_rect.y,
167            self.dst_rect.width,
168            self.dst_rect.height,
169        );
170        if rect.contains(position) {
171            self.element_id
172        } else {
173            None
174        }
175    }
176
177    fn set_element_id(&mut self, id: ElementId) {
178        self.element_id = Some(id);
179    }
180
181    fn element_id(&self) -> Option<ElementId> {
182        self.element_id
183    }
184
185    fn children_count(&self) -> usize {
186        0
187    }
188}
189
190// #[cfg(test)] 已迁到 crates/mgui-test/tests/image.rs