Skip to main content

aureole_core/
image.rs

1//! 图片:`image(来源)` 元素。
2//!
3//! - 来源:文件路径、内存里的编码数据(PNG、JPEG、WebP、GIF)、原始 RGBA(8 位 sRGB 或线性浮点);可以绑定信号换图。
4//! - 色彩:按嵌的 ICC 配置、PNG 的 cICP 换到工作空间(见 [`color`]):没有配置的按 sRGB;
5//!   广色域、HDR 的图存成半精度浮点的纹理,在广色域、HDR 显示器上原样显示,普通显示器上截断、色调映射。
6//! - 动图(GIF、动态 WebP):所有帧在后台解码好、留在缓存里;每个元素有自己的播放进度和一块当前帧的 GPU 位置,
7//!   换帧时只传新的一帧(见 [`Player`]、`tree/animated.rs`),看不见时不换帧。播放控制见 [`PlaybackHandle`]
8//! - 加载:后台线程解码、预乘、生成 mip(见 [`loader`]、[`pixels`]),好了以后元素自动重新布局、重画;
9//!   同一个来源只解码一次,没人用了就释放(最近用过的留在有预算的缓存里)。
10//! - 绘制:小图放进带 mip 的图片图集,和其他图元同一次 draw call;大图各自一张纹理,画到它时
11//!   断开一次 draw call。都是 sRGB 纹理、预乘 alpha、三线性过滤,缩小的照片不闪烁、不发暗。
12//!   圆角用距离场裁剪,裁剪、分组透明度、合成层、模糊和背景模糊照常适用。
13//!
14//! GPU 资源按窗口(元素树)管理:每棵树记下自己用到的图片放在图集哪里、哪些有单独的纹理,
15//! 和字形图集一样把变化([`scene::ImageUpdate`])交给自己的渲染线程。
16//!
17//! SVG 文件(`svg` 特性)也是一种来源:缓存、后台解析、大小、摆放方式、出错都和图片一样,只是解析的结果是一份文档(`svg.rs`),
18//! 画成路径图元(`svg_paint.rs`),不占图片图集;文件里的位图才占。
19
20mod color;
21mod loader;
22mod pixels;
23#[cfg(feature = "svg")]
24mod svg;
25#[cfg(feature = "svg")]
26mod svg_paint;
27
28use std::collections::HashMap;
29use std::fmt;
30use std::path::{Path, PathBuf};
31use std::rc::{Rc, Weak};
32use std::sync::Arc;
33use std::time::Duration;
34
35use animation::Curve;
36use reactive::{Effect, Signal, signal, untracked};
37use scene::{AtlasUpdate, Color, ColorMatrix, DisplayList, IMAGE_ATLAS_LEVELS, ImageData, ImageEncoding, ImageUpdate, Quad, max_atlas_size};
38
39use crate::property::Property;
40use crate::element::Element;
41use crate::geometry::Affine;
42use crate::gradient::Fill;
43
44use crate::property::{IntoProp, PropId, Prop};
45use crate::geometry::Rect;
46use crate::tree::{NodeId, Tree, TreeRef};
47
48pub(crate) use loader::{ImageRef, Status, acquire};
49use pixels::Frames;
50#[cfg(feature = "svg")]
51pub(crate) use svg_paint::SvgTarget;
52
53/// 图片元素。来源可以是路径(`&str`、`String`、`PathBuf`)、[`ImageSource`],
54/// 也可以绑定信号或闭包来换图(新图解码好之前继续显示旧图)。
55///
56/// 没指定大小时用图片的原始大小(1 个像素 = 1 个逻辑像素),只指定一边时按宽高比算另一边;
57/// 解码好之前大小为 0、什么都不画(可以给元素设背景色当占位)。
58///
59/// 打开 `svg` 特性时也认得 SVG 文件(按内容认,不看扩展名):大小用文件写的大小,按需要的缩放画成矢量路径,放大也清晰。
60/// 没打开时进入出错状态,原因里写明要打开这个特性。
61///
62/// ```no_run
63/// # use aureole::prelude::*;
64/// let state = signal(ImageState::Loading);
65/// image("photos/cat.jpg")
66///     .size(240, 160)
67///     .fit(ImageFit::Cover)        // 等比铺满内容区,裁掉多余的部分
68///     .radius(12)                  // 圆角裁剪图片
69///     .image_fade(Tween::new(ms(250)))     // 解码好后淡入
70///     .report_load_state(state);          // 加载状态和原始大小写进信号
71/// ```
72pub fn image<V: Into<ImageSource> + 'static>(source: impl IntoProp<V>) -> Element {
73    Element::from_kind(ImageBlock::default()).set(crate::property::SOURCE, source)
74}
75
76/// 图片从哪来。克隆便宜(数据都是共享的);同一个来源(同一路径、同一块内存)只解码一次
77#[derive(Clone)]
78pub struct ImageSource {
79    pub(crate) kind: SourceKind,
80    pub(crate) max_size: Option<u32>,
81    /// 文件的修订号(开发工具的图片监视,见 [`set_image_revision_source`]):文件改了以后换一个键,重新解码
82    pub(crate) revision: u64,
83}
84
85#[derive(Clone)]
86pub(crate) enum SourceKind {
87    File(Arc<Path>),
88    Bytes(Arc<[u8]>),
89    Static(&'static [u8]),
90    Rgba { width: u32, height: u32, pixels: Arc<[u8]> },
91    RgbaF32 { width: u32, height: u32, pixels: Arc<[f32]> },
92}
93
94/// 缓存的键:文件按路径,内存数据按地址(同一块数据才共享)
95#[derive(Clone, PartialEq, Eq, Hash, Debug)]
96pub(crate) struct SourceKey {
97    kind: KeyKind,
98    max_size: Option<u32>,
99    revision: u64,
100}
101
102#[derive(Clone, PartialEq, Eq, Hash, Debug)]
103enum KeyKind {
104    File(Arc<Path>),
105    Memory(usize, usize),
106    Rgba(usize, usize, u32),
107}
108
109impl ImageSource {
110    /// 图片文件(PNG、JPEG、WebP、GIF,打开 `svg` 特性时还有 SVG),在后台线程读取和解码
111    pub fn file(path: impl AsRef<Path>) -> Self {
112        Self { kind: SourceKind::File(path.as_ref().into()), max_size: None, revision: 0 }
113    }
114
115    /// 内存里的编码数据(PNG、JPEG、WebP、GIF,打开 `svg` 特性时还有 SVG)。按这块内存区分:要共享解码结果,
116    /// 请克隆同一个 `ImageSource`,而不是每次用同样的字节新建一个
117    pub fn bytes(bytes: impl Into<Arc<[u8]>>) -> Self {
118        Self { kind: SourceKind::Bytes(bytes.into()), max_size: None, revision: 0 }
119    }
120
121    /// 编进程序里的编码数据(`include_bytes!`),不复制
122    pub fn from_static(bytes: &'static [u8]) -> Self {
123        Self { kind: SourceKind::Static(bytes), max_size: None, revision: 0 }
124    }
125
126    /// 原始像素:RGBA8,sRGB,直通(未预乘)alpha,逐行紧密排列
127    pub fn rgba(width: u32, height: u32, pixels: impl Into<Arc<[u8]>>) -> Self {
128        Self { kind: SourceKind::Rgba { width, height, pixels: pixels.into() }, max_size: None, revision: 0 }
129    }
130
131    /// 原始像素:RGBA 各一个 `f32`,线性光、sRGB 原色,直通 alpha,逐行紧密排列。分量可以小于 0
132    /// (sRGB 色域外的颜色,见 [`scene::P3_TO_SRGB`])或大于 1(比 SDR 白亮的 HDR 内容,1.0 是 SDR 白)。
133    /// 存成半精度浮点的纹理(每像素 8 字节,不进图集),显示时按显示器的余量做色调映射
134    pub fn rgba_f32(width: u32, height: u32, pixels: impl Into<Arc<[f32]>>) -> Self {
135        Self { kind: SourceKind::RgbaF32 { width, height, pixels: pixels.into() }, max_size: None, revision: 0 }
136    }
137
138    /// 解码后最长边不超过 `pixels` 像素(等比缩小),省内存和上传时间,例如缩略图墙。
139    /// 布局用的原始大小不变;显示得比它大时会糊。对 SVG 文件不起作用(按显示的大小画)
140    pub fn max_size(mut self, pixels: u32) -> Self {
141        self.max_size = Some(pixels.max(1));
142        self
143    }
144
145    pub(crate) fn key(&self) -> SourceKey {
146        let kind = match &self.kind {
147            SourceKind::File(path) => KeyKind::File(path.clone()),
148            SourceKind::Bytes(bytes) => KeyKind::Memory(bytes.as_ptr() as usize, bytes.len()),
149            SourceKind::Static(bytes) => KeyKind::Memory(bytes.as_ptr() as usize, bytes.len()),
150            SourceKind::Rgba { width, pixels, .. } => KeyKind::Rgba(pixels.as_ptr() as usize, pixels.len(), *width),
151            SourceKind::RgbaF32 { width, pixels, .. } => KeyKind::Rgba(pixels.as_ptr() as usize, pixels.len() * 4, *width),
152        };
153        SourceKey { kind, max_size: self.max_size, revision: self.revision }
154    }
155}
156
157impl PartialEq for ImageSource {
158    fn eq(&self, other: &Self) -> bool {
159        self.key() == other.key()
160    }
161}
162
163impl fmt::Debug for ImageSource {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        match &self.kind {
166            SourceKind::File(path) => write!(f, "ImageSource::file({path:?})")?,
167            SourceKind::Bytes(bytes) => write!(f, "ImageSource::bytes({} 字节)", bytes.len())?,
168            SourceKind::Static(bytes) => write!(f, "ImageSource::from_static({} 字节)", bytes.len())?,
169            SourceKind::Rgba { width, height, .. } => write!(f, "ImageSource::rgba({width}x{height})")?,
170            SourceKind::RgbaF32 { width, height, .. } => write!(f, "ImageSource::rgba_f32({width}x{height})")?,
171        }
172        if let Some(max) = self.max_size {
173            write!(f, ".max_size({max})")?;
174        }
175        Ok(())
176    }
177}
178
179impl From<&str> for ImageSource {
180    fn from(path: &str) -> Self {
181        Self::file(path)
182    }
183}
184
185impl From<String> for ImageSource {
186    fn from(path: String) -> Self {
187        Self::file(path)
188    }
189}
190
191impl From<PathBuf> for ImageSource {
192    fn from(path: PathBuf) -> Self {
193        Self::file(path)
194    }
195}
196
197impl From<&Path> for ImageSource {
198    fn from(path: &Path) -> Self {
199        Self::file(path)
200    }
201}
202
203impl IntoProp<ImageSource> for ImageSource {
204    fn into_prop(self) -> Prop<ImageSource> {
205        Prop::Static(self)
206    }
207}
208
209/// 内存里的一张位图:RGBA8,sRGB,直通(未预乘)alpha,逐行紧密排列。克隆便宜(像素是共享的)。
210/// 剪贴板里读出来的、从别的应用拖进来的图片都是它,能直接给 [`image()`]。
211/// 同一张图(克隆出来的)只解码一次,换一张读出来的算新图
212///
213/// ```no_run
214/// # use aureole::prelude::*;
215/// if let Some(picture) = aureole::clipboard::read_image() {
216///     image(picture).size(240, 160);
217/// }
218/// ```
219#[derive(Clone, PartialEq, Eq)]
220pub struct RgbaImage {
221    /// 宽(像素)
222    pub width: u32,
223    /// 高(像素)
224    pub height: u32,
225    /// 像素,`width × height × 4` 个字节
226    pub pixels: Arc<[u8]>,
227}
228
229impl RgbaImage {
230    /// 一张位图。像素数要和宽高对得上(放进剪贴板时检查,对不上时写入失败)
231    pub fn new(width: u32, height: u32, pixels: impl Into<Arc<[u8]>>) -> Self {
232        Self { width, height, pixels: pixels.into() }
233    }
234}
235
236impl fmt::Debug for RgbaImage {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        write!(f, "RgbaImage({}×{}, {} 字节)", self.width, self.height, self.pixels.len())
239    }
240}
241
242impl From<RgbaImage> for ImageSource {
243    fn from(image: RgbaImage) -> Self {
244        Self::rgba(image.width, image.height, image.pixels)
245    }
246}
247
248impl From<&RgbaImage> for ImageSource {
249    fn from(image: &RgbaImage) -> Self {
250        Self::rgba(image.width, image.height, image.pixels.clone())
251    }
252}
253
254impl IntoProp<RgbaImage> for RgbaImage {
255    fn into_prop(self) -> Prop<RgbaImage> {
256        Prop::Static(self)
257    }
258}
259
260/// 文件路径。`&str`、`String` 只有 `IntoProp<String>` 一个实现(`text("..")` 这类调用才推断得出来),
261/// [`image()`] 收它们靠 `String: Into<ImageSource>`
262impl IntoProp<PathBuf> for PathBuf {
263    fn into_prop(self) -> Prop<PathBuf> {
264        Prop::Static(self)
265    }
266}
267
268/// 图片怎么放进元素的内容区
269#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
270#[non_exhaustive]
271pub enum ImageFit {
272    /// 拉伸到框的大小,不保持宽高比(默认)
273    #[default]
274    Stretch,
275    /// 等比缩放到完整放进去,留白
276    Contain,
277    /// 等比缩放到铺满,裁掉多出来的部分
278    Cover,
279    /// 原始大小,超出的部分裁掉
280    None,
281    /// `None` 和 `Contain` 里较小的那个:只缩小、不放大
282    ScaleDown,
283}
284
285impl IntoProp<ImageFit> for ImageFit {
286    fn into_prop(self) -> Prop<ImageFit> {
287        Prop::Static(self)
288    }
289}
290
291/// 图片的加载状态,见 [`Element::report_load_state`]
292#[derive(Clone, Debug, PartialEq)]
293pub enum ImageState {
294    /// 正在读取或解码
295    Loading,
296    /// 解码好了,`width` x `height` 是原始大小(像素)
297    Ready {
298        /// 原始宽度,像素
299        width: u32,
300        /// 原始高度,像素
301        height: u32,
302    },
303    /// 读不到文件、格式不支持、数据损坏
304    Error(Arc<str>),
305}
306
307impl ImageState {
308    /// 是否已经解码好
309    pub fn is_ready(&self) -> bool {
310        matches!(self, Self::Ready { .. })
311    }
312
313    /// 原始大小(像素),解码好之前为 `None`
314    pub fn size(&self) -> Option<[u32; 2]> {
315        match *self {
316            Self::Ready { width, height } => Some([width, height]),
317            _ => None,
318        }
319    }
320}
321
322/// 图片文件的修订号从哪里来,见 [`set_image_revision_source`]
323type RevisionSource = fn(&std::path::Path) -> u64;
324
325thread_local! {
326    static REVISION_SOURCE: std::cell::Cell<Option<RevisionSource>> = const { std::cell::Cell::new(None) };
327}
328
329/// 在这个线程上装上图片文件的修订号从哪里来(开发工具的图片监视:文件变了修订号加一,图片缓存的键带上它,
330/// 于是重新解码)。函数在图片的绑定里调用,读了它的信号就订阅变化。没装时修订号都是 0
331pub fn set_image_revision_source(source: RevisionSource) {
332    REVISION_SOURCE.with(|s| s.set(Some(source)));
333}
334
335/// 图片文件现在的修订号
336fn image_revision(path: &std::path::Path) -> u64 {
337    REVISION_SOURCE.with(std::cell::Cell::get).map_or(0, |source| source(path))
338}
339
340/// 图片缓存的统计,见 [`image_cache_stats`]
341#[derive(Clone, Copy, Debug, Default, PartialEq)]
342pub struct ImageCacheStats {
343    /// 正在被元素使用的图片(含还在解码的)
344    pub images: usize,
345    /// 其中还在解码的
346    pub loading_images: usize,
347    /// 正在使用的图片的像素(含 mip)占多少字节
348    pub bytes: u64,
349    /// 没人用、但还留着的解码结果(再用到时不用重新解码)
350    pub retained_images: usize,
351    /// 留着的解码结果占多少字节
352    pub retained_bytes: u64,
353    /// 一共解码成功了几张
354    pub decoded_images: usize,
355    /// 解码累计耗时(后台线程上的解码 + 预乘 + mip)
356    pub decode_time: Duration,
357}
358
359/// 当前线程图片缓存的统计
360pub fn image_cache_stats() -> ImageCacheStats {
361    loader::stats()
362}
363
364/// 没人用的解码结果最多留多少字节(默认 64MB),超出时先丢最久没用的;0 表示不留
365pub fn set_image_cache_budget(bytes: u64) {
366    loader::set_budget(bytes as usize);
367}
368
369/// 等这个线程提交的后台解码全部完成(测试、截图用)。按进展等:解码线程池(全进程共用)连续 `stall` 没有解完任何一张
370/// 才算卡住,返回还在等的图片(来源的调试表示)
371pub fn wait_idle(stall: Duration) -> Result<(), Vec<String>> {
372    loader::wait_idle(stall)
373}
374
375/// 动图的播放控制,交给 [`Element::playback_handle`]。像信号一样是 `Copy` 的句柄,可以随便放进闭包;
376/// 一个句柄可以控制几个元素(一起暂停、一起重新播)。
377///
378/// 默认(没调用过 [`PlaybackHandle::play`]、[`PlaybackHandle::pause`])跟着系统:没打开"减少动态效果"时播,
379/// 打开时停在第一帧。用户自己点了播放(`play`)就播,不管这个设置。
380///
381/// ```no_run
382/// # use aureole::prelude::*;
383/// let player = PlaybackHandle::new();
384/// column()
385///     .child(image("loading.gif").size(64, 64).playback_handle(player))
386///     .child(button("重新播").on_click(move || player.restart()))
387///     .child(text(move || if player.is_finished() { "播完了" } else { "" }.to_string()));
388/// ```
389#[derive(Clone, Copy, Debug, PartialEq)]
390pub struct PlaybackHandle {
391    /// `None`:跟着系统的减少动态效果
392    playing: Signal<Option<bool>>,
393    restarts: Signal<u64>,
394    pub(crate) finished: Signal<bool>,
395}
396
397impl PlaybackHandle {
398    /// 新的句柄:跟着系统,没打开减少动态效果时播
399    pub fn new() -> Self {
400        Self { playing: signal(None), restarts: signal(0), finished: signal(false) }
401    }
402
403    /// 播放(从停下的那一帧接着播;播完的不会重新开始,用 [`PlaybackHandle::restart`])
404    pub fn play(self) {
405        self.playing.set(Some(true));
406    }
407
408    /// 暂停,停在当前这一帧
409    pub fn pause(self) {
410        self.playing.set(Some(false));
411    }
412
413    /// 在播就暂停,停着就播
414    pub fn toggle(self) {
415        let playing = self.is_playing_untracked();
416        self.playing.set(Some(!playing));
417    }
418
419    /// 回到第一帧重新播(播完的也重新开始),播放次数重新算
420    pub fn restart(self) {
421        self.restarts.update(|n| *n += 1);
422    }
423
424    /// 是否要播(响应式):调用过 `play` / `pause` 时按调用的,否则看系统有没有打开减少动态效果。
425    /// 元素在屏幕外、窗口被挡住时也是 `true`,只是暂时不换帧
426    pub fn is_playing(self) -> bool {
427        self.playing.get().unwrap_or_else(|| !crate::system::is_motion_reduced())
428    }
429
430    fn is_playing_untracked(self) -> bool {
431        untracked(|| self.is_playing())
432    }
433
434    /// 按文件里的循环次数播完了(响应式),停在最后一帧;一直循环的动图永远是 `false`
435    pub fn is_finished(self) -> bool {
436        self.finished.get()
437    }
438}
439
440impl Default for PlaybackHandle {
441    fn default() -> Self {
442        Self::new()
443    }
444}
445
446/// 图片元素上不是属性的设置:淡入(过渡)、加载状态(写回信号)、播放句柄。挂载时和来源一起绑定
447#[derive(Default)]
448pub(crate) struct ImageExtras {
449    fade_in: bool,
450    state: Option<Signal<ImageState>>,
451    player: Option<PlaybackHandle>,
452}
453
454impl Element {
455    /// 图片的淡入、加载状态、播放句柄;设在还没有种类的元素上时,它成为图片元素
456    fn image_extras(&mut self) -> &mut ImageExtras {
457        if self.kind.is_none() {
458            self.kind = Some(Box::new(ImageBlock::default()));
459        }
460        self.image.get_or_insert_with(Box::default)
461    }
462
463    /// 图片在内容区里的对齐:0 靠左 / 上,0.5 居中(默认),1 靠右 / 下,同 `.image_position_x(x).image_position_y(y)`。
464    /// 对 `Contain`、`Cover`、`None`、`ScaleDown` 有效
465    pub fn image_position(self, x: impl IntoProp<f32>, y: impl IntoProp<f32>) -> Self {
466        self.image_position_x(x).image_position_y(y)
467    }
468
469    /// 解码好之后按曲线淡入;挂载时已经在缓存里的图片直接显示。
470    /// 用的是元素的透明度(合成层动画,由渲染线程推进),和 [`Element::opacity`] 相乘
471    pub fn image_fade(mut self, curve: impl Into<Curve>) -> Self {
472        self.image_extras().fade_in = true;
473        self.transition(Property::Opacity, curve)
474    }
475
476    /// 把加载状态(加载中 / 原始大小 / 出错)写进信号,换图时跟着变
477    pub fn report_load_state(mut self, state: Signal<ImageState>) -> Self {
478        self.image_extras().state = Some(state);
479        self
480    }
481
482    /// 用句柄控制动图:暂停、播放、重新播,读它播完了没有(见 [`PlaybackHandle`])。
483    /// 同时设了 [`Element::playing`] 时,播不播按 `playing`
484    pub fn playback_handle(mut self, player: PlaybackHandle) -> Self {
485        self.image_extras().player = Some(player);
486        self
487    }
488}
489
490/// 注册表里 `source` 的绑定:没有淡入、加载状态、播放句柄时
491pub(crate) fn bind_source(tree: &TreeRef, id: NodeId, source: crate::property::registry::Slot) {
492    bind(tree, id, Some(source), None, false);
493}
494
495/// 挂载时绑定图片的来源,连同淡入、加载状态、播放句柄(`playing` 设了时播不播按它,由属性表绑定)。
496/// 淡入时返回"有图片在显示了"的信号,透明度乘上它
497pub(crate) fn bind(tree: &TreeRef, id: NodeId, source: Option<crate::property::registry::Slot>, extras: Option<Box<ImageExtras>>, has_playing: bool) -> Option<Signal<bool>> {
498    let ImageExtras { fade_in, state, player } = extras.map(|e| *e).unwrap_or_default();
499    if let Some(player) = player {
500        // 动图的播放:没设 `playing` 时跟着句柄(句柄的 `None` 是跟着系统)
501        if !has_playing {
502            crate::tree::bind(tree, Some(Prop::Dynamic(Box::new(move || player.playing.get()))), move |tree, intent| tree.set_playing(id, intent));
503        }
504        tree.borrow_mut().update_image(id, |block| block.handle = Some(player));
505        // 重新播:第一次执行(挂载时)不算
506        let weak: Weak<std::cell::RefCell<Tree>> = Rc::downgrade(tree);
507        let mut first = true;
508        Effect::new(move || {
509            player.restarts.get();
510            if std::mem::take(&mut first) {
511                return;
512            }
513            player.finished.set(false);
514            if let Some(tree) = weak.upgrade() {
515                tree.borrow_mut().restart_image(id);
516            }
517        });
518    }
519
520    // 有图片在显示:淡入用
521    let loaded = fade_in.then(|| signal(false));
522    if let Some(source) = source {
523        // 解码好时加一,让下面的绑定重新执行
524        let tick = signal(0u64);
525        let weak: Weak<std::cell::RefCell<Tree>> = Rc::downgrade(tree);
526        Effect::new(move || {
527            tick.get();
528            let Some(mut source) = source.get::<ImageSource>() else { return };
529            // 打开了图片监视时,文件改了修订号就变,换一个缓存条目重新解码
530            if let SourceKind::File(path) = &source.kind {
531                source.revision = image_revision(path);
532            }
533            // 被覆盖层盖着:记下新的来源,不换图
534            let source = match weak.upgrade() {
535                Some(tree) => match tree.borrow_mut().hold_back(id, PropId::SOURCE, source) {
536                    Some(source) => source,
537                    None => return,
538                },
539                None => source,
540            };
541            let image = untracked(|| loader::acquire(&source));
542            image.listen(tick);
543            let status = image.state();
544            let shown = weak.upgrade().is_some_and(|tree| tree.borrow_mut().set_image(id, image));
545            if let Some(state) = state {
546                state.set_if_changed(status);
547            }
548            if let Some(loaded) = loaded {
549                loaded.set_if_changed(shown);
550            }
551        });
552    }
553    loaded
554}
555
556/// 图片元素的内容
557pub(crate) struct ImageBlock {
558    /// 绑定的图片(可能还在解码)
559    requested: Option<ImageRef>,
560    /// 正在显示的图片:换图时新图解码好之前继续显示旧的
561    shown: Option<ImageRef>,
562    pub fit: ImageFit,
563    pub position: [f32; 2],
564    /// 改色([`Element::tint`]):透明表示不改
565    pub tint: Color,
566    /// 显示的是动图时,这个元素自己的播放状态
567    pub player: Option<Player>,
568    /// 想不想播:绑定的 [`Element::playing`] 或者句柄上调用过的 `play` / `pause`;
569    /// `None` 跟着系统(没打开减少动态效果时播,打开时回到第一帧)
570    pub intent: Option<bool>,
571    /// 播放控制的句柄:播完时写它的信号
572    pub handle: Option<PlaybackHandle>,
573}
574
575impl Default for ImageBlock {
576    fn default() -> Self {
577        Self {
578            requested: None,
579            shown: None,
580            fit: ImageFit::Stretch,
581            position: [0.5, 0.5],
582            tint: Color::TRANSPARENT,
583            player: None,
584            intent: None,
585            handle: None,
586        }
587    }
588}
589
590impl ImageBlock {
591    pub fn showing(&self) -> bool {
592        self.shown.is_some()
593    }
594
595    /// 来源的说明(测试读的元素树快照用)
596    pub fn source_label(&self) -> Option<String> {
597        self.requested.as_ref().map(|image| format!("{:?}", image.source()))
598    }
599
600    /// 没指定大小时的大小:图片的原始大小,没在显示时为 0
601    pub fn intrinsic(&self) -> [f32; 2] {
602        match self.shown.as_ref().map(ImageRef::status) {
603            Some(Status::Ready { natural, .. }) => [natural[0] as f32, natural[1] as f32],
604            #[cfg(feature = "svg")]
605            Some(Status::Vector { document }) => document.size,
606            _ => [0.0; 2],
607        }
608    }
609
610    /// 正在显示的是 SVG 文件:解析好的文档
611    #[cfg(feature = "svg")]
612    pub fn document(&self) -> Option<Arc<svg::SvgDocument>> {
613        match self.shown.as_ref().map(ImageRef::status) {
614            Some(Status::Vector { document }) => Some(document),
615            _ => None,
616        }
617    }
618
619    /// 把 SVG 文档放进显示列表([`ImageBlock::document`] 有的时候代替 [`ImageSystem::push`])
620    #[cfg(feature = "svg")]
621    pub fn paint_document(&self, document: &svg::SvgDocument, area: &ImageArea, target: SvgTarget) {
622        svg_paint::paint(document, self, area, target);
623    }
624}
625
626/// 动图在一个元素上的播放状态。帧的像素在缓存里(同一个来源的元素共用),
627/// 每个元素在 GPU 上有自己的一块位置,换帧时只把新的一帧传到这块位置上:不重新布局、不重建显示列表
628pub(crate) struct Player {
629    /// 这个元素在 GPU 资源里的位置([`ImageSystem`] 里的键)
630    key: Key,
631    frames: Arc<Frames>,
632    /// 正在显示第几帧
633    pub frame: usize,
634    /// 下一帧的时间(树的时钟,秒);`None` 表示下次推进时从那一刻开始计时
635    pub due: Option<f64>,
636    /// 播完了几遍
637    played: u32,
638    pub finished: bool,
639}
640
641/// 推进一个动图的结果
642pub(crate) struct Stepped {
643    /// 换了帧
644    pub changed: bool,
645    /// 这一次推进播完了(按文件里的循环次数)
646    pub finished: bool,
647}
648
649impl Player {
650    pub fn frames(&self) -> usize {
651        self.frames.frames.len()
652    }
653
654    /// 当前这一帧还要显示多久
655    pub fn delay(&self) -> f64 {
656        self.frames.delays[self.frame] as f64
657    }
658
659    /// 推进到 `now`:到点了就换下一帧,一次可能跳过几帧(卡顿之后),播到循环次数时停在最后一帧。
660    /// 落后超过 1 秒时从现在重新计时,不一帧一帧地追
661    pub fn step(&mut self, now: f64) -> Stepped {
662        let mut out = Stepped { changed: false, finished: false };
663        let Some(mut due) = self.due else {
664            self.due = Some(now + self.delay());
665            return out;
666        };
667        let count = self.frames();
668        while now >= due && !self.finished {
669            if self.frame + 1 < count {
670                self.frame += 1;
671            } else {
672                self.played += 1;
673                if self.frames.loops.is_some_and(|n| self.played >= n) {
674                    self.finished = true;
675                    out.finished = true;
676                    break;
677                }
678                self.frame = 0;
679            }
680            out.changed = true;
681            due += self.delay();
682            if now - due > 1.0 {
683                due = now + self.delay();
684            }
685        }
686        self.due = Some(due);
687        out
688    }
689
690    /// 回到第一帧,重新开始计时(重新播、减少动态效果时停在第一帧)。返回是否换了帧
691    pub fn rewind(&mut self) -> bool {
692        let changed = self.frame != 0;
693        self.frame = 0;
694        self.played = 0;
695        self.finished = false;
696        self.due = None;
697        changed
698    }
699
700    /// 当前这一帧的像素
701    pub fn current(&self) -> Arc<ImageData> {
702        self.frames.frames[self.frame].clone()
703    }
704}
705
706/// 图片在这棵树的 GPU 资源里放在哪
707#[derive(Clone, Copy, Debug)]
708enum Slot {
709    /// 图片图集里的位置(像素)
710    Atlas([u32; 2]),
711    /// 单独的纹理
712    Texture(u32),
713}
714
715/// 树里一块 GPU 位置的用途:一张图片(同一个来源的元素共用),一个元素上播放的动图(每个元素一块),
716/// 或者 SVG 文件里的一张位图(显示这个文件的元素共用)
717#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
718pub(crate) enum Key {
719    Image(u64),
720    Player(u64),
721    #[cfg(feature = "svg")]
722    Embedded(u64),
723}
724
725/// 这棵树用到的一张图片
726struct TreeImage {
727    image: ImageRef,
728    /// 有几处(元素的"绑定的"和"显示的"各算一处)在用;动图的播放位置总是 1
729    users: u32,
730    slot: Option<Slot>,
731    /// 动图的播放位置:现在放着哪一帧
732    frame: Option<Arc<ImageData>>,
733}
734
735impl TreeImage {
736    /// 要放进这块位置的像素;还没解码好、或者是动图本身(由各元素的播放位置显示,不占位置)时为 `None`
737    fn data(&self) -> Option<Arc<ImageData>> {
738        match (&self.frame, self.image.status()) {
739            (Some(frame), _) => Some(frame.clone()),
740            (None, Status::Ready { frames: Some(_), .. }) => None,
741            (None, Status::Ready { data, .. }) => Some(data),
742            _ => None,
743        }
744    }
745}
746
747/// 每棵元素树的图片:引用计数、图片图集的装箱、给渲染线程的更新
748#[derive(Default)]
749pub(crate) struct ImageSystem {
750    images: HashMap<Key, TreeImage>,
751    /// 图片图集边长,0 表示还没建
752    atlas_size: u32,
753    shelves: Shelves,
754    /// 动图卸载后空出来的图集位置(按存储大小),同样大小的动图再挂载时直接用,虚拟列表来回滚动不用重新装箱
755    spare: Vec<([u32; 2], [u32; 2])>,
756    next_texture: u32,
757    next_player: u64,
758    updates: Vec<AtlasUpdate>,
759    /// 有解码好、还没分配 GPU 位置的图片
760    dirty: bool,
761}
762
763/// 图片图集的起始边长;放不下时先重新装箱,还放不下再翻倍,最大 [`max_atlas_size`]
764const ATLAS_START: u32 = 1024;
765
766impl ImageSystem {
767    /// 元素绑定的图片变了或者解码好了:更新元素要显示的图片,返回画面是否要变
768    pub fn update(&mut self, block: &mut ImageBlock, image: ImageRef) -> bool {
769        if !block.requested.as_ref().is_some_and(|r| r.same(&image)) {
770            self.retain(&image);
771            if let Some(old) = block.requested.replace(image.clone()) {
772                self.release(&old);
773            }
774        }
775        match image.status() {
776            Status::Ready { frames, .. } => {
777                if block.shown.as_ref().is_some_and(|s| s.same(&image)) {
778                    return false;
779                }
780                self.retain(&image);
781                if let Some(old) = block.shown.replace(image.clone()) {
782                    self.release_shown(&old);
783                }
784                // 动图:这个元素自己的播放状态和 GPU 位置,从第一帧开始
785                self.stop(block);
786                if let Some(frames) = frames {
787                    self.next_player += 1;
788                    let key = Key::Player(self.next_player);
789                    let first = frames.frames[0].clone();
790                    self.images.insert(key, TreeImage { image, users: 1, slot: None, frame: Some(first) });
791                    block.player = Some(Player { key, frames, frame: 0, due: None, played: 0, finished: false });
792                }
793                self.dirty = true;
794                true
795            }
796            #[cfg(feature = "svg")]
797            Status::Vector { document } => {
798                if block.shown.as_ref().is_some_and(|s| s.same(&image)) {
799                    return false;
800                }
801                self.retain(&image);
802                if let Some(old) = block.shown.replace(image.clone()) {
803                    self.release_shown(&old);
804                }
805                self.stop(block);
806                self.show_embedded(&document, &image);
807                true
808            }
809            Status::Loading => false,
810            Status::Error(_) => match block.shown.take() {
811                Some(old) => {
812                    self.release_shown(&old);
813                    self.stop(block);
814                    true
815                }
816                None => false,
817            },
818        }
819    }
820
821    /// 元素卸载:放掉它用的图片
822    pub fn detach(&mut self, block: &mut ImageBlock) {
823        self.stop(block);
824        if let Some(image) = block.requested.take() {
825            self.release(&image);
826        }
827        if let Some(image) = block.shown.take() {
828            self.release_shown(&image);
829        }
830    }
831
832    /// 元素不再显示这张图片(SVG 文件里的位图也放掉)
833    fn release_shown(&mut self, image: &ImageRef) {
834        #[cfg(feature = "svg")]
835        if let Status::Vector { document } = image.status() {
836            self.hide_embedded(&document);
837        }
838        self.release(image);
839    }
840
841    /// 元素开始显示这个 SVG 文件:里面的位图占 GPU 位置(这棵树里显示同一个文件的元素共用)
842    #[cfg(feature = "svg")]
843    fn show_embedded(&mut self, document: &svg::SvgDocument, owner: &ImageRef) {
844        for embedded in &document.images {
845            let entry = TreeImage { image: owner.clone(), users: 0, slot: None, frame: Some(embedded.data.clone()) };
846            self.images.entry(Key::Embedded(embedded.id)).or_insert(entry).users += 1;
847            self.dirty = true;
848        }
849    }
850
851    /// 元素不再显示这个 SVG 文件:没人用的位图放掉,单独的纹理释放(图集里的位置在下次重新装箱时收回)
852    #[cfg(feature = "svg")]
853    fn hide_embedded(&mut self, document: &svg::SvgDocument) {
854        for embedded in &document.images {
855            let key = Key::Embedded(embedded.id);
856            let Some(entry) = self.images.get_mut(&key) else { continue };
857            entry.users -= 1;
858            if entry.users == 0
859                && let Some(entry) = self.images.remove(&key)
860                && let Some(Slot::Texture(id)) = entry.slot
861            {
862                self.updates.push(AtlasUpdate::Image(ImageUpdate::Release { id }));
863            }
864        }
865    }
866
867    /// SVG 文件里的一张位图放在哪;还没分配时是 `None`
868    #[cfg(feature = "svg")]
869    fn embedded_slot(&self, id: u64) -> Option<Slot> {
870        self.images.get(&Key::Embedded(id))?.slot
871    }
872
873    /// 元素不再播放这个动图:放掉它的 GPU 位置(图集里的位置留给同样大小的动图)
874    fn stop(&mut self, block: &mut ImageBlock) {
875        let Some(player) = block.player.take() else { return };
876        let Some(entry) = self.images.remove(&player.key) else { return };
877        match entry.slot {
878            Some(Slot::Texture(id)) => self.updates.push(AtlasUpdate::Image(ImageUpdate::Release { id })),
879            Some(Slot::Atlas(at)) => {
880                if let Some(frame) = entry.frame {
881                    self.spare.push((frame.storage(), at));
882                }
883            }
884            None => {}
885        }
886    }
887
888    /// 动图换了一帧:只把新的一帧传到这个元素的位置上(显示列表不变)
889    pub fn show_frame(&mut self, player: &Player) {
890        let Some(entry) = self.images.get_mut(&player.key) else { return };
891        let data = player.current();
892        entry.frame = Some(data.clone());
893        match entry.slot {
894            Some(Slot::Atlas([x, y])) => self.updates.push(AtlasUpdate::Image(ImageUpdate::Atlas { x, y, image: data })),
895            Some(Slot::Texture(id)) => self.updates.push(AtlasUpdate::Image(ImageUpdate::Write { id, image: data })),
896            // 还没分配位置:分配时传的就是当前这一帧
897            None => {}
898        }
899    }
900
901    fn retain(&mut self, image: &ImageRef) {
902        let entry = TreeImage { image: image.clone(), users: 0, slot: None, frame: None };
903        self.images.entry(Key::Image(image.id())).or_insert(entry).users += 1;
904    }
905
906    /// 这棵树里没人用了:释放单独的纹理(图集里的位置在下次重新装箱时收回)
907    fn release(&mut self, image: &ImageRef) {
908        let key = Key::Image(image.id());
909        let Some(entry) = self.images.get_mut(&key) else { return };
910        entry.users -= 1;
911        if entry.users == 0 {
912            let entry = self.images.remove(&key).expect("刚查到");
913            if let Some(Slot::Texture(id)) = entry.slot {
914                self.updates.push(AtlasUpdate::Image(ImageUpdate::Release { id }));
915            }
916        }
917    }
918
919    /// 绘制前:给解码好的图片分配 GPU 位置(图集或单独的纹理),记下要上传的内容。
920    /// 图集放不下时重新装箱(可能翻倍),所有图片的位置都可能变,所以必须在生成图元之前做
921    pub fn prepare(&mut self) {
922        if !std::mem::take(&mut self.dirty) {
923            return;
924        }
925        let mut pending: Vec<Key> = self.images.iter().filter(|(_, e)| e.slot.is_none() && e.data().is_some()).map(|(&k, _)| k).collect();
926        pending.sort_unstable();
927        let mut repack = Vec::new();
928        for key in pending {
929            let data = self.images[&key].data().expect("刚检查过");
930            if !fits_atlas(&data) {
931                self.create_texture(key, data);
932                continue;
933            }
934            let [w, h] = data.storage();
935            // 动图先用空出来的同样大小的位置
936            let spare = matches!(key, Key::Player(_)).then(|| self.spare.iter().position(|(size, _)| *size == [w, h])).flatten();
937            let at = match spare {
938                Some(i) => Some(self.spare.swap_remove(i).1),
939                None => self.shelves.allocate(w, h),
940            };
941            match at {
942                Some(at) if self.atlas_size > 0 => {
943                    self.updates.push(AtlasUpdate::Image(ImageUpdate::Atlas { x: at[0], y: at[1], image: data }));
944                    self.images.get_mut(&key).expect("刚查到").slot = Some(Slot::Atlas(at));
945                }
946                _ => repack.push(key),
947            }
948        }
949        if !repack.is_empty() {
950            self.repack(repack);
951        }
952    }
953
954    fn create_texture(&mut self, key: Key, data: Arc<ImageData>) {
955        self.next_texture += 1;
956        let texture = self.next_texture;
957        self.updates.push(AtlasUpdate::Image(ImageUpdate::Create { id: texture, image: data }));
958        self.images.get_mut(&key).expect("刚查到").slot = Some(Slot::Texture(texture));
959    }
960
961    /// 图集放不下:把图集里还在用的图片和新来的一起重新装箱(先试当前大小,不行再翻倍),
962    /// 最大的图集也放不下的改用单独的纹理
963    fn repack(&mut self, new: Vec<Key>) {
964        let mut keys: Vec<Key> = self.images.iter().filter(|(_, e)| matches!(e.slot, Some(Slot::Atlas(_)))).map(|(&k, _)| k).collect();
965        keys.extend(new);
966        let data: HashMap<Key, Arc<ImageData>> = keys.iter().map(|&k| (k, self.images[&k].data().expect("图集里的都解码好了"))).collect();
967        // 高的先放,货架装得更满
968        keys.sort_by_key(|k| (std::cmp::Reverse(data[k].storage()[1]), *k));
969        let mut size = self.atlas_size.max(ATLAS_START);
970        let placed = loop {
971            let mut shelves = Shelves::new(size);
972            let placed: Vec<Option<[u32; 2]>> = keys.iter().map(|k| shelves.allocate(data[k].storage()[0], data[k].storage()[1])).collect();
973            if placed.iter().all(Option::is_some) || size >= max_atlas_size() {
974                self.shelves = shelves;
975                break placed;
976            }
977            size = (size * 2).min(max_atlas_size());
978        };
979        self.atlas_size = size;
980        // 空出来的位置都作废了
981        self.spare.clear();
982        self.updates.push(AtlasUpdate::Image(ImageUpdate::ResetAtlas { size }));
983        for (key, at) in keys.into_iter().zip(placed) {
984            let image = data[&key].clone();
985            match at {
986                Some(at) => {
987                    self.updates.push(AtlasUpdate::Image(ImageUpdate::Atlas { x: at[0], y: at[1], image }));
988                    self.images.get_mut(&key).expect("刚查到").slot = Some(Slot::Atlas(at));
989                }
990                None => self.create_texture(key, image),
991            }
992        }
993    }
994
995    /// 自上次以来的 GPU 更新,交给渲染线程
996    pub fn take_updates(&mut self) -> Vec<AtlasUpdate> {
997        std::mem::take(&mut self.updates)
998    }
999
1000    /// 完整内容,用于给新的 GPU 侧(离屏渲染)建立图集和纹理;动图是各元素此刻显示的那一帧
1001    pub fn snapshot(&self) -> Vec<AtlasUpdate> {
1002        let mut out = Vec::new();
1003        if self.atlas_size > 0 {
1004            out.push(AtlasUpdate::Image(ImageUpdate::ResetAtlas { size: self.atlas_size }));
1005        }
1006        for entry in self.images.values() {
1007            let (Some(slot), Some(data)) = (entry.slot, entry.data()) else { continue };
1008            out.push(AtlasUpdate::Image(match slot {
1009                Slot::Atlas([x, y]) => ImageUpdate::Atlas { x, y, image: data },
1010                Slot::Texture(id) => ImageUpdate::Create { id, image: data },
1011            }));
1012        }
1013        out
1014    }
1015
1016    /// 生成元素的图片图元:内容区按 fit 和对齐算出图片的位置,四边形就是内容区(圆角裁剪按它算),
1017    /// 图片之外的部分在着色器里不画。有边框时在图片上面再画一次边框
1018    pub fn push(&self, block: &ImageBlock, area: &ImageArea, list: &mut DisplayList) {
1019        let Some(shown) = &block.shown else { return };
1020        let key = block.player.as_ref().map_or(Key::Image(shown.id()), |p| p.key);
1021        let Some(entry) = self.images.get(&key) else { return };
1022        let (Some(slot), Status::Ready { natural, data, .. }) = (entry.slot, shown.status()) else { return };
1023        let content = area.content;
1024        if content.width <= 0.0 || content.height <= 0.0 || natural[0] == 0 || natural[1] == 0 {
1025            return;
1026        }
1027        let [dx, dy, dw, dh] = fit_rect(block.fit, block.position, [natural[0] as f32, natural[1] as f32], [content.width, content.height]);
1028        let (bounds, kind) = self.texture_range(slot, &data);
1029        // 内容区四角对应的纹理坐标(可以超出图片的范围)
1030        let u = |x: f32| bounds[0] + (x - dx) / dw * (bounds[2] - bounds[0]);
1031        let v = |y: f32| bounds[1] + (y - dy) / dh * (bounds[3] - bounds[1]);
1032
1033        let [cx, cy] = area.local.apply(content.center());
1034        let mut quad = Quad::new(cx - content.width * 0.5, cy - content.height * 0.5, content.width, content.height);
1035        quad.transform = area.local.linear;
1036        quad.radii = [area.inner_radius; 4];
1037        quad.uv = [u(0.0), v(0.0), u(content.width), v(content.height)];
1038        quad.shadow_offset = [bounds[0], bounds[1]];
1039        quad.shadow_blur = bounds[2];
1040        quad.border_width = bounds[3];
1041        quad.kind = kind;
1042        quad.opacity = area.opacity;
1043        if !block.tint.is_transparent() {
1044            quad.gradient = list.push_filter(&ColorMatrix::tint(block.tint));
1045        }
1046        if let Slot::Texture(texture) = slot {
1047            list.quad_effects.push(scene::QuadEffect::Image { quad: list.quads.len() as u32, texture });
1048        }
1049        // 广色域、HDR 的图:窗口要换成扩展范围的表面才显示得出来
1050        list.extended |= data.encoding != ImageEncoding::Srgb8;
1051        list.quads.push(quad);
1052        area.push_border(list);
1053    }
1054
1055    /// 图片在纹理里的范围和图元的种类(动图的每一帧大小都一样)
1056    fn texture_range(&self, slot: Slot, data: &ImageData) -> ([f32; 4], u32) {
1057        let [sw, sh] = data.storage();
1058        match slot {
1059            Slot::Atlas([x, y]) => {
1060                let s = self.atlas_size as f32;
1061                ([x as f32 / s, y as f32 / s, (x + data.size[0]) as f32 / s, (y + data.size[1]) as f32 / s], Quad::IMAGE)
1062            }
1063            Slot::Texture(_) => ([0.0, 0.0, data.size[0] as f32 / sw as f32, data.size[1] as f32 / sh as f32], Quad::IMAGE_TEXTURE),
1064        }
1065    }
1066}
1067
1068/// 生成图片图元需要的元素信息
1069pub(crate) struct ImageArea {
1070    /// 元素的范围和内容区(去掉内边距),布局坐标
1071    pub bounds: Rect,
1072    pub content: Rect,
1073    /// 到当前合成层的累积变换
1074    pub local: Affine,
1075    pub opacity: f32,
1076    pub radius: f32,
1077    /// 内容区的圆角:元素的圆角减去内边距
1078    pub inner_radius: f32,
1079    /// 边框宽度和颜色(纯色或渐变),画在图片上面
1080    pub border: Option<(f32, Fill)>,
1081}
1082
1083/// 外部纹理(编号 `texture`,见 [`scene::EXTERNAL_TEXTURE_BASE`])铺满内容区:和单独纹理的大图一样的图元,
1084/// 纹理的整张对应内容区。纹理还没登记时渲染器跳过这个图元
1085pub(crate) fn push_external(texture: u32, area: &ImageArea, list: &mut DisplayList) {
1086    let content = area.content;
1087    if content.width <= 0.0 || content.height <= 0.0 {
1088        return;
1089    }
1090    let [cx, cy] = area.local.apply(content.center());
1091    let mut quad = Quad::new(cx - content.width * 0.5, cy - content.height * 0.5, content.width, content.height);
1092    quad.transform = area.local.linear;
1093    quad.radii = [area.inner_radius; 4];
1094    quad.uv = [0.0, 0.0, 1.0, 1.0];
1095    // 图片在纹理里的范围(见 `texture_range`):整张
1096    quad.shadow_offset = [0.0, 0.0];
1097    quad.shadow_blur = 1.0;
1098    quad.border_width = 1.0;
1099    quad.kind = Quad::IMAGE_TEXTURE;
1100    quad.opacity = area.opacity;
1101    list.quad_effects.push(scene::QuadEffect::Image { quad: list.quads.len() as u32, texture });
1102    list.quads.push(quad);
1103    area.push_border(list);
1104}
1105
1106impl ImageArea {
1107    /// 边框画在图片上面(有边框时)
1108    fn push_border(&self, list: &mut DisplayList) {
1109        let Some((width, color)) = &self.border else { return };
1110        let b = self.bounds;
1111        let [cx, cy] = self.local.apply(b.center());
1112        let mut border = Quad::new(cx - b.width * 0.5, cy - b.height * 0.5, b.width, b.height)
1113            .radius(self.radius)
1114            .fill(Color::TRANSPARENT)
1115            .border(*width, color.color())
1116            .opacity(self.opacity);
1117        border.transform = self.local.linear;
1118        if let Fill::Gradient(gradient) = color {
1119            border = border.with_border_gradient(gradient.push_local(list, [b.width, b.height]));
1120        }
1121        list.quads.push(border);
1122    }
1123}
1124
1125/// 图集版的图片:8 位的、只有图集那几级 mip、补齐过,且放得进图集
1126fn fits_atlas(data: &ImageData) -> bool {
1127    let [w, h] = data.storage();
1128    data.encoding == ImageEncoding::Srgb8 && data.levels.len() == IMAGE_ATLAS_LEVELS as usize && w.max(h) <= max_atlas_size() / 2
1129}
1130
1131/// 按 fit 和对齐,图片在内容区里的位置和大小 `[x, y, w, h]`(相对内容区左上角)
1132pub(crate) fn fit_rect(fit: ImageFit, position: [f32; 2], natural: [f32; 2], area: [f32; 2]) -> [f32; 4] {
1133    let [iw, ih] = natural;
1134    let [w, h] = area;
1135    let contain = (w / iw).min(h / ih);
1136    let scale = match fit {
1137        ImageFit::Stretch => return [0.0, 0.0, w, h],
1138        ImageFit::Contain => contain,
1139        ImageFit::Cover => (w / iw).max(h / ih),
1140        ImageFit::None => 1.0,
1141        ImageFit::ScaleDown => contain.min(1.0),
1142    };
1143    let (dw, dh) = (iw * scale, ih * scale);
1144    [(w - dw) * position[0], (h - dh) * position[1], dw, dh]
1145}
1146
1147/// 图片图集的货架装箱。所有尺寸都是对齐单位的倍数,位置自然对齐
1148#[derive(Default)]
1149struct Shelves {
1150    size: u32,
1151    /// 每层货架:y、高、下一个 x
1152    shelves: Vec<[u32; 3]>,
1153    next_y: u32,
1154}
1155
1156impl Shelves {
1157    fn new(size: u32) -> Self {
1158        Self { size, shelves: Vec::new(), next_y: 0 }
1159    }
1160
1161    fn allocate(&mut self, width: u32, height: u32) -> Option<[u32; 2]> {
1162        if width > self.size || height > self.size {
1163            return None;
1164        }
1165        // 高度合适(不浪费超过一半)且还放得下的货架
1166        let size = self.size;
1167        if let Some(shelf) = self.shelves.iter_mut().find(|[_, h, x]| *h >= height && *h <= height + height / 2 && x + width <= size) {
1168            let x = shelf[2];
1169            shelf[2] += width;
1170            return Some([x, shelf[0]]);
1171        }
1172        if self.next_y + height > self.size {
1173            return None;
1174        }
1175        let y = self.next_y;
1176        self.next_y += height;
1177        self.shelves.push([y, height, width]);
1178        Some([0, y])
1179    }
1180}