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, TextureFrameMeta};
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///
33/// **`stride` 是一等信息,不是优化项**(0.4 §V-P0-1 / RT-01):解码器(FFmpeg 等)
34/// 输出的行常带对齐 padding,`stride > width * 4` 是常态。以前没有这个字段,
35/// 运行时只能假设 packed(`bytes_per_row = 4 * width`),于是每一帧都得先在 CPU 上
36/// 整帧重打包一次(1080p 就是 7.9 MiB/帧)。现在两端都按 `stride` 读,直接透传即可。
37#[derive(Clone)]
38pub struct ImageData {
39    pub rgba: Vec<u8>,
40    pub width: u32,
41    pub height: u32,
42    /// 行距(字节)。`0` 视为 packed(`width * 4`),由 [`ImageData::row_bytes`] 归一。
43    pub stride: usize,
44}
45
46impl ImageData {
47    /// 从 packed(无行 padding)缓冲构造:`stride == width * 4`。
48    pub fn new(rgba: Vec<u8>, width: u32, height: u32) -> Self {
49        Self { rgba, width, height, stride: 0 }
50    }
51
52    /// 从带行 padding 的缓冲构造(解码器输出走这条)。
53    ///
54    /// 不做隐式重打包 —— 静默拷贝整帧正是我们要消掉的开销。约束违反是调用方的
55    /// 编程错误,在 debug 构建里直接 panic,release 下由绘制端按 `row_bytes` 夹紧。
56    pub fn with_stride(rgba: Vec<u8>, width: u32, height: u32, stride: usize) -> Self {
57        debug_assert!(stride >= width as usize * 4, "stride({stride}) 小于 width*4,行会互相覆盖");
58        debug_assert!(rgba.len() >= stride.saturating_mul(height as usize), "rgba 长度不足 stride*height");
59        Self { rgba, width, height, stride }
60    }
61
62    /// 实际行距(字节)。`stride == 0` 表示 packed。
63    pub fn row_bytes(&self) -> usize {
64        if self.stride == 0 {
65            (self.width as usize) * 4
66        } else {
67            self.stride
68        }
69    }
70
71    /// 是否是 packed 缓冲(无行 padding)。
72    pub fn is_packed(&self) -> bool {
73        self.row_bytes() == (self.width as usize) * 4
74    }
75
76    /// 缓冲至少需要的字节数。
77    pub fn min_len(&self) -> usize {
78        self.row_bytes().saturating_mul(self.height as usize)
79    }
80
81    /// 第 `y` 行的字节切片;越界或缓冲不足时返回空切片(绘制端据此跳过坏行)。
82    pub fn row(&self, y: usize) -> &[u8] {
83        let pitch = self.row_bytes();
84        let start = y.checked_mul(pitch);
85        match start {
86            Some(s) if s + pitch <= self.rgba.len() && y < self.height as usize => &self.rgba[s..s + pitch],
87            _ => &[],
88        }
89    }
90
91    /// 纯色图(测试/占位用)
92    pub fn solid(width: u32, height: u32, color: Color) -> Self {
93        let mut rgba = Vec::with_capacity((width * height * 4) as usize);
94        for _ in 0..width * height {
95            rgba.extend_from_slice(&[
96                (color.r * 255.0) as u8,
97                (color.g * 255.0) as u8,
98                (color.b * 255.0) as u8,
99                (color.a * 255.0) as u8,
100            ]);
101        }
102        Self { rgba, width, height, stride: 0 }
103    }
104
105    /// 像素数(宽 × 高)
106    pub fn pixel_count(&self) -> u32 {
107        self.width * self.height
108    }
109}
110
111impl std::fmt::Debug for ImageData {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        f.debug_struct("ImageData")
114            .field("width", &self.width)
115            .field("height", &self.height)
116            .field("bytes", &self.rgba.len())
117            .field("stride", &self.row_bytes())
118            .finish()
119    }
120}
121
122// =================================================================
123// 动态纹理更新契约(0.4 V-P0-1 / RT-01)
124// =================================================================
125
126/// 一张图片纹理在"同一个 `texture_id` 又来了一次 register"时该怎么处理。
127///
128/// **GPU 与软件后端必须走同一个判断**(`ROADMAP_0.4.md` §2.2 V-P0-1 的修复契约):
129/// 以前 GPU 端同 id 直接 return(新帧永远传不上去),软件端却按 `Rc` 身份重建缓存,
130/// 两个后端语义不一致 —— 把这段判断收进一个纯函数,不一致就没有藏身之处了。
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum TextureUpdate {
133    /// 同一份源数据、同一尺寸:纹理原样复用,什么都不做。
134    Reuse,
135    /// 新帧、尺寸不变:只覆盖纹理内容(不重建纹理、不换 view)。
136    UpdateContent,
137    /// 尺寸变了(或首次出现):重建纹理。
138    Recreate,
139}
140
141/// `Rc<ImageData>` 的身份。存进缓存的同时**必须把 `Rc` 本身留住**,
142/// 否则释放后地址被复用,会把"另一张图"误判成"同一帧"。
143pub fn image_identity(data: &Rc<ImageData>) -> usize {
144    Rc::as_ptr(data) as *const u8 as usize
145}
146
147/// 该不该更新纹理。**无 GPU、无分配,纯函数**,所以两端与单测看的是同一条规则。
148///
149/// - `have = None` → 首次注册,`Recreate`。
150/// - 身份相同且尺寸相同 → `Reuse`。
151/// - 身份相同但尺寸变了 → `Recreate`(同一份 `Rc` 被调用方就地改宽高的用法不受支持;
152///   支持它需要额外的一致性保证,而视频侧本来就是每帧一个新帧对象)。
153/// - 身份不同 → 尺寸相同 `UpdateContent`,尺寸不同 `Recreate`。
154pub fn plan_texture_update(have: Option<(usize, u32, u32)>, want: (usize, u32, u32)) -> TextureUpdate {
155    let Some((prev_id, prev_w, prev_h)) = have else {
156        return TextureUpdate::Recreate;
157    };
158    let (_, w, h) = want;
159    if prev_id == want.0 {
160        // 同一份数据:只有尺寸变了才需要重建(帧内容就地被改是不被支持的用法)。
161        return if prev_w == w && prev_h == h { TextureUpdate::Reuse } else { TextureUpdate::Recreate };
162    }
163    if prev_w == w && prev_h == h {
164        TextureUpdate::UpdateContent
165    } else {
166        TextureUpdate::Recreate
167    }
168}
169
170/// 图片填充模式
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
172pub enum BoxFit {
173    /// 拉伸到 widget 尺寸(可能变形)
174    #[default]
175    Fill,
176    /// 等比缩放到完全放进 widget,居中(letterbox)
177    Contain,
178}
179
180// =================================================================
181// ImageRenderObject
182// =================================================================
183
184/// 图片 RO:paint 输出一条 `TexturedRect`(uv 全图,texture_id 非 0)
185pub struct ImageRenderObject {
186    pub image: Rc<ImageData>,
187    pub texture_id: u32,
188    pub width: Option<f32>,
189    pub height: Option<f32>,
190    pub fit: BoxFit,
191    pub element_id: Option<ElementId>,
192    /// widget 尺寸(layout 结果)
193    pub cached_size: Size,
194    /// 实际绘制矩形(widget 本地坐标;Contain 时是居中后的等比矩形)
195    pub dst_rect: Rect,
196    /// 可选的视频帧观测元数据。静态图片恒为 `None`;视频侧在换帧时一并刷新。
197    pub meta: Option<TextureFrameMeta>,
198}
199
200impl ImageRenderObject {
201    pub fn new(image: Rc<ImageData>, texture_id: u32, width: Option<f32>, height: Option<f32>, fit: BoxFit) -> Self {
202        Self {
203            image,
204            texture_id,
205            width,
206            height,
207            fit,
208            element_id: None,
209            cached_size: Size::ZERO,
210            dst_rect: Rect::new(0.0, 0.0, 0.0, 0.0),
211            meta: None,
212        }
213    }
214
215    /// 视频专用:paint 时把共享格当前最新帧号一起带进元数据。
216    ///
217    /// 为什么另开一个方法而不是改 `RenderObject::paint` 的签名:trait 方法是 `&self`,
218    /// 静态图片 / SVG 不需要这一格,也不该为它引入 `Cell`。视频 RO 在 paint 前读一次
219    /// 共享格,就能让 `TextureFrameMeta.latest_seq` 与声明出去的 `sequence` 形成对照。
220    pub fn paint_with_latest_seq(&self, offset: Point, painter: &mut PaintList, latest_seq: u64) {
221        self.paint_impl(offset, painter, Some(latest_seq));
222    }
223
224    fn paint_impl(&self, offset: Point, painter: &mut PaintList, latest_seq: Option<u64>) {
225        let d = self.dst_rect;
226        if d.width <= 0.0 || d.height <= 0.0 {
227            return;
228        }
229        // 1. 声明纹理(renderer render 开始前 drain + register_image,幂等)
230        let meta = self.meta.map(|mut m| {
231            if let Some(s) = latest_seq {
232                m.latest_seq = s;
233            }
234            m
235        });
236        match meta {
237            Some(m) => painter.push_texture_with_meta(self.texture_id, Rc::clone(&self.image), m),
238            None => painter.push_texture(self.texture_id, Rc::clone(&self.image)),
239        }
240        // 2. TexturedRect quad 绘制
241        painter.push(PaintCommand::TexturedRect {
242            rect: Rect::new(offset.x + d.x, offset.y + d.y, d.width, d.height),
243            color: Color::WHITE,
244            uv: [0.0, 0.0, 1.0, 1.0],
245            texture_id: self.texture_id,
246            mode: crate::paint::TextureMode::Color,
247        });
248    }
249}
250
251impl RenderObject for ImageRenderObject {
252    fn layout(&mut self, constraints: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
253        let natural_w = self.image.width as f32;
254        let natural_h = self.image.height as f32;
255        let want = Size::new(self.width.unwrap_or(natural_w), self.height.unwrap_or(natural_h));
256        self.cached_size = constraints.constrain(want);
257
258        // 绘制矩形依 fit(全在 widget 本地坐标)
259        self.dst_rect = match self.fit {
260            BoxFit::Fill => Rect::new(0.0, 0.0, self.cached_size.width, self.cached_size.height),
261            BoxFit::Contain => {
262                if natural_w <= 0.0
263                    || natural_h <= 0.0
264                    || self.cached_size.width <= 0.0
265                    || self.cached_size.height <= 0.0
266                {
267                    Rect::new(0.0, 0.0, 0.0, 0.0)
268                } else {
269                    let scale = (self.cached_size.width / natural_w).min(self.cached_size.height / natural_h);
270                    let dw = natural_w * scale;
271                    let dh = natural_h * scale;
272                    Rect::new((self.cached_size.width - dw) / 2.0, (self.cached_size.height - dh) / 2.0, dw, dh)
273                }
274            }
275        };
276        self.cached_size
277    }
278
279    fn content_size(&self) -> Size {
280        self.cached_size
281    }
282
283    fn paint(&self, offset: Point, painter: &mut PaintList) {
284        self.paint_impl(offset, painter, None);
285    }
286
287    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
288        // 命中 = 绘制矩形内(Contain 的 letterbox 区域不算)
289        let rect = Rect::new(
290            offset.x + self.dst_rect.x,
291            offset.y + self.dst_rect.y,
292            self.dst_rect.width,
293            self.dst_rect.height,
294        );
295        if rect.contains(position) {
296            self.element_id
297        } else {
298            None
299        }
300    }
301
302    fn set_element_id(&mut self, id: ElementId) {
303        self.element_id = Some(id);
304    }
305
306    fn element_id(&self) -> Option<ElementId> {
307        self.element_id
308    }
309
310    fn children_count(&self) -> usize {
311        0
312    }
313}
314
315// #[cfg(test)] 已迁到 crates/mgui-test/tests/image.rs