bevy_map_autotile 0.3.0

Tiled-compatible terrain autotile system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Terrain types and data structures
//!
//! This module contains the core terrain types used for autotiling.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// Simple RGBA color for terrain visualization (no Bevy dependency)
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Color {
    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
        Self { r, g, b, a }
    }

    pub const fn rgb(r: f32, g: f32, b: f32) -> Self {
        Self { r, g, b, a: 1.0 }
    }

    pub const WHITE: Self = Self::rgb(1.0, 1.0, 1.0);
    pub const BLACK: Self = Self::rgb(0.0, 0.0, 0.0);
    pub const RED: Self = Self::rgb(1.0, 0.0, 0.0);
    pub const GREEN: Self = Self::rgb(0.0, 1.0, 0.0);
    pub const BLUE: Self = Self::rgb(0.0, 0.0, 1.0);
}

impl Default for Color {
    fn default() -> Self {
        Self::WHITE
    }
}

/// Type of terrain set - determines how tiles are matched
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum TerrainSetType {
    /// 4 corners per tile (TL, TR, BL, BR)
    /// Good for basic terrain transitions
    #[default]
    Corner,
    /// 4 edges per tile (Top, Right, Bottom, Left)
    /// Good for roads, platforms, paths
    Edge,
    /// 4 corners + 4 edges per tile
    /// Most flexible, requires more tiles
    Mixed,
}

impl TerrainSetType {
    /// Get the number of positions used by this terrain set type
    pub fn position_count(&self) -> usize {
        match self {
            TerrainSetType::Corner => 4,
            TerrainSetType::Edge => 4,
            TerrainSetType::Mixed => 8,
        }
    }

    /// Get the name for a position index
    pub fn position_name(&self, index: usize) -> &'static str {
        match self {
            TerrainSetType::Corner => match index {
                0 => "Top-Left",
                1 => "Top-Right",
                2 => "Bottom-Left",
                3 => "Bottom-Right",
                _ => "Unknown",
            },
            TerrainSetType::Edge => match index {
                0 => "Top",
                1 => "Right",
                2 => "Bottom",
                3 => "Left",
                _ => "Unknown",
            },
            TerrainSetType::Mixed => match index {
                0 => "Top-Left Corner",
                1 => "Top Edge",
                2 => "Top-Right Corner",
                3 => "Right Edge",
                4 => "Bottom-Right Corner",
                5 => "Bottom Edge",
                6 => "Bottom-Left Corner",
                7 => "Left Edge",
                _ => "Unknown",
            },
        }
    }
}

/// A terrain type within a set (e.g., "Grass", "Dirt", "Water")
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Terrain {
    pub id: Uuid,
    pub name: String,
    /// Display color for UI visualization
    pub color: Color,
    /// Representative tile for this terrain (shown in UI)
    pub icon_tile: Option<u32>,
}

impl Terrain {
    pub fn new(name: String, color: Color) -> Self {
        Self {
            id: Uuid::new_v4(),
            name,
            color,
            icon_tile: None,
        }
    }
}

/// Terrain assignments for a single tile's corners/edges/center
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TileTerrainData {
    /// Terrain index at each position (None = no terrain assigned)
    /// For Corner: indices 0-3 (TL, TR, BL, BR)
    /// For Edge: indices 0-3 (Top, Right, Bottom, Left)
    /// For Mixed: indices 0-7 (TL, T, TR, R, BR, B, BL, L - clockwise from top-left)
    ///            index 8 = Center (visual only, doesn't affect Wang matching)
    #[serde(deserialize_with = "deserialize_terrains")]
    pub terrains: [Option<usize>; 9],
}

/// Custom deserializer that handles both old 8-element and new 9-element terrain arrays
fn deserialize_terrains<'de, D>(deserializer: D) -> Result<[Option<usize>; 9], D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{SeqAccess, Visitor};

    struct TerrainsVisitor;

    impl<'de> Visitor<'de> for TerrainsVisitor {
        type Value = [Option<usize>; 9];

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("an array of 8 or 9 optional terrain indices")
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let mut terrains = [None; 9];
            let mut i = 0;
            while let Some(value) = seq.next_element()? {
                if i < 9 {
                    terrains[i] = value;
                }
                i += 1;
            }
            // If we read 8 elements (old format), the 9th stays None (center unassigned)
            // If we read 9 elements (new format), all are populated
            Ok(terrains)
        }
    }

    deserializer.deserialize_seq(TerrainsVisitor)
}

impl TileTerrainData {
    pub fn new() -> Self {
        Self {
            terrains: [None; 9],
        }
    }

    /// Set terrain at a specific position
    pub fn set(&mut self, position: usize, terrain_index: Option<usize>) {
        if position < 9 {
            self.terrains[position] = terrain_index;
        }
    }

