Skip to main content

flatland_client_ui/
map_presentation.rs

1//! Map presentation catalogs (`assets/world/terrain-kinds.yaml`, `map-glyphs.yaml`, item templates).
2
3use crate::color::{parse_color, RgbColor};
4
5use std::collections::HashMap;
6use std::path::PathBuf;
7use std::sync::{OnceLock, RwLock};
8
9use flatland_protocol::{NpcView, ResourceNodeState, ResourceNodeView, TerrainKindView};
10use serde::Deserialize;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct MapPresentation {
14    pub glyph: String,
15    pub color: RgbColor,
16}
17
18impl MapPresentation {
19    fn new(glyph: impl Into<String>, color: RgbColor) -> Self {
20        Self {
21            glyph: glyph.into(),
22            color,
23        }
24    }
25}
26
27#[derive(Debug, Default, Deserialize)]
28struct DefaultsYaml {
29    #[serde(default)]
30    resource: Option<GlyphColorYaml>,
31    #[serde(default)]
32    resource_harvesting: Option<GlyphColorYaml>,
33    #[serde(default)]
34    resource_cooldown: Option<GlyphColorYaml>,
35    #[serde(default)]
36    npc_wildlife: Option<GlyphColorYaml>,
37    #[serde(default)]
38    npc_friendly: Option<GlyphColorYaml>,
39    #[serde(default)]
40    player: Option<GlyphColorYaml>,
41    #[serde(default)]
42    corpse: Option<GlyphColorYaml>,
43    #[serde(default)]
44    loot: Option<GlyphColorYaml>,
45    #[serde(default)]
46    chest: Option<GlyphColorYaml>,
47    #[serde(default)]
48    chest_locked: Option<GlyphColorYaml>,
49    #[serde(default)]
50    door_closed: Option<GlyphColorYaml>,
51    #[serde(default)]
52    door_open: Option<GlyphColorYaml>,
53    #[serde(default)]
54    wall: Option<GlyphColorYaml>,
55    #[serde(default)]
56    well_center: Option<GlyphColorYaml>,
57    #[serde(default)]
58    quest_board: Option<GlyphColorYaml>,
59}
60
61#[derive(Debug, Deserialize)]
62struct GlyphColorYaml {
63    glyph: String,
64    color: String,
65}
66
67#[derive(Debug, Deserialize)]
68struct TerrainKindsFile {
69    terrain_kinds: HashMap<String, GlyphColorYaml>,
70}
71
72#[derive(Debug, Deserialize)]
73struct ItemGlyphsFile {
74    items: Vec<ItemGlyphEntry>,
75}
76
77#[derive(Debug, Deserialize)]
78struct ItemGlyphEntry {
79    template_id: String,
80    #[serde(default)]
81    glyph: Option<String>,
82    #[serde(default)]
83    color: Option<String>,
84}
85
86#[derive(Debug, Deserialize)]
87struct MapGlyphsFile {
88    #[serde(default)]
89    defaults: DefaultsYaml,
90    #[serde(default)]
91    npcs: HashMap<String, GlyphColorYaml>,
92    #[serde(default)]
93    entities: HashMap<String, GlyphColorYaml>,
94}
95
96#[derive(Debug)]
97struct Catalog {
98    terrain: HashMap<String, MapPresentation>,
99    defaults: DefaultsBlock,
100    items: HashMap<String, MapPresentation>,
101    npcs: HashMap<String, MapPresentation>,
102    entities: HashMap<String, MapPresentation>,
103}
104
105#[derive(Debug)]
106struct DefaultsBlock {
107    resource: MapPresentation,
108    resource_harvesting: MapPresentation,
109    resource_cooldown: MapPresentation,
110    npc_wildlife: MapPresentation,
111    npc_friendly: MapPresentation,
112    player: MapPresentation,
113    corpse: MapPresentation,
114    loot: MapPresentation,
115    chest: MapPresentation,
116    chest_locked: MapPresentation,
117    door_closed: MapPresentation,
118    door_open: MapPresentation,
119    wall: MapPresentation,
120    well_center: MapPresentation,
121    quest_board: MapPresentation,
122}
123
124fn find_assets_path(relative: &str) -> PathBuf {
125    if let Ok(root) = std::env::var("FLATLAND_ASSETS") {
126        let candidate = PathBuf::from(root).join(relative.strip_prefix("assets/").unwrap_or(relative));
127        if candidate.is_file() {
128            return candidate;
129        }
130    }
131    // Synced client bundle: presentation YAML under rev-N/presentation/.
132    if let Some(file) = relative.strip_prefix("assets/world/") {
133        if let Ok(home) = std::env::var("HOME") {
134            let candidate = PathBuf::from(home)
135                .join(".flatland3/assets/current/presentation")
136                .join(file);
137            if candidate.is_file() {
138                return candidate;
139            }
140        }
141    }
142    let mut dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
143    for _ in 0..8 {
144        let candidate = dir.join(relative);
145        if candidate.is_file() {
146            return candidate;
147        }
148        if !dir.pop() {
149            break;
150        }
151    }
152    let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
153    for ancestor in manifest.ancestors() {
154        let candidate = ancestor.join(relative);
155        if candidate.is_file() {
156            return candidate;
157        }
158    }
159    PathBuf::from(relative)
160}
161
162fn find_assets_dir(relative: &str) -> PathBuf {
163    if let Ok(root) = std::env::var("FLATLAND_ASSETS") {
164        let candidate = PathBuf::from(root).join(relative.strip_prefix("assets/").unwrap_or(relative));
165        if candidate.is_dir() {
166            return candidate;
167        }
168    }
169    let mut dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
170    for _ in 0..8 {
171        let candidate = dir.join(relative);
172        if candidate.is_dir() {
173            return candidate;
174        }
175        if !dir.pop() {
176            break;
177        }
178    }
179    let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
180    for ancestor in manifest.ancestors() {
181        let candidate = ancestor.join(relative);
182        if candidate.is_dir() {
183            return candidate;
184        }
185    }
186    PathBuf::from(relative)
187}
188
189fn parse_entry(def: &GlyphColorYaml) -> Option<MapPresentation> {
190    if def.glyph.is_empty() {
191        return None;
192    }
193    let color = parse_color(&def.color)?;
194    Some(MapPresentation::new(def.glyph.clone(), color))
195}
196
197fn parse_map(defs: HashMap<String, GlyphColorYaml>) -> HashMap<String, MapPresentation> {
198    defs.into_iter()
199        .filter_map(|(k, v)| parse_entry(&v).map(|p| (k, p)))
200        .collect()
201}
202
203fn builtin_defaults() -> DefaultsBlock {
204    DefaultsBlock {
205        resource: MapPresentation::new("?", RgbColor::DARK_GRAY),
206        resource_harvesting: MapPresentation::new("%", RgbColor::YELLOW),
207        resource_cooldown: MapPresentation::new("·", RgbColor::DARK_GRAY),
208        npc_wildlife: MapPresentation::new("N", RgbColor::YELLOW),
209        npc_friendly: MapPresentation::new("N", RgbColor::CYAN),
210        player: MapPresentation::new("@", RgbColor::GREEN),
211        corpse: MapPresentation::new("x", RgbColor::DARK_GRAY),
212        loot: MapPresentation::new("*", RgbColor::YELLOW),
213        chest: MapPresentation::new("■", RgbColor::rgb(139, 90, 43)),
214        chest_locked: MapPresentation::new("▣", RgbColor::rgb(160, 82, 45)),
215        door_closed: MapPresentation::new("D", RgbColor::RED),
216        door_open: MapPresentation::new("d", RgbColor::LIGHT_RED),
217        wall: MapPresentation::new("+", RgbColor::MAGENTA),
218        well_center: MapPresentation::new("O", RgbColor::CYAN),
219        quest_board: MapPresentation::new("!", RgbColor::rgb(0xe8, 0xc5, 0x47)),
220    }
221}
222
223fn merge_default(yaml: Option<GlyphColorYaml>, fallback: &MapPresentation) -> MapPresentation {
224    yaml.and_then(|d| parse_entry(&d))
225        .unwrap_or_else(|| fallback.clone())
226}
227
228fn builtin_terrain(kind: TerrainKindView) -> MapPresentation {
229    match kind {
230        TerrainKindView::Grass => MapPresentation::new(".", RgbColor::rgb(0x5a, 0x73, 0x56)),
231        TerrainKindView::Dirt => MapPresentation::new(".", RgbColor::rgb(0x8a, 0x70, 0x4a)),
232        TerrainKindView::Tilled => MapPresentation::new("=", RgbColor::rgb(0x6e, 0x58, 0x38)),
233        TerrainKindView::Desert => MapPresentation::new(".", RgbColor::rgb(0xd4, 0xc0, 0x7a)),
234        TerrainKindView::Hill => MapPresentation::new("^", RgbColor::rgb(0x9a, 0x92, 0x68)),
235        TerrainKindView::Trail => MapPresentation::new(":", RgbColor::rgb(0xc4, 0xb8, 0x90)),
236        TerrainKindView::Road => MapPresentation::new("=", RgbColor::rgb(0xb0, 0xa0, 0x78)),
237        TerrainKindView::Rock => MapPresentation::new("#", RgbColor::rgb(0x5a, 0x50, 0x48)),
238        TerrainKindView::Bog => MapPresentation::new(",", RgbColor::MAGENTA),
239        TerrainKindView::ShallowWater => MapPresentation::new("~", RgbColor::CYAN),
240        TerrainKindView::DeepWater => MapPresentation::new("~", RgbColor::BLUE),
241    }
242}
243
244fn terrain_key(kind: TerrainKindView) -> &'static str {
245    match kind {
246        TerrainKindView::Grass => "grass",
247        TerrainKindView::Dirt => "dirt",
248        TerrainKindView::Tilled => "tilled",
249        TerrainKindView::Desert => "desert",
250        TerrainKindView::Hill => "hill",
251        TerrainKindView::Trail => "trail",
252        TerrainKindView::Road => "road",
253        TerrainKindView::Rock => "rock",
254        TerrainKindView::Bog => "bog",
255        TerrainKindView::ShallowWater => "shallow_water",
256        TerrainKindView::DeepWater => "deep_water",
257    }
258}
259
260/// Ground elevation → hue ladder (low cool green → mid olive → high warm tan → snow).
261fn elevation_palette(elevation: f32) -> RgbColor {
262    let bucket = elevation.round().clamp(-3.0, 8.0) as i32;
263    match bucket {
264        b if b <= -1 => RgbColor::rgb(0x3d, 0x58, 0x6a), // below grade — cool slate
265        0 => RgbColor::rgb(0x4a, 0x6b, 0x42),            // lowland green
266        1 => RgbColor::rgb(0x62, 0x7a, 0x48),            // foothill
267        2 => RgbColor::rgb(0x7a, 0x86, 0x4c),            // slope olive
268        3 => RgbColor::rgb(0x96, 0x8a, 0x58),            // upper slope tan-green
269        4 => RgbColor::rgb(0xae, 0x8c, 0x62),            // ridge / plateau
270        5 => RgbColor::rgb(0xc8, 0xa4, 0x72),            // high scree
271        6 => RgbColor::rgb(0xde, 0xc0, 0x90),            // near summit
272        _ => RgbColor::rgb(0xec, 0xea, 0xf4),            // snow cap
273    }
274}
275
276fn darken_rgb(color: RgbColor, factor: f32) -> RgbColor {
277    RgbColor::rgb(
278        (color.r as f32 * factor) as u8,
279        (color.g as f32 * factor) as u8,
280        (color.b as f32 * factor) as u8,
281    )
282}
283
284fn lighten_rgb(color: RgbColor, factor: f32) -> RgbColor {
285    RgbColor::rgb(
286        ((color.r as f32 * factor).min(255.0)) as u8,
287        ((color.g as f32 * factor).min(255.0)) as u8,
288        ((color.b as f32 * factor).min(255.0)) as u8,
289    )
290}
291
292fn load_item_presentations() -> HashMap<String, MapPresentation> {
293    let path = find_assets_dir("assets/items");
294    let Ok(entries) = std::fs::read_dir(&path) else {
295        return HashMap::new();
296    };
297    let fallback = RgbColor::rgb(0x8a, 0x8a, 0x8a);
298    let mut out = HashMap::new();
299    let mut files: Vec<PathBuf> = entries
300        .filter_map(|e| e.ok())
301        .map(|e| e.path())
302        .filter(|p| {
303            p.is_file()
304                && p.extension()
305                    .is_some_and(|ext| ext == "yaml" || ext == "yml")
306        })
307        .collect();
308    files.sort();
309    for file in files {
310        let Ok(raw) = std::fs::read_to_string(&file) else {
311            continue;
312        };
313        let Ok(root) = serde_yaml::from_str::<ItemGlyphsFile>(&raw) else {
314            continue;
315        };
316        for item in root.items {
317            let Some(glyph) = item.glyph else {
318                continue;
319            };
320            let color = item
321                .color
322                .as_deref()
323                .and_then(parse_color)
324                .unwrap_or(fallback);
325            out.insert(item.template_id, MapPresentation::new(glyph, color));
326        }
327    }
328    out
329}
330
331fn load_catalog() -> Catalog {
332    let mut terrain = HashMap::new();
333    if let Ok(raw) = std::fs::read_to_string(find_assets_path("assets/world/terrain-kinds.yaml")) {
334        if let Ok(file) = serde_yaml::from_str::<TerrainKindsFile>(&raw) {
335            terrain = parse_map(file.terrain_kinds);
336        }
337    }
338
339    let mut defaults = builtin_defaults();
340    let items = load_item_presentations();
341    let mut npcs = HashMap::new();
342    let mut entities = HashMap::new();
343
344    if let Ok(raw) = std::fs::read_to_string(find_assets_path("assets/world/map-glyphs.yaml")) {
345        if let Ok(file) = serde_yaml::from_str::<MapGlyphsFile>(&raw) {
346            let base = builtin_defaults();
347            defaults = DefaultsBlock {
348                resource: merge_default(file.defaults.resource, &base.resource),
349                resource_harvesting: merge_default(
350                    file.defaults.resource_harvesting,
351                    &base.resource_harvesting,
352                ),
353                resource_cooldown: merge_default(
354                    file.defaults.resource_cooldown,
355                    &base.resource_cooldown,
356                ),
357                npc_wildlife: merge_default(file.defaults.npc_wildlife, &base.npc_wildlife),
358                npc_friendly: merge_default(file.defaults.npc_friendly, &base.npc_friendly),
359                player: merge_default(file.defaults.player, &base.player),
360                corpse: merge_default(file.defaults.corpse, &base.corpse),
361                loot: merge_default(file.defaults.loot, &base.loot),
362                chest: merge_default(file.defaults.chest, &base.chest),
363                chest_locked: merge_default(file.defaults.chest_locked, &base.chest_locked),
364                door_closed: merge_default(file.defaults.door_closed, &base.door_closed),
365                door_open: merge_default(file.defaults.door_open, &base.door_open),
366                wall: merge_default(file.defaults.wall, &base.wall),
367                well_center: merge_default(file.defaults.well_center, &base.well_center),
368                quest_board: merge_default(file.defaults.quest_board, &base.quest_board),
369            };
370            npcs = parse_map(file.npcs);
371            entities = parse_map(file.entities);
372        }
373    }
374
375    Catalog {
376        terrain,
377        defaults,
378        items,
379        npcs,
380        entities,
381    }
382}
383
384fn catalog_cell() -> &'static RwLock<Catalog> {
385    static CELL: OnceLock<RwLock<Catalog>> = OnceLock::new();
386    CELL.get_or_init(|| RwLock::new(load_catalog()))
387}
388
389fn catalog() -> std::sync::RwLockReadGuard<'static, Catalog> {
390    catalog_cell()
391        .read()
392        .expect("map presentation catalog lock")
393}
394
395/// Reload `terrain-kinds.yaml`, `map-glyphs.yaml`, and item glyphs from disk.
396pub fn reload_map_presentation_catalog() {
397    *catalog_cell()
398        .write()
399        .expect("map presentation catalog lock") = load_catalog();
400}
401
402/// Reload presentation YAML when the sim reports a newer content revision (after publish).
403pub fn maybe_reload_for_content_rev(content_rev: u64) {
404    static LAST_REV: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
405    let prev = LAST_REV.load(std::sync::atomic::Ordering::Relaxed);
406    if content_rev > 0 && content_rev != prev {
407        LAST_REV.store(content_rev, std::sync::atomic::Ordering::Relaxed);
408        reload_map_presentation_catalog();
409    }
410}
411
412fn npc_glyph_lookup(c: &Catalog, npc: &NpcView) -> Option<MapPresentation> {
413    let id_key = npc.id.to_ascii_lowercase();
414    if let Some(p) = c.npcs.get(&id_key) {
415        return Some(p.clone());
416    }
417    if let Some(prefix) = id_key.split('_').next() {
418        if let Some(p) = c.npcs.get(prefix) {
419            return Some(p.clone());
420        }
421    }
422    let label_key = npc.label.to_ascii_lowercase();
423    c.npcs.get(&label_key).cloned()
424}
425
426pub fn terrain_for(kind: TerrainKindView) -> MapPresentation {
427    catalog()
428        .terrain
429        .get(terrain_key(kind))
430        .cloned()
431        .unwrap_or_else(|| builtin_terrain(kind))
432}
433
434/// Terrain glyph + color from zone kind and ground elevation (topographic read).
435pub fn terrain_for_elevation(kind: TerrainKindView, elevation: f32) -> MapPresentation {
436    match kind {
437        TerrainKindView::ShallowWater | TerrainKindView::DeepWater | TerrainKindView::Bog => {
438            return terrain_for(kind);
439        }
440        TerrainKindView::Trail => {
441            let color = lighten_rgb(elevation_palette(elevation), 1.12);
442            return MapPresentation::new(":", color);
443        }
444        TerrainKindView::Road => {
445            let color = lighten_rgb(elevation_palette(elevation), 1.22);
446            return MapPresentation::new("=", color);
447        }
448        TerrainKindView::Rock => {
449            let color = darken_rgb(elevation_palette(elevation), 0.62);
450            let glyph = if elevation >= 3.5 { "▓" } else { "#" };
451            return MapPresentation::new(glyph, color);
452        }
453        _ => {}
454    }
455
456    let base = terrain_for(kind);
457    let color = elevation_palette(elevation);
458    if elevation.abs() < 0.25 {
459        return MapPresentation::new(base.glyph, color);
460    }
461
462    let bucket = elevation.round().clamp(-9.0, 9.0) as i32;
463    let ch = match bucket {
464        b if b >= 6 => '▲',
465        b if b >= 4 => '▲',
466        b if b >= 2 => '^',
467        b if b >= 1 => '▴',
468        b if b <= -1 => '▾',
469        _ => base.glyph.chars().next().unwrap_or('.'),
470    };
471    MapPresentation::new(ch.to_string(), color)
472}
473
474/// Terrain presentation for a zone cell, applying optional per-zone glyph/color overrides from YAML.
475pub fn terrain_for_zone(
476    kind: TerrainKindView,
477    elevation: f32,
478    glyph_override: Option<&str>,
479    color_override: Option<&str>,
480) -> MapPresentation {
481    let mut pres = terrain_for_elevation(kind, elevation);
482    if let Some(g) = glyph_override.map(str::trim).filter(|s| !s.is_empty()) {
483        let ch = g.chars().next().unwrap_or('.');
484        pres.glyph = ch.to_string();
485    }
486    if let Some(raw) = color_override.map(str::trim).filter(|s| !s.is_empty()) {
487        if let Some(color) = parse_color(raw) {
488            pres.color = color;
489        }
490    }
491    pres
492}
493
494pub fn resource_for(node: &ResourceNodeView) -> MapPresentation {
495    let c = catalog();
496    match node.state {
497        ResourceNodeState::Harvesting => c.defaults.resource_harvesting.clone(),
498        ResourceNodeState::Cooldown => c.defaults.resource_cooldown.clone(),
499        ResourceNodeState::Available => c
500            .items
501            .get(&node.item_template)
502            .cloned()
503            .unwrap_or_else(|| c.defaults.resource.clone()),
504    }
505}
506
507pub fn npc_for(npc: &NpcView) -> MapPresentation {
508    let c = catalog();
509    if let Some(p) = npc_glyph_lookup(&c, npc) {
510        return p;
511    }
512    if npc.entity_id.is_some() {
513        return c.defaults.npc_wildlife.clone();
514    }
515    c.defaults.npc_friendly.clone()
516}
517
518pub fn player_presentation() -> MapPresentation {
519    catalog().defaults.player.clone()
520}
521
522pub fn corpse_presentation() -> MapPresentation {
523    catalog().defaults.corpse.clone()
524}
525
526pub fn loot_presentation() -> MapPresentation {
527    catalog().defaults.loot.clone()
528}
529
530pub fn chest_presentation(locked: bool) -> MapPresentation {
531    let c = catalog();
532    if locked {
533        c.defaults.chest_locked.clone()
534    } else {
535        c.defaults.chest.clone()
536    }
537}
538
539pub fn door_presentation(open: bool) -> MapPresentation {
540    let c = catalog();
541    if open {
542        c.defaults.door_open.clone()
543    } else {
544        c.defaults.door_closed.clone()
545    }
546}
547
548pub fn wall_presentation() -> MapPresentation {
549    catalog().defaults.wall.clone()
550}
551
552pub fn well_center_presentation() -> MapPresentation {
553    catalog().defaults.well_center.clone()
554}
555
556pub fn quest_board_presentation() -> MapPresentation {
557    catalog().defaults.quest_board.clone()
558}
559
560pub fn shallow_water_presentation() -> MapPresentation {
561    terrain_for(TerrainKindView::ShallowWater)
562}
563
564pub fn entity_fallback(label: &str) -> MapPresentation {
565    let c = catalog();
566    let initial = label
567        .chars()
568        .next()
569        .map(|ch| ch.to_ascii_uppercase().to_string())
570        .unwrap_or_else(|| "?".into());
571    if let Some(mut p) = c.entities.get("wildlife_other").cloned() {
572        p.glyph = initial.clone();
573        return p;
574    }
575    MapPresentation::new(initial, RgbColor::YELLOW)
576}
577
578/// One row in the `?` help map legend (glyphs from YAML catalogs).
579#[derive(Debug, Clone)]
580pub struct MapLegendEntry {
581    pub presentation: MapPresentation,
582    pub label: String,
583}
584
585fn legend_push(out: &mut Vec<MapLegendEntry>, pres: &MapPresentation, label: impl Into<String>) {
586    out.push(MapLegendEntry {
587        presentation: pres.clone(),
588        label: label.into(),
589    });
590}
591
592/// Map legend rows for help overlay and `flatland3 keys`.
593pub fn map_legend_entries() -> Vec<MapLegendEntry> {
594    let c = catalog();
595    let mut out = Vec::new();
596
597    legend_push(&mut out, &c.defaults.player, "you");
598    legend_push(&mut out, &c.defaults.loot, "ground loot");
599    legend_push(&mut out, &c.defaults.corpse, "carcass");
600    legend_push(&mut out, &c.defaults.door_closed, "door (closed)");
601    legend_push(&mut out, &c.defaults.door_open, "door (open)");
602    legend_push(&mut out, &c.defaults.wall, "wall");
603    legend_push(&mut out, &c.defaults.well_center, "well");
604    legend_push(&mut out, &c.defaults.resource_harvesting, "harvesting node");
605    legend_push(&mut out, &c.defaults.resource_cooldown, "node cooldown");
606
607    let mut terrain: Vec<_> = c.terrain.iter().collect();
608    terrain.sort_by_key(|(k, _)| *k);
609    if terrain.is_empty() {
610        for kind in [
611            TerrainKindView::Grass,
612            TerrainKindView::Dirt,
613            TerrainKindView::Tilled,
614            TerrainKindView::Desert,
615            TerrainKindView::Hill,
616            TerrainKindView::Trail,
617            TerrainKindView::Road,
618            TerrainKindView::Rock,
619            TerrainKindView::Bog,
620            TerrainKindView::ShallowWater,
621            TerrainKindView::DeepWater,
622        ] {
623            let pres = terrain_for(kind);
624            legend_push(&mut out, &pres, terrain_key(kind).replace('_', " "));
625        }
626    } else {
627        for (kind, pres) in terrain {
628            legend_push(&mut out, pres, kind.replace('_', " "));
629        }
630    }
631
632    let mut npcs: Vec<_> = c.npcs.iter().collect();
633    npcs.sort_by_key(|(k, _)| *k);
634    for (id, pres) in npcs {
635        legend_push(&mut out, pres, format!("{id}"));
636    }
637
638    let mut items: Vec<_> = c.items.iter().collect();
639    items.sort_by_key(|(k, _)| *k);
640    for (id, pres) in items {
641        legend_push(&mut out, pres, id.replace('_', " "));
642    }
643
644    out
645}
646
647pub fn format_map_legend_plain() -> String {
648    let mut out = String::from("Map legend\n");
649    for entry in map_legend_entries() {
650        out.push_str(&format!(
651            "  {}  {}\n",
652            entry.presentation.glyph, entry.label
653        ));
654    }
655    out.push_str("  [red cell]  T1 combat target\n");
656    out.push_str("  [blue cell]  T2 combat target\n");
657    out
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663
664    #[test]
665    fn parses_named_and_hex_colors() {
666        assert_eq!(parse_color("cyan"), Some(RgbColor::CYAN));
667        assert_eq!(parse_color("#0af"), Some(RgbColor::rgb(0x00, 0xaa, 0xff)));
668    }
669
670    #[test]
671    fn terrain_and_resource_catalog_load() {
672        let oak = resource_for(&ResourceNodeView {
673            id: "t".into(),
674            label: "Oak".into(),
675            x: 0.0,
676            y: 0.0,
677            z: 0.0,
678            item_template: "oak_log".into(),
679            state: ResourceNodeState::Available,
680            blocking: false,
681            blocking_radius_m: 0.8,
682            tile_id: None,
683            paperdoll_ref: None,
684            yaw: 0.0,
685            pitch: 0.0,
686            roll: 0.0,
687            draw_scale: 1.0,
688            sprite_mode: None,
689            presentation_state: None,
690        });
691        assert_eq!(oak.glyph, "?");
692
693        let rabbit = npc_for(&NpcView {
694            id: "r1".into(),
695            label: "Rabbit".into(),
696            role: "critter".into(),
697            x: 0.0,
698            y: 0.0,
699            building_id: None,
700            entity_id: Some(2),
701            life_state: None,
702            hp_pct: None,
703            can_trade: false,
704            tile_id: None,
705            behavior_state: None,
706            sprite_mode: None,
707            presentation_state: None,
708            paperdoll_ref: None,
709        });
710        assert_eq!(rabbit.glyph, "N");
711
712        let jack = npc_for(&NpcView {
713            id: "jack_wanderer".into(),
714            label: "Jack".into(),
715            role: "villager".into(),
716            x: 0.0,
717            y: 0.0,
718            building_id: None,
719            entity_id: None,
720            life_state: None,
721            hp_pct: None,
722            can_trade: false,
723            tile_id: None,
724            behavior_state: None,
725            sprite_mode: None,
726            presentation_state: None,
727            paperdoll_ref: None,
728        });
729        assert_eq!(jack.glyph, "N");
730        assert_eq!(jack.color, parse_color("cyan").expect("cyan"));
731    }
732
733    #[test]
734    fn trail_and_rock_use_distinct_glyphs_with_elevation_tint() {
735        let trail = terrain_for_elevation(TerrainKindView::Trail, 2.0);
736        assert_eq!(trail.glyph, ":");
737        let rock = terrain_for_elevation(TerrainKindView::Rock, 4.0);
738        assert_eq!(rock.glyph, "▓");
739        let low = terrain_for_elevation(TerrainKindView::Grass, 0.0);
740        let high = terrain_for_elevation(TerrainKindView::Grass, 4.0);
741        assert_ne!(low.color, high.color);
742    }
743
744    #[test]
745    fn terrain_for_zone_applies_glyph_and_color_overrides() {
746        let base = terrain_for_elevation(TerrainKindView::Grass, 0.0);
747        let custom = terrain_for_zone(TerrainKindView::Grass, 0.0, Some("%"), Some("blue"));
748        assert_eq!(custom.glyph, "%");
749        assert_eq!(custom.color, parse_color("blue").expect("blue"));
750        assert_ne!(custom.glyph, base.glyph);
751        assert_ne!(custom.color, base.color);
752    }
753}