Skip to main content

re_core/
tilebuild.rs

1//! Ready-made tilesets and grid builders so a client (agent or GUI) can lay
2//! out floors, paths, dungeons and caves with one call.
3//!
4//! [`preset_tileset`] registers a small kit of primitive-built tiles (floor,
5//! path, wall, corner, ramp, …) with matching materials; the generator
6//! functions paint those tiles onto a [`crate::tileset::TileMap`]:
7//! [`paint_line`] for paths, [`gen_dungeon`] (rooms + corridors + walls) and
8//! [`gen_cave`] (cellular automata). Tile convention: every kit mesh is built
9//! around XZ-center with its bottom at y = 0; [`ops::add_tile_mesh`] places
10//! it with an offset of half a cell.
11
12use std::collections::BTreeSet;
13
14use anyhow::{bail, Result};
15use glam::{EulerRot, Quat, Vec3};
16
17use crate::id::{MaterialId, TileMapId, TileSetId};
18use crate::material::Material;
19use crate::mesh::Mesh;
20use crate::ops;
21use crate::primitives;
22use crate::project::Project;
23use crate::terrain::material_by_name;
24use crate::transform::Transform;
25
26/// Deterministic tiny LCG — no `rand` dependency.
27pub struct Rng(u64);
28
29impl Rng {
30    pub fn new(seed: u64) -> Self {
31        Self(seed | 1)
32    }
33    fn next_u64(&mut self) -> u64 {
34        self.0 = self
35            .0
36            .wrapping_mul(6364136223846793005)
37            .wrapping_add(1442695040888963407);
38        self.0 >> 17
39    }
40    pub fn f32(&mut self) -> f32 {
41        (self.next_u64() % 100000) as f32 / 100000.0
42    }
43    /// Inclusive range; returns `lo` when the range is empty.
44    pub fn int(&mut self, lo: i32, hi: i32) -> i32 {
45        if hi <= lo {
46            return lo;
47        }
48        lo + (self.next_u64() % ((hi - lo + 1) as u64)) as i32
49    }
50}
51
52/// Meshes are built around the XZ center, bottom at y = 0, and are later
53/// offset by half a cell — so every part transform here is expressed with
54/// that origin convention.
55fn box_at(w: f32, h: f32, d: f32, pos: Vec3, rot: Quat) -> Mesh {
56    let mut m = primitives::cube(w, h, d);
57    let t = Transform::from_parts(pos, rot, Vec3::ONE).to_mat4();
58    for p in &mut m.positions {
59        *p = t.transform_point3(Vec3::from_array(*p)).to_array();
60    }
61    m
62}
63
64/// Union of box parts into one mesh (no skin/UVs; normals recomputed).
65pub fn merge_meshes(parts: &[Mesh]) -> Mesh {
66    let mut out = Mesh {
67        name: String::new(),
68        ..Default::default()
69    };
70    for m in parts {
71        let base = out.positions.len() as u32;
72        out.positions.extend_from_slice(&m.positions);
73        let idx = out.indices.get_or_insert_with(Vec::new);
74        for t in m.iter_triangles() {
75            idx.extend_from_slice(&[t[0] + base, t[1] + base, t[2] + base]);
76        }
77    }
78    out.compute_normals();
79    out
80}
81
82/// One kit entry returned by [`preset_tileset`].
83#[derive(Clone, Debug)]
84pub struct KitTile {
85    pub name: String,
86    pub index: u32,
87}
88
89fn kit_mat(p: &mut Project, name: &str, rgba: [f32; 4], emissive: [f32; 3]) -> MaterialId {
90    material_by_name(p, name, || {
91        let mut m = Material::colored(name, rgba);
92        m.roughness = 0.9;
93        m.emissive = emissive;
94        m
95    })
96}
97
98/// Motion the kits apply to their tiles by name (living-world wiring).
99pub fn kit_motion(tile_name: &str, cell: f32) -> crate::motion::Motion {
100    use crate::motion::Motion;
101    match tile_name {
102        "wasser" => Motion::Waves {
103            amp: (cell * 0.02).max(0.02),
104            speed: 1.4,
105        },
106        "baum" | "hecke" => Motion::Sway {
107            amp: (cell * 0.03).max(0.02),
108            speed: 1.1,
109        },
110        "kristall" => Motion::Bob {
111            amp: (cell * 0.025).max(0.02),
112            speed: 0.9,
113        },
114        _ => Motion::None,
115    }
116}
117
118/// Register a primitive-built kit as a new tileset. `kind`: `dungeon`
119/// (Verlies: Boden/Weg/Wand/Ecke/Rampe/Tor), `cave` (Höhle: dunkler Boden,
120/// Wand, Felsbrocken, Kristall, Wasser) or `outdoor` (Gras/Weg/Fels/Baum/
121/// Hecke/Wasser). Returns the tileset id and its named tiles.
122pub fn preset_tileset(
123    p: &mut Project,
124    kind: &str,
125    cell: f32,
126    name: &str,
127) -> Result<(TileSetId, Vec<KitTile>)> {
128    let cell = cell.clamp(0.5, 10.0);
129    let h = cell / 2.0; // center offset applied to every tile
130    let wall_h = cell * 1.6;
131    let kind = kind.to_ascii_lowercase();
132    let ts = ops::create_tileset(p, if name.is_empty() { "kit" } else { name }, cell, cell);
133    let mut tiles: Vec<KitTile> = Vec::new();
134
135    let add = |p: &mut Project,
136               tiles: &mut Vec<KitTile>,
137               tname: &str,
138               mesh: Mesh,
139               mat: MaterialId|
140     -> Result<()> {
141        let mut mesh = mesh;
142        mesh.name = format!("{name}/{tname}");
143        mesh.compute_normals();
144        let mid = p.library.add_mesh(mesh);
145        let idx = ops::add_tile_mesh(
146            p,
147            ts,
148            tname,
149            mid,
150            Transform {
151                translation: [h, 0.0, h],
152                ..Default::default()
153            },
154            Some(mat),
155        )?;
156        // kit wiring: water ripples, foliage sways, crystals float
157        let mo = kit_motion(tname, cell);
158        if !mo.is_none() {
159            let _ = ops::set_tile_motion(p, ts, idx, mo);
160        }
161        tiles.push(KitTile {
162            name: tname.into(),
163            index: idx,
164        });
165        Ok(())
166    };
167
168    let slab = |height: f32| {
169        box_at(
170            cell,
171            height,
172            cell,
173            Vec3::new(0.0, height / 2.0, 0.0),
174            Quat::IDENTITY,
175        )
176    };
177
178    match kind.as_str() {
179        "dungeon" | "verlies" => {
180            let floor = kit_mat(p, "Kit-Boden", [0.30, 0.29, 0.31, 1.0], [0.0; 3]);
181            let path = kit_mat(p, "Kit-Weg", [0.55, 0.47, 0.34, 1.0], [0.0; 3]);
182            let wall = kit_mat(p, "Kit-Wand", [0.46, 0.44, 0.48, 1.0], [0.0; 3]);
183            add(p, &mut tiles, "boden", slab(cell * 0.12), floor)?;
184            add(p, &mut tiles, "weg", slab(cell * 0.15), path)?;
185            add(
186                p,
187                &mut tiles,
188                "wand",
189                box_at(
190                    cell,
191                    wall_h,
192                    cell,
193                    Vec3::new(0.0, wall_h / 2.0, 0.0),
194                    Quat::IDENTITY,
195                ),
196                wall,
197            )?;
198            let ecke = merge_meshes(&[
199                box_at(
200                    cell,
201                    wall_h,
202                    cell,
203                    Vec3::new(0.0, wall_h / 2.0, 0.0),
204                    Quat::IDENTITY,
205                ),
206                box_at(
207                    cell,
208                    wall_h,
209                    cell * 0.6,
210                    Vec3::new(0.0, wall_h / 2.0, -cell * 0.8),
211                    Quat::IDENTITY,
212                ),
213            ]);
214            add(p, &mut tiles, "ecke", ecke, wall)?;
215            let ramp_rot = Quat::from_euler(EulerRot::XYZ, -0.32, 0.0, 0.0);
216            add(
217                p,
218                &mut tiles,
219                "rampe",
220                box_at(
221                    cell,
222                    cell * 0.22,
223                    cell * 1.5,
224                    Vec3::new(0.0, cell * 0.42, 0.0),
225                    ramp_rot,
226                ),
227                path,
228            )?;
229            let tor = merge_meshes(&[
230                box_at(
231                    cell * 0.25,
232                    wall_h,
233                    cell * 0.25,
234                    Vec3::new(-cell * 0.375, wall_h / 2.0, 0.0),
235                    Quat::IDENTITY,
236                ),
237                box_at(
238                    cell * 0.25,
239                    wall_h,
240                    cell * 0.25,
241                    Vec3::new(cell * 0.375, wall_h / 2.0, 0.0),
242                    Quat::IDENTITY,
243                ),
244                box_at(
245                    cell,
246                    cell * 0.3,
247                    cell * 0.25,
248                    Vec3::new(0.0, wall_h + cell * 0.15, 0.0),
249                    Quat::IDENTITY,
250                ),
251            ]);
252            add(p, &mut tiles, "tor", tor, wall)?;
253        }
254        "cave" | "hoehle" | "höhle" => {
255            let floor = kit_mat(p, "Kit-Höhlenboden", [0.20, 0.19, 0.22, 1.0], [0.0; 3]);
256            let wall = kit_mat(p, "Kit-Höhlenwand", [0.34, 0.31, 0.36, 1.0], [0.0; 3]);
257            let rock = kit_mat(p, "Kit-Fels", [0.42, 0.40, 0.42, 1.0], [0.0; 3]);
258            let crystal = kit_mat(
259                p,
260                "Kit-Kristall",
261                [0.30, 0.62, 0.80, 1.0],
262                [0.12, 0.30, 0.45],
263            );
264            let water = material_by_name(p, "Wasser", crate::terrain::water_material);
265            add(p, &mut tiles, "boden", slab(cell * 0.10), floor)?;
266            add(
267                p,
268                &mut tiles,
269                "wand",
270                box_at(
271                    cell * 1.05,
272                    wall_h * 1.2,
273                    cell * 1.05,
274                    Vec3::new(0.0, wall_h * 0.6 + cell * 0.09, 0.0),
275                    Quat::from_euler(EulerRot::XYZ, 0.03, 0.4, 0.05),
276                ),
277                wall,
278            )?;
279            let mut brocken_mesh = primitives::generate(
280                crate::primitives::PrimitiveKind::Sphere,
281                cell * 0.3,
282                cell * 0.22,
283                6,
284            );
285            // uv_sphere uses `a` as radius in all axes → center at the radius so the rock rests on y = 0
286            let brocken = Vec3::new(0.0, cell * 0.3, 0.0);
287            let t = Transform::from_parts(brocken, Quat::IDENTITY, Vec3::ONE).to_mat4();
288            for q in &mut brocken_mesh.positions {
289                *q = t.transform_point3(Vec3::from_array(*q)).to_array();
290            }
291            add(p, &mut tiles, "felsen", brocken_mesh, rock)?;
292            let kristall = box_at(
293                cell * 0.22,
294                cell * 0.75,
295                cell * 0.22,
296                Vec3::new(0.0, cell * 0.5, 0.0),
297                Quat::from_euler(EulerRot::XYZ, 0.12, 0.6, -0.1),
298            );
299            add(p, &mut tiles, "kristall", kristall, crystal)?;
300            add(p, &mut tiles, "wasser", slab(cell * 0.05), water)?;
301        }
302        "outdoor" | "aussen" | "außen" | "natur" => {
303            let grass = kit_mat(p, "Kit-Gras", [0.28, 0.44, 0.22, 1.0], [0.0; 3]);
304            let path = kit_mat(p, "Kit-Weg", [0.55, 0.47, 0.34, 1.0], [0.0; 3]);
305            let rock = kit_mat(p, "Kit-Fels", [0.42, 0.40, 0.42, 1.0], [0.0; 3]);
306            let wood = kit_mat(p, "Kit-Holz", [0.42, 0.30, 0.18, 1.0], [0.0; 3]);
307            let leaves = kit_mat(p, "Kit-Laub", [0.22, 0.40, 0.18, 1.0], [0.0; 3]);
308            let water = material_by_name(p, "Wasser", crate::terrain::water_material);
309            add(p, &mut tiles, "boden", slab(cell * 0.12), grass)?;
310            add(p, &mut tiles, "weg", slab(cell * 0.14), path)?;
311            let mut fels = primitives::generate(
312                crate::primitives::PrimitiveKind::Sphere,
313                cell * 0.34,
314                cell * 0.26,
315                6,
316            );
317            let t =
318                Transform::from_parts(Vec3::new(0.0, cell * 0.34, 0.0), Quat::IDENTITY, Vec3::ONE)
319                    .to_mat4();
320            for q in &mut fels.positions {
321                *q = t.transform_point3(Vec3::from_array(*q)).to_array();
322            }
323            add(p, &mut tiles, "felsen", fels, rock)?;
324            let baum = merge_meshes(&[
325                box_at(
326                    cell * 0.16,
327                    cell * 0.9,
328                    cell * 0.16,
329                    Vec3::new(0.0, cell * 0.45, 0.0),
330                    Quat::IDENTITY,
331                ),
332                {
333                    let mut crown = primitives::generate(
334                        crate::primitives::PrimitiveKind::Sphere,
335                        cell * 0.42,
336                        cell * 0.34,
337                        6,
338                    );
339                    let t = Transform::from_parts(
340                        Vec3::new(0.0, cell * 1.1, 0.0),
341                        Quat::IDENTITY,
342                        Vec3::ONE,
343                    )
344                    .to_mat4();
345                    for q in &mut crown.positions {
346                        *q = t.transform_point3(Vec3::from_array(*q)).to_array();
347                    }
348                    crown
349                },
350            ]);
351            add(p, &mut tiles, "baum", baum, wood)?;
352            let mut hecke = primitives::generate(
353                crate::primitives::PrimitiveKind::Sphere,
354                cell * 0.28,
355                cell * 0.2,
356                5,
357            );
358            let t =
359                Transform::from_parts(Vec3::new(0.0, cell * 0.28, 0.0), Quat::IDENTITY, Vec3::ONE)
360                    .to_mat4();
361            for q in &mut hecke.positions {
362                *q = t.transform_point3(Vec3::from_array(*q)).to_array();
363            }
364            add(p, &mut tiles, "hecke", hecke, leaves)?;
365            add(p, &mut tiles, "wasser", slab(cell * 0.05), water)?;
366        }
367        other => bail!("unknown kit kind '{other}' (use dungeon, cave or outdoor)"),
368    }
369    Ok((ts, tiles))
370}
371
372fn check_tile(p: &Project, map: TileMapId, tile: u32, what: &str) -> Result<()> {
373    let m = p
374        .library
375        .tilemaps
376        .get(&map)
377        .ok_or_else(|| anyhow::anyhow!("tilemap not found"))?;
378    let ts = p
379        .library
380        .tilesets
381        .get(&m.tileset)
382        .ok_or_else(|| anyhow::anyhow!("tileset of tilemap missing"))?;
383    if tile as usize >= ts.tiles.len() {
384        bail!(
385            "{what} tile {tile} out of range (tileset has {} tiles)",
386            ts.tiles.len()
387        );
388    }
389    Ok(())
390}
391
392/// Bresenham line of `tile` from cell `(x0,z0)` to `(x1,z1)`; returns count.
393pub fn paint_line(
394    p: &mut Project,
395    map: TileMapId,
396    x0: i32,
397    z0: i32,
398    x1: i32,
399    z1: i32,
400    tile: u32,
401) -> Result<usize> {
402    check_tile(p, map, tile, "line")?;
403    // i64 deltas: i32 subtraction of extreme coordinates would wrap and
404    // the loop below would never terminate.
405    let dx = (x1 as i64 - x0 as i64).abs();
406    let dz = (z1 as i64 - z0 as i64).abs();
407    if dx.max(dz) as usize > crate::ops::MAX_PAINT_CELLS {
408        bail!(
409            "line too long (limit {} cells)",
410            crate::ops::MAX_PAINT_CELLS
411        );
412    }
413    let sx = if x0 < x1 { 1 } else { -1 };
414    let sz = if z0 < z1 { 1 } else { -1 };
415    let mut err = dx - dz;
416    let (mut x, mut z) = (x0, z0);
417    let mut count = 0;
418    loop {
419        ops::tilemap_set_cell(p, map, x, z, tile)?;
420        count += 1;
421        if x == x1 && z == z1 {
422            break;
423        }
424        let e2 = 2 * err;
425        if e2 > -dz {
426            err -= dz;
427            x += sx;
428        }
429        if e2 < dx {
430            err += dx;
431            z += sz;
432        }
433    }
434    Ok(count)
435}
436
437fn line_cells(x0: i32, z0: i32, x1: i32, z1: i32) -> Vec<(i32, i32)> {
438    let mut out = Vec::new();
439    // i64 deltas (see paint_line): wrapped i32 deltas never terminate.
440    let dx = (x1 as i64 - x0 as i64).abs();
441    let dz = (z1 as i64 - z0 as i64).abs();
442    let cap = crate::ops::MAX_PAINT_CELLS as i64;
443    if dx > cap || dz > cap {
444        return out; // absurd extent: no cells
445    }
446    let sx = if x0 < x1 { 1 } else { -1 };
447    let sz = if z0 < z1 { 1 } else { -1 };
448    let mut err = dx - dz;
449    let (mut x, mut z) = (x0, z0);
450    loop {
451        out.push((x, z));
452        if x == x1 && z == z1 {
453            break;
454        }
455        let e2 = 2 * err;
456        if e2 > -dz {
457            err -= dz;
458            x += sx;
459        }
460        if e2 < dx {
461            err += dx;
462            z += sz;
463        }
464    }
465    out
466}
467
468/// Dungeon parameters: `w`×`h` cells (from cell 0,0), `rooms` random chambers
469/// connected by corridors; every border cell of open space gets the wall tile.
470#[derive(Clone, Debug)]
471pub struct DungeonOpts {
472    pub w: i32,
473    pub h: i32,
474    pub rooms: usize,
475    pub seed: u64,
476    pub floor: u32,
477    pub wall: u32,
478    /// Optional distinct tile for corridors (e.g. "weg"); corridors are then
479    /// kept out of the room floor set.
480    pub path: Option<u32>,
481}
482
483impl Default for DungeonOpts {
484    fn default() -> Self {
485        Self {
486            w: 32,
487            h: 32,
488            rooms: 5,
489            seed: 7,
490            floor: 0,
491            wall: 2,
492            path: None,
493        }
494    }
495}
496
497#[derive(Clone, Copy, Debug, Default)]
498pub struct BuildReport {
499    pub floors: usize,
500    pub walls: usize,
501    pub extra: usize,
502}
503
504/// Rooms + corridors + wall ring painted onto `map` (cells overwritten).
505pub fn gen_dungeon(p: &mut Project, map: TileMapId, opt: &DungeonOpts) -> Result<BuildReport> {
506    check_tile(p, map, opt.floor, "floor")?;
507    check_tile(p, map, opt.wall, "wall")?;
508    if let Some(t) = opt.path {
509        check_tile(p, map, t, "path")?;
510    }
511    let w = opt.w.clamp(8, 256);
512    let h = opt.h.clamp(8, 256);
513    let mut rng = Rng::new(opt.seed);
514
515    let mut floors: BTreeSet<(i32, i32)> = BTreeSet::new();
516    let mut halls: BTreeSet<(i32, i32)> = BTreeSet::new();
517    let mut centers: Vec<(i32, i32)> = Vec::new();
518    for _ in 0..opt.rooms.clamp(1, 40) {
519        let rw = rng.int(3, (w / 3).max(4));
520        let rh = rng.int(3, (h / 3).max(4));
521        let rx = rng.int(1, w - rw - 2).max(1);
522        let rz = rng.int(1, h - rh - 2).max(1);
523        for z in rz..rz + rh {
524            for x in rx..rx + rw {
525                floors.insert((x, z));
526            }
527        }
528        centers.push((rx + rw / 2, rz + rh / 2));
529    }
530    for pair in centers.windows(2) {
531        let cells = line_cells(pair[0].0, pair[0].1, pair[1].0, pair[1].1);
532        for c in cells {
533            if opt.path.is_some() {
534                halls.insert(c);
535            } else {
536                floors.insert(c);
537            }
538        }
539    }
540
541    let mut walls: BTreeSet<(i32, i32)> = BTreeSet::new();
542    for &(x, z) in floors.iter().chain(halls.iter()) {
543        for (dx, dz) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
544            let k = (x + dx, z + dz);
545            if !floors.contains(&k) && !halls.contains(&k) {
546                walls.insert(k);
547            }
548        }
549    }
550
551    let mut report = BuildReport::default();
552    for &(x, z) in &floors {
553        ops::tilemap_set_cell(p, map, x, z, opt.floor)?;
554        report.floors += 1;
555    }
556    if let Some(t) = opt.path {
557        for &(x, z) in &halls {
558            ops::tilemap_set_cell(p, map, x, z, t)?;
559            report.extra += 1;
560        }
561    }
562    for &(x, z) in &walls {
563        ops::tilemap_set_cell(p, map, x, z, opt.wall)?;
564        report.walls += 1;
565    }
566    Ok(report)
567}
568
569/// Cave parameters: cellular automata. `fill` ~ initial wall density,
570/// `smooth` iteration passes; open cells become floor, border walls become
571/// `wall`; rare `accent` tiles (crystals) dot the floor.
572#[derive(Clone, Debug)]
573pub struct CaveOpts {
574    pub w: i32,
575    pub h: i32,
576    pub seed: u64,
577    pub fill: f32,
578    pub smooth: usize,
579    pub floor: u32,
580    pub wall: u32,
581    pub accent: Option<u32>,
582}
583
584impl Default for CaveOpts {
585    fn default() -> Self {
586        Self {
587            w: 32,
588            h: 32,
589            seed: 11,
590            fill: 0.45,
591            smooth: 4,
592            floor: 0,
593            wall: 1,
594            accent: None,
595        }
596    }
597}
598
599/// Organic cave system painted onto `map`.
600pub fn gen_cave(p: &mut Project, map: TileMapId, opt: &CaveOpts) -> Result<BuildReport> {
601    check_tile(p, map, opt.floor, "floor")?;
602    check_tile(p, map, opt.wall, "wall")?;
603    if let Some(t) = opt.accent {
604        check_tile(p, map, t, "accent")?;
605    }
606    let w = opt.w.clamp(8, 256) as usize;
607    let h = opt.h.clamp(8, 256) as usize;
608    let fill = opt.fill.clamp(0.35, 0.6);
609    let rounds = opt.smooth.clamp(1, 8);
610    let mut rng = Rng::new(opt.seed);
611
612    let mut alive = vec![vec![true; h]; w];
613    // Zuerst z, dann x — diese Reihenfolge legt die Rng-Ziehungen fest und
614    // ist damit speicherkompatibel. Spalten-Iteratoren wären hier nicht
615    // natürlich, deshalb Range-Schleife mit dokumentiertem Allow.
616    #[allow(clippy::needless_range_loop)]
617    for z in 0..h {
618        for x in 0..w {
619            alive[x][z] = x == 0 || z == 0 || x == w - 1 || z == h - 1 || rng.f32() < fill;
620        }
621    }
622    let cnt = |g: &[Vec<bool>], x: i32, z: i32| -> u32 {
623        let mut n = 0;
624        for (dx, dz) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
625            let (nx, nz) = (x + dx, z + dz);
626            if nx < 0 || nz < 0 || nx >= w as i32 || nz >= h as i32 {
627                n += 1; // out of bounds counts as rock
628            } else if g[nx as usize][nz as usize] {
629                n += 1;
630            }
631        }
632        n
633    };
634    for _ in 0..rounds {
635        let mut next = alive.clone();
636        for z in 0..h {
637            for x in 0..w {
638                let n = cnt(&alive, x as i32, z as i32);
639                next[x][z] = if alive[x][z] { n >= 2 } else { n >= 4 };
640            }
641        }
642        alive = next;
643    }
644
645    let open: BTreeSet<(i32, i32)> = (0..w as i32)
646        .flat_map(|x| (0..h as i32).map(move |z| (x, z)))
647        .filter(|(x, z)| !alive[*x as usize][*z as usize])
648        .collect();
649    let mut walls: BTreeSet<(i32, i32)> = BTreeSet::new();
650    for &(x, z) in &open {
651        for (dx, dz) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
652            let k = (x + dx, z + dz);
653            if !open.contains(&k) {
654                walls.insert(k);
655            }
656        }
657    }
658
659    let mut report = BuildReport::default();
660    for &(x, z) in &open {
661        let use_accent = opt.accent.is_some_and(|_| rng.f32() < 0.02);
662        let tile = match (use_accent, opt.accent) {
663            (true, Some(t)) => t,
664            _ => opt.floor,
665        };
666        if use_accent {
667            report.extra += 1;
668        }
669        ops::tilemap_set_cell(p, map, x, z, tile)?;
670        report.floors += 1;
671    }
672    for &(x, z) in &walls {
673        ops::tilemap_set_cell(p, map, x, z, opt.wall)?;
674        report.walls += 1;
675    }
676    Ok(report)
677}
678
679#[cfg(test)]
680mod tests {
681    use super::*;
682    use crate::transform::Transform;
683
684    fn dungeon_map(p: &mut Project) -> TileMapId {
685        let (ts, _) = preset_tileset(p, "dungeon", 2.0, "k").unwrap();
686        let (node, map) = ops::create_tilemap(p, "m", ts, None, Transform::default()).unwrap();
687        let _ = node;
688        map
689    }
690
691    #[test]
692    fn presets_build_complete_kits() {
693        let mut p = Project::new("kit");
694        for kind in ["dungeon", "cave", "outdoor"] {
695            let (ts, tiles) = preset_tileset(&mut p, kind, 2.0, kind).unwrap();
696            assert!(tiles.len() >= 5, "{kind}: {}", tiles.len());
697            let t = &p.library.tilesets[&ts];
698            assert_eq!(t.cell, [2.0, 2.0]);
699            for tile in &t.tiles {
700                assert!(p.library.meshes.contains_key(&tile.mesh));
701                // bottom of every tile is at/below y=0, nothing far above a cell
702                let (min, max) = p.library.meshes[&tile.mesh].aabb();
703                assert!(min[1] >= -0.01, "{kind}/{} sinks below floor", tile.name);
704                assert!(max[1] < 8.0, "{kind}/{} absurdly tall", tile.name);
705                // living-world wiring: kit tiles carry their signature motion
706                let want = kit_motion(&tile.name, 2.0);
707                assert_eq!(tile.motion, want, "{kind}/{} motion", tile.name);
708            }
709        }
710        // the signature tiles really animate
711        let outdoor = preset_tileset(&mut p, "outdoor", 2.0, "o2").unwrap();
712        let t = &p.library.tilesets[&outdoor.0];
713        let by = |n: &str| t.tiles.iter().find(|x| x.name == n).unwrap().motion;
714        assert!(matches!(by("wasser"), crate::motion::Motion::Waves { .. }));
715        assert!(matches!(by("baum"), crate::motion::Motion::Sway { .. }));
716        assert!(matches!(by("boden"), crate::motion::Motion::None));
717        assert!(preset_tileset(&mut p, "quatsch", 2.0, "x").is_err());
718    }
719
720    #[test]
721    fn line_paints_a_bresenham_path() {
722        let mut p = Project::new("kit");
723        let map = dungeon_map(&mut p);
724        let n = paint_line(&mut p, map, 0, 0, 5, 2, 1).unwrap();
725        assert_eq!(n, 6);
726        let m = &p.library.tilemaps[&map];
727        assert_eq!(m.get(0, 0), Some(1));
728        assert_eq!(m.get(5, 2), Some(1));
729        assert_eq!(m.get(3, 1), Some(1));
730    }
731
732    #[test]
733    fn dungeon_has_rooms_corridors_and_wall_ring() {
734        let mut p = Project::new("kit");
735        let map = dungeon_map(&mut p);
736        let rep = gen_dungeon(
737            &mut p,
738            map,
739            &DungeonOpts {
740                w: 24,
741                h: 24,
742                rooms: 4,
743                seed: 42,
744                floor: 0,
745                wall: 2,
746                path: Some(1),
747            },
748        )
749        .unwrap();
750        assert!(
751            rep.floors > 50 && rep.walls > 50 && rep.extra > 10,
752            "{rep:?}"
753        );
754        let m = &p.library.tilemaps[&map];
755        // every open cell touches at least one wall somewhere (ring exists)
756        let open: Vec<(i32, i32)> = m
757            .cells
758            .iter()
759            .filter(|c| c.tile != 2)
760            .map(|c| (c.x, c.z))
761            .collect();
762        assert!(!open.is_empty());
763        // walls only neighbour open cells
764        for c in m.cells.iter().filter(|c| c.tile == 2) {
765            let has_open_nb = [(-1, 0), (1, 0), (0, -1), (0, 1)]
766                .iter()
767                .any(|(dx, dz)| open.contains(&(c.x + dx, c.z + dz)));
768            assert!(has_open_nb, "floating wall at {:?}", (c.x, c.z));
769        }
770    }
771
772    #[test]
773    fn cave_is_reproducible_and_has_floor_and_walls() {
774        let opts = CaveOpts {
775            w: 20,
776            h: 20,
777            seed: 3,
778            fill: 0.45,
779            smooth: 4,
780            floor: 0,
781            wall: 2,
782            accent: Some(3),
783        };
784        let mut p = Project::new("kit");
785        let map = dungeon_map(&mut p);
786        let rep = gen_cave(&mut p, map, &opts).unwrap();
787        assert!(rep.floors > 30 && rep.walls > 30, "{rep:?}");
788        let snap = p.library.tilemaps[&map].cells.clone();
789
790        let mut p2 = Project::new("kit");
791        let map2 = dungeon_map(&mut p2);
792        gen_cave(&mut p2, map2, &opts).unwrap();
793        // gleicher Seed => identischer Grundriss (BTreeSet-reihenfolge deterministisch)
794        assert_eq!(snap, p2.library.tilemaps[&map2].cells);
795    }
796}