tawasuyu/llimphi
Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.
⎇ c5a232cf24788ab75a850ffe81eca5a7af50e2f8
llimphi-compositor/examples/anim_demo.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
refresh: stack al día (vello 0.7 / wgpu 27 / parley 0.6) + motor 3D voxel
1//! Filmstrip headless de **animaciones implícitas**, tres filas:
2//!
3//! - **Fila 1** — `View::animated`: el mismo nodo cuyo `fill` cambia de rojo a
4//! azul, reconciliado a 6 instantes crecientes — crossfade rojo→púrpura→azul.
5//! - **Fila 2** — `View::animated_enter`: el fade-in de ENTRADA de un nodo, de
6//! opacidad 0 a opaco, a los mismos 6 progresos.
7//! - **Fila 3** — `View::animated_exit`: el fade-out de SALIDA de un nodo
8//! (capturado mientras vivía, reproducido como fantasma), de opaco a 0.
9//!
10//! Prueba el camino completo View.animated[_enter|_exit] → AnimRegistry →
11//! paint/paint_range/replay_ghosts → píxeles.
12//!
13//! `cargo run -p llimphi-compositor --example anim_demo -- [out.png]`
14
15use std::fs::File;
16use std::io::BufWriter;
17use std::time::{Duration, Instant};
18
19use llimphi_compositor::{mount, paint, paint_range, AnimRegistry, View};
20use llimphi_hal::{wgpu, Hal};
21use llimphi_layout::taffy::prelude::{length, FlexDirection, Size, Style};
22use llimphi_layout::taffy::{AlignItems, JustifyContent};
23use llimphi_layout::LayoutTree;
24use llimphi_raster::peniko::Color;
25use llimphi_raster::{vello, Renderer};
26use llimphi_text::{Alignment, Typesetter};
27use vello::kurbo::Affine;
28
29const W: u32 = 1180;
30const H: u32 = 580;
31/// Y de la fila de crossfade, de fade-in de entrada y de fade-out de salida.
32const ROW_FADE_Y: f64 = 40.0;
33const ROW_ENTER_Y: f64 = 220.0;
34const ROW_EXIT_Y: f64 = 400.0;
35const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
36const FRAMES: usize = 6;
37const DUR: Duration = Duration::from_millis(500);
38
39fn rgb(r: u8, g: u8, b: u8) -> Color {
40 Color::from_rgba8(r, g, b, 255)
41}
42
43/// Una tarjeta animada (key=1) con `fill`, transladada (vía `transform`) a su
44/// columna `i` y con el `fill` que la `view` "quiere" este frame.
45fn card_shell(col: usize, row_y: f64, label: &str, fg: Color) -> View<()> {
46 View::<()>::new(Style {
47 size: Size { width: length(170.0), height: length(140.0) },
48 align_items: Some(AlignItems::Center),
49 justify_content: Some(JustifyContent::Center),
50 flex_direction: FlexDirection::Column,
51 ..Default::default()
52 })
53 .transform(Affine::translate((20.0 + col as f64 * 190.0, row_y)))
54 .radius(18.0)
55 .children(vec![View::<()>::new(Style {
56 size: Size { width: length(150.0), height: length(20.0) },
57 ..Default::default()
58 })
59 .text_aligned(label.to_string(), 13.0, fg, Alignment::Center)])
60}
61
62fn card(fill: Color, col: usize, label: &str, fg: Color) -> View<()> {
63 card_shell(col, ROW_FADE_Y, label, fg).fill(fill).animated(1, DUR)
64}
65
66/// Tarjeta con animación de ENTRADA: su primera aparición sube de opacidad 0
67/// a opaco. La key se varía por columna (key=10+col) para que cada registro la
68/// trate como una entrada nueva e independiente.
69fn card_enter(col: usize, label: &str, fg: Color) -> View<()> {
70 card_shell(col, ROW_ENTER_Y, label, fg)
71 .fill(rgb(60, 90, 220))
72 .animated_enter(10 + col as u64, DUR)
73}
74
75/// Tarjeta con animación de SALIDA: cuando desaparece, el runtime reproduce su
76/// subescena capturada con opacidad decreciente. Verde para distinguir la fila.
77fn card_exit(col: usize, label: &str, fg: Color) -> View<()> {
78 card_shell(col, ROW_EXIT_Y, label, fg)
79 .fill(rgb(40, 160, 90))
80 .animated_exit(20 + col as u64, DUR)
81}
82
83fn main() {
84 let out = std::env::args().nth(1).unwrap_or_else(|| "anim.png".to_string());
85 let red = rgb(220, 60, 60);
86 let blue = rgb(60, 90, 220);
87 let white = rgb(245, 245, 250);
88
89 // Un registro por columna: cada uno se asienta en rojo y arranca el tween
90 // a azul en t0, pero se OBSERVA a un instante distinto (i * paso). Así el
91 // filmstrip muestra la misma transición a 6 progresos.
92 let t0 = Instant::now();
93 let step = DUR / (FRAMES as u32 - 1);
94
95 let mut cards = Vec::new();
96 for i in 0..FRAMES {
97 let mut reg = AnimRegistry::new();
98 // Frame de asentamiento (rojo) en t0.
99 {
100 let mut layout = LayoutTree::new();
101 let mut m = mount(&mut layout, card(red, i, "", white));
102 reg.reconcile(&mut m, t0);
103 }
104 // Frame de detección del cambio a azul (arranca el reloj en t0).
105 {
106 let mut layout = LayoutTree::new();
107 let mut m = mount(&mut layout, card(blue, i, "", white));
108 reg.reconcile(&mut m, t0);
109 }
110 // Frame de observación: el nodo `card` se reconcilia a t0 + i*paso y su
111 // `fill` queda con el valor interpolado. Lo dejamos para pintar.
112 let now = t0 + step * i as u32;
113 let pct = (i as f32 / (FRAMES as f32 - 1.0) * 100.0).round() as i32;
114 let mut layout = LayoutTree::new();
115 let mut m = mount(&mut layout, card(blue, i, &format!("{pct}%"), white));
116 let computed = layout.compute(m.root, (W as f32, H as f32)).expect("layout");
117 reg.reconcile(&mut m, now);
118 cards.push((m, computed));
119
120 // Fila de entrada: la PRIMERA aparición ARRANCA el tween (en t0), así
121 // que el frame de observación a `now` ve el progreso correcto. Si se
122 // reconciliara una sola vez en `now`, el tween arrancaría y se
123 // observaría en el mismo instante → siempre t=0 (invisible).
124 let mut reg_enter = AnimRegistry::new();
125 {
126 let mut layout = LayoutTree::new();
127 let mut me = mount(&mut layout, card_enter(i, "", white));
128 reg_enter.reconcile(&mut me, t0);
129 }
130 let mut layout = LayoutTree::new();
131 let mut me = mount(&mut layout, card_enter(i, &format!("{pct}%"), white));
132 let computed = layout.compute(me.root, (W as f32, H as f32)).expect("layout");
133 reg_enter.reconcile(&mut me, now);
134 cards.push((me, computed));
135 }
136
137 // Fila de SALIDA: cada columna corre el ciclo real captura→fantasma→replay.
138 // (1) frame VIVO en t0: se reconcilia y se captura su subescena con
139 // `paint_range`. (2) frame AUSENTE en t0: la key desaparece → se promueve a
140 // fantasma (start=t0). (3) `replay_ghosts` a t0+paso·i lo pinta con la
141 // opacidad decreciente sobre `ghost_scene`, que luego se compone.
142 let mut ts_exit = Typesetter::new();
143 let mut ghost_scene = vello::Scene::new();
144 for i in 0..FRAMES {
145 let mut reg = AnimRegistry::new();
146 // (1) Vivo: reconcilia y captura su subárbol (root = idx 0).
147 {
148 let mut layout = LayoutTree::new();
149 let mut mv = mount(&mut layout, card_exit(i, "", white));
150 let computed = layout.compute(mv.root, (W as f32, H as f32)).expect("layout");
151 reg.reconcile(&mut mv, t0);
152 let n = mv.nodes.len();
153 let mut sub = vello::Scene::new();
154 paint_range(&mut sub, &mv, &computed, &mut ts_exit, None, None, 0, n, Affine::IDENTITY);
155 reg.store_live_exit(20 + i as u64, sub, DUR, llimphi_compositor::ease_out_cubic);
156 }
157 // (2) Ausente: la key se va → fantasma con start=t0.
158 {
159 let mut layout = LayoutTree::new();
160 let mut empty = mount(&mut layout, card_shell(i, ROW_EXIT_Y, "", white));
161 layout.compute(empty.root, (W as f32, H as f32)).expect("layout");
162 reg.reconcile(&mut empty, t0);
163 }
164 // (3) Observación: el fantasma se reproduce al progreso `now`.
165 let now = t0 + step * i as u32;
166 let pct = (i as f32 / (FRAMES as f32 - 1.0) * 100.0).round() as i32;
167 reg.replay_ghosts(&mut ghost_scene, now, W as f32, H as f32);
168 // Rótulo del progreso sobre la tarjeta (fuera del fantasma, siempre nítido).
169 let mut layout = LayoutTree::new();
170 let mut lbl = mount(&mut layout, card_shell(i, ROW_EXIT_Y, &format!("{pct}%"), rgb(40, 50, 60)));
171 let lc = layout.compute(lbl.root, (W as f32, H as f32)).expect("layout");
172 // Sólo el texto (sin fill): reusa la tarjeta vacía como portador del label.
173 lbl.nodes[0].fill = None;
174 cards.push((lbl, lc));
175 }
176
177 // Pinta las columnas (cada una su árbol ya reconciliado) en una escena, y
178 // por debajo de los rótulos compone los fantasmas de la fila de salida.
179 let mut ts = Typesetter::new();
180 let mut scene = vello::Scene::new();
181 scene.append(&ghost_scene, None);
182 for (m, computed) in &cards {
183 paint(&mut scene, m, computed, &mut ts, None, None);
184 }
185
186 // Volcado a PNG.
187 let hal = pollster::block_on(Hal::new(None)).expect("hal");
188 let mut renderer = Renderer::new(&hal).expect("renderer");
189 let target = hal.device.create_texture(&wgpu::TextureDescriptor {
190 label: Some("dump-anim"),
191 size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
192 mip_level_count: 1,
193 sample_count: 1,
194 dimension: wgpu::TextureDimension::D2,
195 format: FMT,
196 usage: wgpu::TextureUsages::STORAGE_BINDING
197 | wgpu::TextureUsages::RENDER_ATTACHMENT
198 | wgpu::TextureUsages::COPY_SRC,
199 view_formats: &[],
200 });
201 let view = target.create_view(&wgpu::TextureViewDescriptor::default());
202 let bg = rgb(244, 245, 248);
203 renderer.render_to_view(&hal, &scene, &view, W, H, bg).expect("render_to_view");
204 write_png(&hal, &target, &out);
205 eprintln!(
206 "anim_demo: escrito {out} ({W}x{H}) — fila 1: crossfade rojo→azul · \
207 fila 2: fade-in de entrada · fila 3: fade-out de salida · {FRAMES} pasos"
208 );
209}
210
211fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
212 let unpadded = (W * 4) as usize;
213 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
214 let padded = unpadded.div_ceil(align) * align;
215 let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
216 label: Some("readback"),
217 size: (padded * H as usize) as u64,
218 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
219 mapped_at_creation: false,
220 });
221 let mut enc = hal
222 .device
223 .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
224 enc.copy_texture_to_buffer(
225 wgpu::TexelCopyTextureInfo {
226 texture: target,
227 mip_level: 0,
228 origin: wgpu::Origin3d::ZERO,
229 aspect: wgpu::TextureAspect::All,
230 },
231 wgpu::TexelCopyBufferInfo {
232 buffer: &buf,
233 layout: wgpu::TexelCopyBufferLayout {
234 offset: 0,
235 bytes_per_row: Some(padded as u32),
236 rows_per_image: Some(H),
237 },
238 },
239 wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
240 );
241 hal.queue.submit(std::iter::once(enc.finish()));
242 let slice = buf.slice(..);
243 let (tx, rx) = std::sync::mpsc::channel();
244 slice.map_async(wgpu::MapMode::Read, move |r| {
245 let _ = tx.send(r);
246 });
247 hal.device.poll(wgpu::PollType::wait_indefinitely());
248 rx.recv().unwrap().unwrap();
249 let data = slice.get_mapped_range();
250 let mut pixels = Vec::with_capacity((W * H * 4) as usize);
251 for row in 0..H as usize {
252 let s = row * padded;
253 pixels.extend_from_slice(&data[s..s + unpadded]);
254 }
255 drop(data);
256 buf.unmap();
257 let file = File::create(path).expect("png");
258 let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
259 enc.set_color(png::ColorType::Rgba);
260 enc.set_depth(png::BitDepth::Eight);
261 let mut w = enc.write_header().unwrap();
262 w.write_image_data(&pixels).unwrap();
263}