    /// Get terrain at a specific position
    pub fn get(&self, position: usize) -> Option<usize> {
        self.terrains.get(position).copied().flatten()
    }

    /// Check if this tile has any terrain assigned
    pub fn has_any_terrain(&self) -> bool {
        self.terrains.iter().any(|t| t.is_some())
    }

    /// Check if all positions have the same terrain (useful for fill tiles)
    pub fn is_uniform(&self, position_count: usize) -> Option<usize> {
        let first = self.terrains[0]?;
        for i in 1..position_count {
            if self.terrains[i] != Some(first) {
                return None;
            }
        }
        Some(first)
    }
}

/// Constraints for finding a matching tile (Tiled-style with masks)
#[derive(Debug, Clone, Default)]
pub struct TileConstraints {
    /// Desired terrain at each position
    pub desired: [Option<usize>; 8],
    /// Mask indicating which positions are constrained (true = must match)
    pub mask: [bool; 8],
}

impl TileConstraints {
    pub fn new() -> Self {
        Self {
            desired: [None; 8],
            mask: [false; 8],
        }
    }

    /// Set a constrained terrain at a position
    pub fn set(&mut self, position: usize, terrain_index: usize) {
        if position < 8 {
            self.desired[position] = Some(terrain_index);
            self.mask[position] = true;
        }
    }

    /// Set desired terrain without constraining (soft preference)
    pub fn set_desired(&mut self, position: usize, terrain_index: usize) {
        if position < 8 {
            self.desired[position] = Some(terrain_index);
        }
    }

    /// Check if a position is constrained
    pub fn is_constrained(&self, position: usize) -> bool {
        position < 8 && self.mask[position]
    }

    /// Get the required terrains array (legacy compatibility)
    #[allow(dead_code)]
    pub fn required(&self) -> &[Option<usize>; 8] {
        &self.desired
    }
}

/// A terrain set attached to a tileset
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TerrainSet {
    pub id: Uuid,
    pub name: String,
    /// Which tileset this terrain set belongs to
    pub tileset_id: Uuid,
    /// Type of terrain matching (Corner, Edge, or Mixed)
    pub set_type: TerrainSetType,
    /// List of terrains in this set (e.g., ["Grass", "Dirt", "Water"])
    pub terrains: Vec<Terrain>,
    /// Terrain assignments for each tile (tile_index -> TileTerrainData)
    pub tile_terrains: HashMap<u32, TileTerrainData>,
    /// Per-tile probability weights (default 1.0 if not specified)
    /// Used by WangFiller to bias tile selection toward certain variants
    #[serde(default)]
    pub tile_probabilities: HashMap<u32, f32>,
}

impl TerrainSet {
    pub fn new(name: String, tileset_id: Uuid, set_type: TerrainSetType) -> Self {
        Self {
            id: Uuid::new_v4(),
            name,
            tileset_id,
            set_type,
            terrains: Vec::new(),
            tile_terrains: HashMap::new(),
            tile_probabilities: HashMap::new(),
        }
    }

    /// Add a new terrain to this set
    pub fn add_terrain(&mut self, name: String, color: Color) -> usize {
        let terrain = Terrain::new(name, color);
        self.terrains.push(terrain);
        self.terrains.len() - 1
    }

    /// Remove a terrain by index
    pub fn remove_terrain(&mut self, index: usize) -> Option<Terrain> {
        if index < self.terrains.len() {
            // Update all tile terrain data to remove references to this terrain
            for tile_data in self.tile_terrains.values_mut() {
                for pos in tile_data.terrains.iter_mut() {
                    if let Some(terrain_idx) = pos {
                        if *terrain_idx == index {
                            *pos = None;
                        } else if *terrain_idx > index {
                            *terrain_idx -= 1;
                        }
                    }
                }
            }
            Some(self.terrains.remove(index))
        } else {
            None
        }
    }

    /// Get terrain index by name
    pub fn get_terrain_index(&self, name: &str) -> Option<usize> {
        self.terrains.iter().position(|t| t.name == name)
    }

    /// Set terrain for a tile position
    pub fn set_tile_terrain(
        &mut self,
        tile_index: u32,
        position: usize,
        terrain_index: Option<usize>,
    ) {
        let data = self.tile_terrains.entry(tile_index).or_default();
        data.set(position, terrain_index);
    }

    /// Get tile terrain data
    pub fn get_tile_terrain(&self, tile_index: u32) -> Option<&TileTerrainData> {
        self.tile_terrains.get(&tile_index)
    }

    /// Set the probability weight for a specific tile (used in random selection)
    /// Higher values make the tile more likely to be chosen among equal matches.
    /// Default is 1.0 if not set.
    pub fn set_tile_probability(&mut self, tile_index: u32, probability: f32) {
        if (probability - 1.0).abs() < f32::EPSILON {
            // Remove default value to save space
            self.tile_probabilities.remove(&tile_index);
        } else {
            self.tile_probabilities.insert(tile_index, probability);
        }
    }

