tawasuyu

tawasuyu/llimphi

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

Rust 614Markdown 274TOML 149RON 310606 Definiciones

⎇ main llimphi-compositor/examples/primitivas_demo.rs Rust · 273 líneas · 10.5 KB Historia Quién tocó qué crudo

chore: refresco desde el monorepo — vello 0.9 / wgpu 29, 120 miembros d251eb32b · Sergio ·

1//! Volcado headless de las primitivas nuevas del compositor (Tier 1+2 del
2//! roadmap PARIDAD-FLUTTER): **sombra · gradiente · borde · peso de fuente ·
3//! radio por esquina**. Monta un árbol `View` con tarjetas que ejercitan cada
4//! una (y su combinación), lo pinta a una `vello::Scene` y lee la textura a
5//! PNG. Sirve para VERLAS sin ventana.
6//!
7//! `cargo run -p llimphi-compositor --example primitivas_demo -- [out.png]`
8
9use std::fs::File;
10use std::io::BufWriter;
11
12use llimphi_compositor::{measure_text_node, mount, paint, Shadow, View};
13use llimphi_hal::{wgpu, Hal};
14use llimphi_layout::taffy;
15use llimphi_layout::taffy::prelude::{length, percent, FlexDirection, Size, Style};
16use llimphi_layout::taffy::{AlignItems, JustifyContent, Rect};
17use llimphi_layout::LayoutTree;
18use llimphi_raster::peniko::{Color, Gradient};
19use llimphi_raster::{vello, Renderer};
20use llimphi_text::{Alignment, Typesetter};
21use vello::kurbo::Point;
22
23const W: u32 = 1476;
24const H: u32 = 340;
25const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
26
27/// Una tarjeta con título + descripción, dimensionada igual para todas.
28fn card(build: impl FnOnce(View<()>) -> View<()>, title: &str, fg: Color) -> View<()> {
29    let base = View::<()>::new(Style {
30        size: Size { width: length(180.0_f32), height: length(150.0_f32) },
31        flex_direction: FlexDirection::Column,
32        align_items: Some(AlignItems::CENTER),
33        justify_content: Some(JustifyContent::CENTER),
34        gap: Size { width: length(0.0_f32), height: length(8.0_f32) },
35        ..Default::default()
36    })
37    .radius(16.0);
38    build(base).children(vec![View::<()>::new(Style {
39        size: Size { width: percent(0.9_f32), height: length(22.0_f32) },
40        ..Default::default()
41    })
42    .text_aligned(title.to_string(), 16.0, fg, Alignment::Center)])
43}
44
45fn main() {
46    let out = std::env::args().nth(1).unwrap_or_else(|| "primitivas.png".to_string());
47    let theme = llimphi_theme::Theme::light();
48
49    let panel = theme.bg_panel;
50    let dark = Color::from_rgba8(30, 34, 44, 255);
51    let white = Color::from_rgba8(248, 248, 250, 255);
52
53    // 1) Sombra: fill plano + elevación suave.
54    let sombra = card(
55        |v| v.fill(panel).shadow(Shadow::soft(70, 22.0).offset(0.0, 10.0)),
56        "Sombra",
57        dark,
58    );
59
60    // 2) Gradiente: relleno vertical claro→oscuro (espacio unidad [0,1]²).
61    let grad = Gradient::new_linear(Point::new(0.0, 0.0), Point::new(0.0, 1.0)).with_stops(
62        [Color::from_rgba8(96, 130, 220, 255), Color::from_rgba8(40, 60, 140, 255)].as_slice(),
63    );
64    let gradiente = card(|v| v.fill_gradient(grad.clone()), "Gradiente", white);
65
66    // 3) Borde: hairline sobre fill plano (reemplaza el truco del rect-padre).
67    let borde = card(
68        |v| v.fill(panel).border(1.5, theme.accent),
69        "Borde",
70        dark,
71    );
72
73    // 4) Combo: gradiente + borde + sombra — el look de un botón/card moderno.
74    let combo_grad = Gradient::new_linear(Point::new(0.0, 0.0), Point::new(1.0, 1.0)).with_stops(
75        [Color::from_rgba8(80, 200, 140, 255), Color::from_rgba8(30, 140, 110, 255)].as_slice(),
76    );
77    let combo = card(
78        |v| {
79            v.fill_gradient(combo_grad)
80                .border(1.5, Color::from_rgba8(180, 240, 210, 255))
81                .shadow(Shadow::soft(90, 24.0).offset(0.0, 12.0))
82        },
83        "Combo",
84        white,
85    );
86
87    // 5) Peso de fuente: la misma palabra en 400 (normal) y 700 (bold), para
88    //    contrastar el grosor del trazo en una sola tarjeta.
89    let line = |txt: &str, bold: bool| {
90        let v = View::<()>::new(Style {
91            size: Size { width: percent(0.9_f32), height: length(30.0_f32) },
92            ..Default::default()
93        })
94        .text_aligned(txt.to_string(), 24.0, dark, Alignment::Center);
95        if bold { v.bold() } else { v }
96    };
97    let peso = View::<()>::new(Style {
98        size: Size { width: length(180.0_f32), height: length(150.0_f32) },
99        flex_direction: FlexDirection::Column,
100        align_items: Some(AlignItems::CENTER),
101        justify_content: Some(JustifyContent::CENTER),
102        gap: Size { width: length(0.0_f32), height: length(4.0_f32) },
103        ..Default::default()
104    })
105    .radius(16.0)
106    .fill(panel)
107    .border(1.0, theme.accent)
108    .children(vec![
109        line("Regular 400", false),
110        line("Bold 700", true),
111        View::<()>::new(Style {
112            size: Size { width: percent(0.9_f32), height: length(20.0_f32) },
113            ..Default::default()
114        })
115        .text_aligned("Peso", 14.0, dark, Alignment::Center),
116    ]);
117
118    // 6) Radio por esquina: esquinas asimétricas (arriba muy redondeadas,
119    //    abajo casi rectas) — el look de una pestaña / bocadillo de chat. El
120    //    borde sigue las cuatro esquinas.
121    let esquinas = card(
122        |v| {
123            v.fill_gradient(grad.clone())
124                .border(1.5, white)
125                .radius_corners(34.0, 34.0, 4.0, 4.0)
126        },
127        "Esquinas",
128        white,
129    );
130
131    // 7) Overflow / ellipsis: texto largo clampado a 1 y a 2 líneas, terminando
132    //    en `…`. El ancho de la caja fuerza la envoltura; el clamp recorta.
133    let long = "Texto largo que no entra en el ancho de esta tarjeta angosta y debe recortarse";
134    let clamp = |txt: &str, n: usize, h: f32| {
135        View::<()>::new(Style {
136            size: Size { width: percent(0.86_f32), height: length(h) },
137            ..Default::default()
138        })
139        .text_aligned(txt.to_string(), 13.0, dark, Alignment::Start)
140        .ellipsis(n)
141    };
142    let elipsis = View::<()>::new(Style {
143        size: Size { width: length(180.0_f32), height: length(150.0_f32) },
144        flex_direction: FlexDirection::Column,
145        align_items: Some(AlignItems::CENTER),
146        justify_content: Some(JustifyContent::CENTER),
147        gap: Size { width: length(0.0_f32), height: length(10.0_f32) },
148        ..Default::default()
149    })
150    .radius(16.0)
151    .fill(panel)
152    .border(1.0, theme.accent)
153    .children(vec![
154        clamp(long, 1, 18.0),
155        clamp(long, 2, 36.0),
156        View::<()>::new(Style {
157            size: Size { width: percent(0.9_f32), height: length(20.0_f32) },
158            ..Default::default()
159        })
160        .text_aligned("Ellipsis 1·2", 14.0, dark, Alignment::Center),
161    ]);
162
163    let root = View::<()>::new(Style {
164        size: Size { width: percent(1.0_f32), height: percent(1.0_f32) },
165        flex_direction: FlexDirection::Row,
166        align_items: Some(AlignItems::CENTER),
167        justify_content: Some(JustifyContent::CENTER),
168        gap: Size { width: length(28.0_f32), height: length(0.0_f32) },
169        padding: Rect {
170            left: length(24.0_f32),
171            right: length(24.0_f32),
172            top: length(24.0_f32),
173            bottom: length(24.0_f32),
174        },
175        ..Default::default()
176    })
177    .fill(theme.bg_app)
178    .children(vec![sombra, gradiente, borde, combo, peso, esquinas, elipsis]);
179
180    // view → layout → scene (misma secuencia que el eventloop).
181    let mut layout = LayoutTree::new();
182    let mounted = mount(&mut layout, root);
183    let mut ts = Typesetter::new();
184    let computed = {
185        let tmap = &mounted.text_measures;
186        layout
187            .compute_with_measure(mounted.root, (W as f32, H as f32), |nid, known, avail| {
188                match tmap.get(&nid) {
189                    Some(tm) => measure_text_node(&mut ts, tm, known, avail),
190                    None => taffy::Size::ZERO,
191                }
192            })
193            .expect("layout")
194    };
195    let mut scene = vello::Scene::new();
196    paint(&mut scene, &mounted, &computed, &mut ts, None, None);
197
198    let hal = pollster::block_on(Hal::new(None)).expect("hal");
199    let mut renderer = Renderer::new(&hal).expect("renderer");
200    let target = hal.device.create_texture(&wgpu::TextureDescriptor {
201        label: Some("dump-primitivas"),
202        size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
203        mip_level_count: 1,
204        sample_count: 1,
205        dimension: wgpu::TextureDimension::D2,
206        format: FMT,
207        usage: wgpu::TextureUsages::STORAGE_BINDING
208            | wgpu::TextureUsages::RENDER_ATTACHMENT
209            | wgpu::TextureUsages::COPY_SRC,
210        view_formats: &[],
211    });
212    let view = target.create_view(&wgpu::TextureViewDescriptor::default());
213    let [r, g, b, _] = theme.bg_app.components;
214    let bg = Color::from_rgba8((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8, 255);
215    renderer.render_to_view(&hal, &scene, &view, W, H, bg).expect("render_to_view");
216
217    write_png(&hal, &target, &out);
218    eprintln!("primitivas_demo: escrito {out} ({W}x{H})");
219}
220
221fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
222    let unpadded = (W * 4) as usize;
223    let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
224    let padded = unpadded.div_ceil(align) * align;
225    let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
226        label: Some("readback"),
227        size: (padded * H as usize) as u64,
228        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
229        mapped_at_creation: false,
230    });
231    let mut enc = hal
232        .device
233        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
234    enc.copy_texture_to_buffer(
235        wgpu::TexelCopyTextureInfo {
236            texture: target,
237            mip_level: 0,
238            origin: wgpu::Origin3d::ZERO,
239            aspect: wgpu::TextureAspect::All,
240        },
241        wgpu::TexelCopyBufferInfo {
242            buffer: &buf,
243            layout: wgpu::TexelCopyBufferLayout {
244                offset: 0,
245                bytes_per_row: Some(padded as u32),
246                rows_per_image: Some(H),
247            },
248        },
249        wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
250    );
251    hal.queue.submit(std::iter::once(enc.finish()));
252    let slice = buf.slice(..);
253    let (tx, rx) = std::sync::mpsc::channel();
254    slice.map_async(wgpu::MapMode::Read, move |r| {
255        let _ = tx.send(r);
256    });
257    let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
258    rx.recv().unwrap().unwrap();
259    let data = slice.get_mapped_range();
260    let mut pixels = Vec::with_capacity((W * H * 4) as usize);
261    for row in 0..H as usize {
262        let s = row * padded;
263        pixels.extend_from_slice(&data[s..s + unpadded]);
264    }
265    drop(data);
266    buf.unmap();
267    let file = File::create(path).expect("png");
268    let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
269    enc.set_color(png::ColorType::Rgba);
270    enc.set_depth(png::BitDepth::Eight);
271    let mut w = enc.write_header().unwrap();
272    w.write_image_data(&pixels).unwrap();
273}