Skip to main content

Tile

Enum Tile 

Source
pub enum Tile {
    Wall,
    Floor,
}
Expand description

Basic tile type for dungeon/terrain generation.

Variants§

§

Wall

Impassable wall tile.

§

Floor

Passable floor tile.

Implementations§

Source§

impl Tile

Source

pub fn is_wall(&self) -> bool

Returns true if this tile is a wall.

Source

pub fn is_floor(&self) -> bool

Returns true if this tile is a floor.

Examples found in repository?
examples/advanced_pathfinding.rs (line 66)
62fn print_grid(grid: &Grid<Tile>) {
63    for y in 0..grid.height() {
64        for x in 0..grid.width() {
65            let tile = grid.get(x as i32, y as i32).unwrap();
66            print!("{}", if tile.is_floor() { "." } else { "#" });
67        }
68        println!();
69    }
70}
More examples
Hide additional examples
examples/distance_transforms.rs (line 54)
50fn print_grid(grid: &Grid<Tile>) {
51    for y in 0..grid.height() {
52        for x in 0..grid.width() {
53            let tile = grid.get(x as i32, y as i32).unwrap();
54            print!("{}", if tile.is_floor() { "." } else { "#" });
55        }
56        println!();
57    }
58}
examples/delaunay_connections.rs (line 144)
135fn count_rooms(grid: &Grid<Tile>) -> usize {
136    // Simple room counting by finding floor clusters
137    let mut room_count = 0;
138    let mut visited = vec![vec![false; grid.width()]; grid.height()];
139
140    for y in 0..grid.height() {
141        for x in 0..grid.width() {
142            if !visited[y][x] {
143                if let Some(tile) = grid.get(x as i32, y as i32) {
144                    if tile.is_floor() {
145                        flood_fill(grid, &mut visited, x, y);
146                        room_count += 1;
147                    }
148                }
149            }
150        }
151    }
152
153    room_count
154}
155
156fn flood_fill(grid: &Grid<Tile>, visited: &mut [Vec<bool>], start_x: usize, start_y: usize) {
157    let mut stack = vec![(start_x, start_y)];
158
159    while let Some((x, y)) = stack.pop() {
160        if visited[y][x] {
161            continue;
162        }
163        visited[y][x] = true;
164
165        for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
166            let nx = x as i32 + dx;
167            let ny = y as i32 + dy;
168
169            if nx >= 0 && ny >= 0 && (nx as usize) < grid.width() && (ny as usize) < grid.height() {
170                let nx = nx as usize;
171                let ny = ny as usize;
172
173                if !visited[ny][nx] {
174                    if let Some(tile) = grid.get(nx as i32, ny as i32) {
175                        if tile.is_floor() {
176                            stack.push((nx, ny));
177                        }
178                    }
179                }
180            }
181        }
182    }
183}
184
185fn find_room_centers(grid: &Grid<Tile>) -> Vec<Point> {
186    let mut centers = Vec::new();
187    let mut visited = vec![vec![false; grid.width()]; grid.height()];
188
189    for y in 0..grid.height() {
190        for x in 0..grid.width() {
191            if !visited[y][x] {
192                if let Some(tile) = grid.get(x as i32, y as i32) {
193                    if tile.is_floor() {
194                        let center = find_room_center(grid, &mut visited, x, y);
195                        centers.push(center);
196                    }
197                }
198            }
199        }
200    }
201
202    centers
203}
204
205fn find_room_center(
206    grid: &Grid<Tile>,
207    visited: &mut [Vec<bool>],
208    start_x: usize,
209    start_y: usize,
210) -> Point {
211    let mut room_cells = Vec::new();
212    let mut stack = vec![(start_x, start_y)];
213
214    while let Some((x, y)) = stack.pop() {
215        if visited[y][x] {
216            continue;
217        }
218        visited[y][x] = true;
219        room_cells.push((x, y));
220
221        for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
222            let nx = x as i32 + dx;
223            let ny = y as i32 + dy;
224
225            if nx >= 0 && ny >= 0 && (nx as usize) < grid.width() && (ny as usize) < grid.height() {
226                let nx = nx as usize;
227                let ny = ny as usize;
228
229                if !visited[ny][nx] {
230                    if let Some(tile) = grid.get(nx as i32, ny as i32) {
231                        if tile.is_floor() {
232                            stack.push((nx, ny));
233                        }
234                    }
235                }
236            }
237        }
238    }
239
240    // Calculate centroid
241    let sum_x: usize = room_cells.iter().map(|(x, _)| x).sum();
242    let sum_y: usize = room_cells.iter().map(|(_, y)| y).sum();
243    let count = room_cells.len();
244
245    Point::new(sum_x as f32 / count as f32, sum_y as f32 / count as f32)
246}
examples/phase1_demo.rs (line 90)
76fn demo_generate_with_requirements() {
77    println!("📋 Demo 2: Generate with Requirements");
78
79    let mut requirements = SemanticRequirements::basic_dungeon();
80    requirements.min_regions.insert("room".to_string(), 4);
81    requirements
82        .required_markers
83        .insert(MarkerType::LootTier { tier: 1 }, 2);
84
85    match terrain_forge::generate_with_requirements("bsp", 60, 40, requirements, Some(5), 54321) {
86        Ok((grid, semantic)) => {
87            println!("  ✅ Generated valid dungeon!");
88            println!("  Regions: {}", semantic.regions.len());
89            println!("  Markers: {}", semantic.markers.len());
90            println!("  Floor tiles: {}", grid.count(|t| t.is_floor()));
91        }
92        Err(msg) => println!("  ❌ Failed: {}", msg),
93    }
94    println!();
95}
examples/bsp_analysis.rs (line 14)
3fn main() {
4    println!("=== BSP Algorithm Analysis ===\n");
5
6    let mut grid = Grid::new(40, 30);
7    algorithms::get("bsp").unwrap().generate(&mut grid, 12345);
8
9    let extractor = SemanticExtractor::for_rooms();
10    let mut rng = Rng::new(12345);
11    let semantic = extractor.extract(&grid, &mut rng);
12
13    println!("Generated map analysis:");
14    println!("  Floor tiles: {}", grid.count(|t| t.is_floor()));
15    println!("  Total regions: {}", semantic.regions.len());
16
17    println!("\nRegion breakdown:");
18    let mut region_counts = std::collections::HashMap::new();
19    for region in &semantic.regions {
20        *region_counts.entry(&region.kind).or_insert(0) += 1;
21    }
22
23    for (kind, count) in &region_counts {
24        println!("  {}: {}", kind, count);
25    }
26
27    println!("\nMarker breakdown:");
28    let mut marker_counts = std::collections::HashMap::new();
29    for marker in &semantic.markers {
30        *marker_counts.entry(marker.tag()).or_insert(0) += 1;
31    }
32
33    for (tag, count) in &marker_counts {
34        println!("  {}: {}", tag, count);
35    }
36}
examples/requirements_demo.rs (line 22)
3fn main() {
4    println!("=== Generate with Requirements Demo ===\n");
5
6    // Create simple requirements that match BSP output
7    let mut requirements = SemanticRequirements::none();
8    requirements.min_regions.insert("Hall".to_string(), 1); // BSP produces "Hall" regions
9    requirements
10        .required_markers
11        .insert(MarkerType::Custom("PlayerStart".to_string()), 1); // BSP produces "PlayerStart"
12
13    println!("Requirements:");
14    println!("  - Minimum 1 Hall region");
15    println!("  - At least 1 PlayerStart marker");
16    println!();
17
18    match generate_with_requirements("bsp", 40, 30, requirements, Some(10), 12345) {
19        Ok((grid, semantic)) => {
20            println!("✅ Successfully generated map meeting requirements!");
21            println!("  Grid size: {}x{}", grid.width(), grid.height());
22            println!("  Floor tiles: {}", grid.count(|t| t.is_floor()));
23            println!("  Total regions: {}", semantic.regions.len());
24
25            // Count Hall regions
26            let hall_count = semantic.regions.iter().filter(|r| r.kind == "Hall").count();
27            println!("  Hall regions: {}", hall_count);
28
29            // Count PlayerStart markers
30            let start_count = semantic
31                .markers
32                .iter()
33                .filter(|m| m.tag() == "PlayerStart")
34                .count();
35            println!("  PlayerStart markers: {}", start_count);
36
37            println!("\nFirst few regions:");
38            for (i, region) in semantic.regions.iter().take(3).enumerate() {
39                println!("  {}: {} ({} cells)", i + 1, region.kind, region.area());
40            }
41        }
42        Err(msg) => {
43            println!("❌ Failed to generate: {}", msg);
44        }
45    }
46}

Trait Implementations§

Source§

impl Cell for Tile

Source§

fn is_passable(&self) -> bool

Returns true if this cell is passable (walkable).
Source§

fn set_passable(&mut self)

Marks this cell as passable. Default implementation is a no-op.
Source§

impl Clone for Tile

Source§

fn clone(&self) -> Tile

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Tile

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Tile

Source§

fn default() -> Tile

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Tile

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Tile

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for Tile

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Tile

Source§

fn eq(&self, other: &Tile) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Tile

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Copy for Tile

Source§

impl Eq for Tile

Source§

impl StructuralPartialEq for Tile

Auto Trait Implementations§

§

impl Freeze for Tile

§

impl RefUnwindSafe for Tile

§

impl Send for Tile

§

impl Sync for Tile

§

impl Unpin for Tile

§

impl UnwindSafe for Tile

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,