    /// Get the probability weight for a specific tile
    /// Returns 1.0 if no custom probability is set
    pub fn get_tile_probability(&self, tile_index: u32) -> f32 {
        self.tile_probabilities
            .get(&tile_index)
            .copied()
            .unwrap_or(1.0)
    }

    /// Find a tile that matches the given constraints (Tiled-style penalty scoring)
    /// Returns the best matching tile, even if not perfect
    pub fn find_matching_tile(&self, constraints: &TileConstraints) -> Option<u32> {
        self.find_best_tile(constraints).map(|(tile, _score)| tile)
    }

    /// Find the best tile match using Tiled-style penalty scoring
    /// Returns (tile_index, penalty_score) where lower score = better match
    /// Returns None only if no tiles have terrain data
    pub fn find_best_tile(&self, constraints: &TileConstraints) -> Option<(u32, f32)> {
        let position_count = self.set_type.position_count();
        let mut best_tile: Option<(u32, f32)> = None;

        for (&tile_index, tile_data) in &self.tile_terrains {
            if !tile_data.has_any_terrain() {
                continue;
            }

            let mut penalty = 0.0f32;
            let mut impossible = false;

            for i in 0..position_count {
                let desired = constraints.desired[i];
                let actual = tile_data.terrains[i];
                let is_constrained = constraints.mask[i];

                match (desired, actual, is_constrained) {
                    // Constrained position: must match exactly
                    (Some(d), Some(a), true) if d != a => {
                        // Hard constraint violation - reject this tile
                        impossible = true;
                        break;
                    }
                    // Constrained position: matches
                    (Some(_), Some(_), true) => {
                        // Perfect match, no penalty
                    }
                    // Constrained but tile has no terrain here
                    (Some(_), None, true) => {
                        impossible = true;
                        break;
                    }
                    // Unconstrained position with preference: score by match
                    (Some(d), Some(a), false) if d != a => {
                        // Soft mismatch - add transition penalty
                        penalty += self.transition_penalty(d, a);
                    }
                    // Unconstrained, no preference or matches
                    _ => {
                        // No penalty
                    }
                }
            }

            if impossible {
                continue;
            }

            // Track the best (lowest penalty) tile
            match best_tile {
                None => best_tile = Some((tile_index, penalty)),
                Some((_, best_penalty)) if penalty < best_penalty => {
                    best_tile = Some((tile_index, penalty));
                }
                _ => {}
            }
        }

        best_tile
    }

    /// Calculate transition penalty between two terrain types
    /// Returns 0 for same terrain, positive for different terrains
    ///
    /// This can be extended in the future to support custom transition costs
    /// for specific terrain pairs (e.g., grass-to-dirt = 1, grass-to-water = 2)
    pub fn transition_penalty(&self, from: usize, to: usize) -> f32 {
        if from == to {
            0.0
        } else {
            // Simple penalty: 1 per mismatch
            // Future: could look up terrain-specific transition costs
            1.0
        }
    }

    /// Find all tiles that have a specific terrain (useful for finding "fill" tiles)
    pub fn find_uniform_tiles(&self, terrain_index: usize) -> Vec<u32> {
        let position_count = self.set_type.position_count();

        self.tile_terrains
            .iter()
            .filter_map(|(&tile_index, tile_data)| {
                if tile_data.is_uniform(position_count) == Some(terrain_index) {
                    Some(tile_index)
                } else {
                    None
                }
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_terrain_set_type_position_count() {
        assert_eq!(TerrainSetType::Corner.position_count(), 4);
        assert_eq!(TerrainSetType::Edge.position_count(), 4);
        assert_eq!(TerrainSetType::Mixed.position_count(), 8);
    }

    #[test]
    fn test_tile_terrain_data() {
        let mut data = TileTerrainData::new();
        assert!(!data.has_any_terrain());

        data.set(0, Some(0));
        assert!(data.has_any_terrain());
        assert_eq!(data.get(0), Some(0));
        assert_eq!(data.get(1), None);
    }

    #[test]
    fn test_terrain_set_find_uniform() {
        let mut set = TerrainSet::new("Test".to_string(), Uuid::new_v4(), TerrainSetType::Corner);

        set.add_terrain("Grass".to_string(), Color::GREEN);

        // Add a uniform tile (all corners = grass)
        let mut tile_data = TileTerrainData::new();
        for i in 0..4 {
            tile_data.set(i, Some(0));
        }
        set.tile_terrains.insert(42, tile_data);

        let uniform_tiles = set.find_uniform_tiles(0);
        assert!(uniform_tiles.contains(&42));
    }
}