tawasuyu

tawasuyu/llimphi

Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.

Rust 660Markdown 302TOML 157RON 312382 Sutichaykuna

⎇ c5a232cf24788ab75a850ffe81eca5a7af50e2f8 llimphi-compositor/examples/image_fit_demo.rs Rust · 288 siq'ikuna · 10.8 KB Ñawpa willay Pi imata llamkarqan ch'uya

refresh: stack al día (vello 0.7 / wgpu 27 / parley 0.6) + motor 3D voxel ccab39f14 · Sergio ·

1//! Filmstrip headless de **`ImageFit`** (Bloque 12 de PARIDAD-FLUTTER):
2//! una misma imagen 4:3 sintética se compone en cinco rects 1:1 con
3//! `ImageFit::{Contain, Cover, Fill, None}` y, al final, un círculo
4//! redondeado al máximo con `ImageFit::Cover` para verificar que el
5//! clip respeta `radius` / `corner_radii` (caso avatar).
6//!
7//! Prueba el camino `View::image` + `View::image_fit` → `paint` (pasada
8//! de `node.image_fit` y `node_rrect` para el clip). Render headless:
9//! vello pinta a una textura y volcamos a PNG.
10//!
11//! `cargo run -p llimphi-compositor --example image_fit_demo -- [out.png]`
12
13use std::fs::File;
14use std::io::BufWriter;
15use std::sync::Arc;
16
17use llimphi_compositor::{measure_text_node, mount, paint, ImageFit, View};
18use llimphi_hal::{wgpu, Hal};
19use llimphi_layout::taffy;
20use llimphi_layout::taffy::prelude::{length, percent, FlexDirection, Size, Style};
21use llimphi_layout::taffy::{AlignItems, JustifyContent, Rect};
22use llimphi_layout::LayoutTree;
23use llimphi_raster::peniko::{
24    Blob, Color, ImageAlphaType, ImageBrush as Image, ImageData, ImageFormat,
25};
26use llimphi_raster::{vello, Renderer};
27use llimphi_text::{Alignment, Typesetter};
28
29const W: u32 = 1500;
30const H: u32 = 380;
31const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
32
33/// Imagen sintética 4:3 (`240×180`): cuadrícula de 4×3 con colores
34/// distintos por celda + cruz central blanca. Permite "ver" la
35/// diferencia entre los fits sin embeber un archivo (`Contain` deja
36/// banda, `Cover` recorta, `Fill` deforma la cruz, `None` clippea las
37/// celdas externas).
38fn make_image() -> Image {
39    const IW: u32 = 240;
40    const IH: u32 = 180;
41    const COLS: u32 = 4;
42    const ROWS: u32 = 3;
43    let palette: [[u8; 3]; 12] = [
44        [231, 76, 60],   [241, 196, 15], [46, 204, 113], [52, 152, 219],
45        [155, 89, 182],  [26, 188, 156], [230, 126, 34], [149, 165, 166],
46        [192, 57, 43],   [243, 156, 18], [22, 160, 133], [41, 128, 185],
47    ];
48    let mut px: Vec<u8> = Vec::with_capacity((IW * IH * 4) as usize);
49    let cw = IW / COLS;
50    let ch = IH / ROWS;
51    for y in 0..IH {
52        for x in 0..IW {
53            let col = (x / cw).min(COLS - 1);
54            let row = (y / ch).min(ROWS - 1);
55            let idx = (row * COLS + col) as usize;
56            // Cruz central blanca, ~8 px de grosor — la deformación de
57            // `Fill` se hace evidente cuando los brazos cambian de razón.
58            let mid_x = (x as i32 - IW as i32 / 2).abs() <= 4;
59            let mid_y = (y as i32 - IH as i32 / 2).abs() <= 4;
60            let [r, g, b] = if mid_x || mid_y {
61                [255, 255, 255]
62            } else {
63                palette[idx]
64            };
65            px.extend_from_slice(&[r, g, b, 255]);
66        }
67    }
68    Image::new(ImageData {
69        data: Blob::new(Arc::new(px)),
70        format: ImageFormat::Rgba8,
71        alpha_type: ImageAlphaType::Alpha,
72        width: IW,
73        height: IH,
74    })
75}
76
77/// Una "ficha" con la imagen arriba (cuadrada de 200×200) + un rótulo
78/// abajo con el nombre del fit. Cuerpo blanco con borde sutil.
79fn ficha(img: &Image, fit: ImageFit, label: &str, panel: Color, fg: Color) -> View<()> {
80    let visor = View::<()>::new(Style {
81        size: Size { width: length(200.0_f32), height: length(200.0_f32) },
82        ..Default::default()
83    })
84    .fill(Color::from_rgba8(30, 34, 44, 255)) // fondo gris para que `Contain` deje banda visible
85    .radius(8.0)
86    .border(1.0, Color::from_rgba8(60, 66, 80, 255))
87    .image(img.clone())
88    .image_fit(fit);
89
90    View::<()>::new(Style {
91        size: Size { width: length(220.0_f32), height: length(260.0_f32) },
92        flex_direction: FlexDirection::Column,
93        align_items: Some(AlignItems::Center),
94        justify_content: Some(JustifyContent::FlexStart),
95        gap: Size { width: length(0.0_f32), height: length(10.0_f32) },
96        padding: Rect {
97            left: length(10.0_f32),
98            right: length(10.0_f32),
99            top: length(10.0_f32),
100            bottom: length(10.0_f32),
101        },
102        ..Default::default()
103    })
104    .fill(panel)
105    .radius(14.0)
106    .border(1.0, Color::from_rgba8(220, 224, 232, 255))
107    .children(vec![
108        visor,
109        View::<()>::new(Style {
110            size: Size { width: percent(0.95_f32), height: length(20.0_f32) },
111            ..Default::default()
112        })
113        .text_aligned(label.to_string(), 14.0, fg, Alignment::Center),
114    ])
115}
116
117/// Ficha avatar: imagen rectangular 4:3 metida en un cuadrado con
118/// radio máximo (= círculo) y `Cover`. Verifica que el clip respeta el
119/// `node_rrect` (corona el caso que rompía antes del Bloque 12).
120fn avatar(img: &Image, panel: Color, fg: Color) -> View<()> {
121    let crc = View::<()>::new(Style {
122        size: Size { width: length(200.0_f32), height: length(200.0_f32) },
123        ..Default::default()
124    })
125    .fill(Color::from_rgba8(30, 34, 44, 255))
126    .radius(100.0) // círculo completo
127    .border(2.0, Color::from_rgba8(60, 66, 80, 255))
128    .image(img.clone())
129    .image_fit(ImageFit::Cover);
130
131    View::<()>::new(Style {
132        size: Size { width: length(220.0_f32), height: length(260.0_f32) },
133        flex_direction: FlexDirection::Column,
134        align_items: Some(AlignItems::Center),
135        justify_content: Some(JustifyContent::FlexStart),
136        gap: Size { width: length(0.0_f32), height: length(10.0_f32) },
137        padding: Rect {
138            left: length(10.0_f32),
139            right: length(10.0_f32),
140            top: length(10.0_f32),
141            bottom: length(10.0_f32),
142        },
143        ..Default::default()
144    })
145    .fill(panel)
146    .radius(14.0)
147    .border(1.0, Color::from_rgba8(220, 224, 232, 255))
148    .children(vec![
149        crc,
150        View::<()>::new(Style {
151            size: Size { width: percent(0.95_f32), height: length(20.0_f32) },
152            ..Default::default()
153        })
154        .text_aligned("Cover + radio".to_string(), 14.0, fg, Alignment::Center),
155    ])
156}
157
158fn main() {
159    let out = std::env::args().nth(1).unwrap_or_else(|| "image_fit.png".to_string());
160    let theme = llimphi_theme::Theme::light();
161    let panel = theme.bg_panel;
162    let fg = Color::from_rgba8(30, 34, 44, 255);
163
164    let img = make_image();
165
166    let root = View::<()>::new(Style {
167        size: Size { width: percent(1.0_f32), height: percent(1.0_f32) },
168        flex_direction: FlexDirection::Row,
169        align_items: Some(AlignItems::Center),
170        justify_content: Some(JustifyContent::Center),
171        gap: Size { width: length(20.0_f32), height: length(0.0_f32) },
172        padding: Rect {
173            left: length(24.0_f32),
174            right: length(24.0_f32),
175            top: length(24.0_f32),
176            bottom: length(24.0_f32),
177        },
178        ..Default::default()
179    })
180    .fill(theme.bg_app)
181    .children(vec![
182        ficha(&img, ImageFit::Contain, "Contain", panel, fg),
183        ficha(&img, ImageFit::Cover, "Cover", panel, fg),
184        ficha(&img, ImageFit::Fill, "Fill", panel, fg),
185        ficha(&img, ImageFit::None, "None", panel, fg),
186        avatar(&img, panel, fg),
187    ]);
188
189    let mut layout = LayoutTree::new();
190    let mounted = mount(&mut layout, root);
191    let mut ts = Typesetter::new();
192    let computed = {
193        let tmap = &mounted.text_measures;
194        layout
195            .compute_with_measure(mounted.root, (W as f32, H as f32), |nid, known, avail| {
196                match tmap.get(&nid) {
197                    Some(tm) => measure_text_node(&mut ts, tm, known, avail),
198                    None => taffy::Size::ZERO,
199                }
200            })
201            .expect("layout")
202    };
203    let mut scene = vello::Scene::new();
204    paint(&mut scene, &mounted, &computed, &mut ts, None, None);
205
206    let hal = pollster::block_on(Hal::new(None)).expect("hal");
207    let mut renderer = Renderer::new(&hal).expect("renderer");
208    let target = hal.device.create_texture(&wgpu::TextureDescriptor {
209        label: Some("dump-image-fit"),
210        size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
211        mip_level_count: 1,
212        sample_count: 1,
213        dimension: wgpu::TextureDimension::D2,
214        format: FMT,
215        usage: wgpu::TextureUsages::STORAGE_BINDING
216            | wgpu::TextureUsages::RENDER_ATTACHMENT
217            | wgpu::TextureUsages::COPY_SRC,
218        view_formats: &[],
219    });
220    let view = target.create_view(&wgpu::TextureViewDescriptor::default());
221    let [r, g, b, _] = theme.bg_app.components;
222    let bg = Color::from_rgba8((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8, 255);
223    renderer
224        .render_to_view(&hal, &scene, &view, W, H, bg)
225        .expect("render_to_view");
226
227    write_png(&hal, &target, &out);
228    eprintln!(
229        "image_fit_demo: escrito {out} ({W}x{H}) — 5 fichas: Contain (deja \
230         banda en el eje extra) · Cover (recorta el sobrante) · Fill (deforma \
231         la cruz) · None (1:1 centrada, recorta lo que no entra) · Cover sobre \
232         un cuadrado con radius=100 (avatar circular)."
233    );
234}
235
236fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
237    let unpadded = (W * 4) as usize;
238    let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
239    let padded = unpadded.div_ceil(align) * align;
240    let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
241        label: Some("readback"),
242        size: (padded * H as usize) as u64,
243        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
244        mapped_at_creation: false,
245    });
246    let mut enc = hal
247        .device
248        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
249    enc.copy_texture_to_buffer(
250        wgpu::TexelCopyTextureInfo {
251            texture: target,
252            mip_level: 0,
253            origin: wgpu::Origin3d::ZERO,
254            aspect: wgpu::TextureAspect::All,
255        },
256        wgpu::TexelCopyBufferInfo {
257            buffer: &buf,
258            layout: wgpu::TexelCopyBufferLayout {
259                offset: 0,
260                bytes_per_row: Some(padded as u32),
261                rows_per_image: Some(H),
262            },
263        },
264        wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
265    );
266    hal.queue.submit(std::iter::once(enc.finish()));
267    let slice = buf.slice(..);
268    let (tx, rx) = std::sync::mpsc::channel();
269    slice.map_async(wgpu::MapMode::Read, move |r| {
270        let _ = tx.send(r);
271    });
272    hal.device.poll(wgpu::PollType::wait_indefinitely());
273    rx.recv().unwrap().unwrap();
274    let data = slice.get_mapped_range();
275    let mut pixels = Vec::with_capacity((W * H * 4) as usize);
276    for row in 0..H as usize {
277        let s = row * padded;
278        pixels.extend_from_slice(&data[s..s + unpadded]);
279    }
280    drop(data);
281    buf.unmap();
282    let file = File::create(path).expect("png");
283    let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
284    enc.set_color(png::ColorType::Rgba);
285    enc.set_depth(png::BitDepth::Eight);
286    let mut w = enc.write_header().unwrap();
287    w.write_image_data(&pixels).unwrap();
288}