gioser

tawasuyu/llimphi

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

Rust 229TOML 101Markdown 82Shell 24052 Definitions

⎇ main llimphi-voxel/examples/house_demo.rs Rust · 249 lines · 8.5 KB History Who touched what raw

chore: refresco desde el monorepo — 27 crates nuevos (anim, lottie, svg, mesh, image, layer, test, wire-view, widgets rag-sidebar/router/lazy-list/rive-button) y sync de los 95 existentes 93253cc22 · Sergio ·

1//! Casita de voxels construida con los **materiales de casa**: muros de ladrillo,
2//! piso y puerta de madera, ventanas de **vidrio** (lustroso → glasean al sol),
3//! techo a dos aguas de teja y una chimenea de pizarra. Verifica la tanda de
4//! materiales de obra *en contexto* y el brillo de los materiales (no sólo minerales).
5//!
6//! `cargo run -p llimphi-voxel --example house_demo --release` → `/tmp/house.png`
7
8use std::fs::File;
9use std::io::BufWriter;
10
11use llimphi_3d::glam::Vec3;
12use llimphi_3d::{Atmosphere, Camera3d, Scene3d, VoxelGrid, VoxelRenderer};
13use llimphi_hal::{wgpu, Hal};
14use llimphi_raster::peniko::Color;
15use llimphi_raster::{vello, Renderer};
16use llimphi_voxel::Material;
17
18const W: u32 = 1180;
19const H: u32 = 700;
20const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
21
22/// Coloca un voxel del material `m`, llevando su brillo en el alpha (los lustrosos
23/// como el vidrio glasean; los mate quedan en 255).
24fn put(g: &mut VoxelGrid, x: i32, y: i32, z: i32, m: Material) {
25    if x < 0 || y < 0 || z < 0 {
26        return;
27    }
28    let a = VoxelGrid::shine_to_alpha(m.brillo());
29    g.set_rgba(x as u32, y as u32, z as u32, m.color(), a);
30}
31
32fn main() {
33    let dim = [56u32, 44, 52];
34    let mut g = VoxelGrid::new(dim);
35
36    // Césped.
37    let gh = 4i32;
38    for x in 0..dim[0] as i32 {
39        for z in 0..dim[2] as i32 {
40            for y in 0..gh {
41                let t = ((x * 5 + z * 7 + y) % 9) as i32 - 4;
42                let base = Material::Grass.color();
43                let c = |v: u8| (v as i32 + t).clamp(0, 255) as u8;
44                g.set(x as u32, y as u32, z as u32, [c(base[0]), c(base[1]), c(base[2])]);
45            }
46        }
47    }
48
49    // Footprint de la casa.
50    let (x0, z0) = (12i32, 12i32);
51    let (wd, dp) = (26i32, 22i32); // ancho (x), profundidad (z)
52    let wh = 9i32; // alto de muros
53    let (x1, z1) = (x0 + wd - 1, z0 + dp - 1);
54
55    // Piso de madera.
56    for x in x0..=x1 {
57        for z in z0..=z1 {
58            put(&mut g, x, gh, z, Material::Madera);
59        }
60    }
61
62    // Muros de ladrillo (perímetro).
63    for yy in 0..wh {
64        let y = gh + 1 + yy;
65        for x in x0..=x1 {
66            put(&mut g, x, y, z0, Material::Ladrillo);
67            put(&mut g, x, y, z1, Material::Ladrillo);
68        }
69        for z in z0..=z1 {
70            put(&mut g, x0, y, z, Material::Ladrillo);
71            put(&mut g, x1, y, z, Material::Ladrillo);
72        }
73    }
74
75    // Vigas de acero en las esquinas (lustrosas).
76    for yy in 0..wh {
77        let y = gh + 1 + yy;
78        for (cx, cz) in [(x0, z0), (x1, z0), (x0, z1), (x1, z1)] {
79            put(&mut g, cx, y, cz, Material::Acero);
80        }
81    }
82
83    // Puerta de madera (pared frontal z0, centrada).
84    let dcx = x0 + wd / 2;
85    for yy in 0..5 {
86        for dx in -1..=1 {
87            put(&mut g, dcx + dx, gh + 1 + yy, z0, Material::Madera);
88        }
89    }
90
91    // Ventanas de vidrio (3×3) en las cuatro paredes.
92    let ventana = |g: &mut VoxelGrid, cx: i32, cz: i32, along_x: bool| {
93        for a in -1..=1 {
94            for b in 0..3 {
95                let y = gh + 3 + b;
96                if along_x {
97                    put(g, cx + a, y, cz, Material::Vidrio);
98                } else {
99                    put(g, cx, y, cz + a, Material::Vidrio);
100                }
101            }
102        }
103    };
104    // Frontal: dos ventanas flanqueando la puerta.
105    ventana(&mut g, x0 + 4, z0, true);
106    ventana(&mut g, x1 - 4, z0, true);
107    // Trasera.
108    ventana(&mut g, x0 + wd / 3, z1, true);
109    ventana(&mut g, x1 - wd / 3, z1, true);
110    // Laterales.
111    ventana(&mut g, x0, z0 + dp / 2, false);
112    ventana(&mut g, x1, z0 + dp / 2, false);
113
114    // Techo a dos aguas de teja (cumbrera a lo largo de x), con alero de 1.
115    let roof_base = gh + 1 + wh;
116    let half = (dp + 1) / 2;
117    for r in 0..half {
118        let y = roof_base + r;
119        let za = z0 - 1 + r; // agua norte
120        let zb = z1 + 1 - r; // agua sur
121        for x in (x0 - 1)..=(x1 + 1) {
122            put(&mut g, x, y, za, Material::Teja);
123            put(&mut g, x, y, zb, Material::Teja);
124        }
125    }
126
127    // Chimenea de pizarra (sobresale del techo).
128    let (chx, chz) = (x1 - 3, z0 + 3);
129    for y in (gh + 1)..(roof_base + half + 2) {
130        for dx in 0..2 {
131            for dz in 0..2 {
132                put(&mut g, chx + dx, y, chz + dz, Material::Pizarra);
133            }
134        }
135    }
136
137    // --- Render ---
138    let hal = pollster::block_on(Hal::new(None)).expect("hal");
139    let mut renderer = Renderer::new(&hal).expect("renderer");
140    let mut vr = VoxelRenderer::new(&hal.device, &hal.queue, FMT, &g);
141    vr.sun_dir = [0.42, 0.66, 0.62]; // sol alto-frontal → las ventanas glasean
142    vr.atmosphere = Atmosphere {
143        sky_zenith: [96, 146, 208],
144        sky_horizon: [206, 220, 232],
145        fog_density: 0.0,
146        god_rays: 0.0,
147    };
148    let camera = Camera3d::orbit(
149        Vec3::new(0.0, dim[1] as f32 * 0.06, 0.0),
150        34_f32.to_radians(),
151        20_f32.to_radians(),
152        dim[0] as f32 * 1.15,
153    );
154    let mut scene = Scene3d::new();
155    let pixels = render(&hal, &mut renderer, &mut scene, &mut vr, &camera);
156    write_png(&pixels, "/tmp/house.png");
157    eprintln!("escrito /tmp/house.png — casita con materiales de obra (vidrio/acero lustrosos)");
158}
159
160fn render(
161    hal: &Hal,
162    renderer: &mut Renderer,
163    scene: &mut Scene3d,
164    vr: &mut VoxelRenderer,
165    camera: &Camera3d,
166) -> Vec<u8> {
167    let inter = hal.device.create_texture(&wgpu::TextureDescriptor {
168        label: Some("inter"),
169        size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
170        mip_level_count: 1,
171        sample_count: 1,
172        dimension: wgpu::TextureDimension::D2,
173        format: FMT,
174        usage: wgpu::TextureUsages::STORAGE_BINDING
175            | wgpu::TextureUsages::TEXTURE_BINDING
176            | wgpu::TextureUsages::RENDER_ATTACHMENT
177            | wgpu::TextureUsages::COPY_SRC,
178        view_formats: &[],
179    });
180    let view = inter.create_view(&wgpu::TextureViewDescriptor::default());
181    renderer
182        .render_to_view(hal, &vello::Scene::new(), &view, W, H, Color::from_rgba8(0, 0, 0, 255))
183        .expect("base");
184    let mut enc = hal
185        .device
186        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("house") });
187    scene.render(&hal.device, &hal.queue, &mut enc, &view, (W, H), camera, Some(vr), &[]);
188    hal.queue.submit(std::iter::once(enc.finish()));
189    let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
190    readback(hal, &inter)
191}
192
193fn readback(hal: &Hal, target: &wgpu::Texture) -> Vec<u8> {
194    let unpadded = (W * 4) as usize;
195    let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
196    let padded = unpadded.div_ceil(align) * align;
197    let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
198        label: Some("readback"),
199        size: (padded * H as usize) as u64,
200        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
201        mapped_at_creation: false,
202    });
203    let mut enc = hal
204        .device
205        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
206    enc.copy_texture_to_buffer(
207        wgpu::TexelCopyTextureInfo {
208            texture: target,
209            mip_level: 0,
210            origin: wgpu::Origin3d::ZERO,
211            aspect: wgpu::TextureAspect::All,
212        },
213        wgpu::TexelCopyBufferInfo {
214            buffer: &buf,
215            layout: wgpu::TexelCopyBufferLayout {
216                offset: 0,
217                bytes_per_row: Some(padded as u32),
218                rows_per_image: Some(H),
219            },
220        },
221        wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
222    );
223    hal.queue.submit(std::iter::once(enc.finish()));
224    let slice = buf.slice(..);
225    let (tx, rx) = std::sync::mpsc::channel();
226    slice.map_async(wgpu::MapMode::Read, move |r| {
227        let _ = tx.send(r);
228    });
229    let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
230    rx.recv().unwrap().unwrap();
231    let data = slice.get_mapped_range();
232    let mut pixels = Vec::with_capacity((W * H * 4) as usize);
233    for row in 0..H as usize {
234        let srow = row * padded;
235        pixels.extend_from_slice(&data[srow..srow + unpadded]);
236    }
237    drop(data);
238    buf.unmap();
239    pixels
240}
241
242fn write_png(pixels: &[u8], path: &str) {
243    let file = File::create(path).expect("png");
244    let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
245    enc.set_color(png::ColorType::Rgba);
246    enc.set_depth(png::BitDepth::Eight);
247    let mut wtr = enc.write_header().unwrap();
248    wtr.write_image_data(pixels).unwrap();
249}