flatland-client-ui 0.2.7

Engine-agnostic play client UI state (world grid, input, presentation)
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
use crate::color::RgbColor;
use flatland_client_lib::GameState;
use flatland_protocol::{BuildingView, InteriorMapView, TerrainKindView};

use crate::map_presentation::{self, MapPresentation};

/// The TUI map uses one terminal cell per world meter on both axes so terrain, entities,
/// resources, and mouse targeting share the same grid. Terminal fonts are taller than wide,
/// so buildings look vertically stretched compared to the content-admin editor.

pub struct WorldView {
    pub width: usize,
    pub height: usize,
    pub cells: Vec<String>,
    /// Per-cell foreground color from presentation catalog (None = entity-specific style).
    pub cell_fg: Vec<Option<RgbColor>>,
    /// T1 target ring (red).
    pub target_t1_cells: Vec<bool>,
    /// T2 target ring (blue).
    pub target_t2_cells: Vec<bool>,
    pub origin_x: f32,
    pub origin_y: f32,
    pub inside_building: Option<String>,
}

/// Presentation flags for [`WorldView::build_with_options`].
#[derive(Debug, Clone, Copy)]
pub struct WorldViewOptions {
    /// Paint local player `@` at view center (TUI). Gfx uses a sprite instead.
    pub paint_local_player: bool,
    /// Paint NPCs, resources, loot, chests, quest boards, entities into the cell grid.
    /// Gfx sets this false and draws those at continuous world coordinates.
    pub paint_overlays: bool,
}

impl Default for WorldViewOptions {
    fn default() -> Self {
        Self {
            paint_local_player: true,
            paint_overlays: true,
        }
    }
}

impl WorldViewOptions {
    /// Terrain / walls only — gfx draws movers at precise x,y.
    pub fn terrain_only() -> Self {
        Self {
            paint_local_player: false,
            paint_overlays: false,
        }
    }
}

impl WorldView {
    pub fn build_with_target(
        state: &GameState,
        view_w: usize,
        view_h: usize,
        map_target: Option<(f32, f32)>,
    ) -> Self {
        Self::build_with_options(
            state,
            view_w,
            view_h,
            map_target,
            WorldViewOptions::default(),
        )
    }

    /// Like [`build_with_target`] with gfx/TUI presentation flags.
    pub fn build_with_options(
        state: &GameState,
        view_w: usize,
        view_h: usize,
        map_target: Option<(f32, f32)>,
        options: WorldViewOptions,
    ) -> Self {
        let (px, py) = state.player_position();
        Self::build_with_anchor(state, view_w, view_h, px, py, map_target, options)
    }

    /// Build a view anchored at explicit world coordinates (gfx uses smoothed camera).
    pub fn build_with_anchor(
        state: &GameState,
        view_w: usize,
        view_h: usize,
        anchor_x: f32,
        anchor_y: f32,
        map_target: Option<(f32, f32)>,
        options: WorldViewOptions,
    ) -> Self {
        map_presentation::maybe_reload_for_content_rev(state.content_rev);
        let px = anchor_x;
        let py = anchor_y;
        let inside_building = state.effective_inside_building();

        let width = view_w.max(3);
        let height = view_h.max(3);
        let grass = map_presentation::terrain_for(TerrainKindView::Grass);
        let mut cells = vec![grass.glyph.clone(); width * height];
        let mut cell_fg = vec![Some(grass.color); width * height];

        let half_w = (width / 2) as i32;
        let half_h = (height / 2) as i32;

        // Interior rendering is authoritative from `inside_building`, not stale `interior_map`.
        if let (Some(_bid), Some(interior)) =
            (inside_building.as_deref(), state.interior_map.as_ref())
        {
            paint_interior_background(&mut cells, &mut cell_fg, width, height, interior);
            paint_interior_rooms(
                &mut cells,
                &mut cell_fg,
                width,
                height,
                interior,
                px,
                py,
                half_w,
                half_h,
            );
            let door_gaps = interior_door_gaps(interior, &state.doors);
            for room in &interior.rooms {
                paint_building_walls(
                    &mut cells,
                    &mut cell_fg,
                    width,
                    height,
                    room.x0,
                    room.y0,
                    room.x1 - room.x0,
                    room.y1 - room.y0,
                    px,
                    py,
                    half_w,
                    half_h,
                    &door_gaps,
                );
            }
        } else {
            paint_terrain(
                &mut cells,
                &mut cell_fg,
                width,
                height,
                state,
                px,
                py,
                half_w,
                half_h,
            );

            for building in &state.buildings {
                if building.tags.iter().any(|t| t == "well") {
                    paint_well(
                        &mut cells,
                        &mut cell_fg,
                        width,
                        height,
                        building,
                        px,
                        py,
                        half_w,
                        half_h,
                    );
                } else {
                    paint_building_walls_centered(
                        &mut cells,
                        &mut cell_fg,
                        width,
                        height,
                        building,
                        px,
                        py,
                        half_w,
                        half_h,
                    );
                }
            }
        }

        if options.paint_overlays {
            for door in &state.doors {
                if let Some((gx, gy)) =
                    world_to_grid(door.x, door.y, px, py, half_w, half_h, width, height)
                {
                    let idx = gy * width + gx;
                    paint_presentation(
                        &mut cells,
                        &mut cell_fg,
                        idx,
                        &map_presentation::door_presentation(door.open),
                    );
                }
            }

            for npc in &state.npcs {
                if let Some((gx, gy)) =
                    world_to_grid(npc.x, npc.y, px, py, half_w, half_h, width, height)
                {
                    let idx = gy * width + gx;
                    paint_presentation(
                        &mut cells,
                        &mut cell_fg,
                        idx,
                        &map_presentation::npc_for(npc),
                    );
                }
            }

            let ground = empty_ground_glyph();
            let player_glyph = map_presentation::player_presentation().glyph;
            for node in &state.resource_nodes {
                if let Some((gx, gy)) =
                    world_to_grid(node.x, node.y, px, py, half_w, half_h, width, height)
                {
                    let idx = gy * width + gx;
                    let pres = map_presentation::resource_for(node);
                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
                        paint_presentation(&mut cells, &mut cell_fg, idx, &pres);
                    }
                }
            }

            for drop in &state.ground_drops {
                if let Some((gx, gy)) =
                    world_to_grid(drop.x, drop.y, px, py, half_w, half_h, width, height)
                {
                    let idx = gy * width + gx;
                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
                        paint_presentation(
                            &mut cells,
                            &mut cell_fg,
                            idx,
                            &map_presentation::loot_presentation(),
                        );
                    }
                }
            }

            for chest in &state.placed_containers {
                if let Some((gx, gy)) =
                    world_to_grid(chest.x, chest.y, px, py, half_w, half_h, width, height)
                {
                    let idx = gy * width + gx;
                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
                        paint_presentation(
                            &mut cells,
                            &mut cell_fg,
                            idx,
                            &map_presentation::chest_presentation(chest.locked),
                        );
                    }
                }
            }

            if state.effective_inside_building().is_none() {
                for inter in &state.interactables {
                    if inter.kind != "quest_board" {
                        continue;
                    }
                    if let Some((gx, gy)) =
                        world_to_grid(inter.x, inter.y, px, py, half_w, half_h, width, height)
                    {
                        let idx = gy * width + gx;
                        if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
                            paint_presentation(
                                &mut cells,
                                &mut cell_fg,
                                idx,
                                &map_presentation::quest_board_presentation(),
                            );
                        }
                    }
                }
            }

            for entity in &state.entities {
                // When gfx draws a sprite for the local player, omit the `@` glyph.
                if !options.paint_local_player && entity.id == state.entity_id {
                    continue;
                }
                if let Some(pres) = entity_presentation(entity, state.entity_id) {
                    if let Some((gx, gy)) = world_to_grid(
                        entity.transform.position.x,
                        entity.transform.position.y,
                        px,
                        py,
                        half_w,
                        half_h,
                        width,
                        height,
                    ) {
                        let idx = gy * width + gx;
                        paint_presentation(&mut cells, &mut cell_fg, idx, &pres);
                    }
                }
            }
        }

        if options.paint_local_player {
            if state.player_entity().is_some() {
                let cx = half_w as usize;
                let cy = half_h as usize;
                let idx = cy * width + cx;
                if idx < cells.len() {
                    paint_presentation(
                        &mut cells,
                        &mut cell_fg,
                        idx,
                        &map_presentation::player_presentation(),
                    );
                }
            }
        }

        let mut target_t1_cells = vec![false; cells.len()];
        let mut target_t2_cells = vec![false; cells.len()];
        if options.paint_overlays {
            for (slot, cells_out) in [(1, &mut target_t1_cells), (2, &mut target_t2_cells)] {
                let target_id = state
                    .combat_slots
                    .iter()
                    .find(|s| s.slot_index == slot)
                    .and_then(|s| s.target_entity_id)
                    .or_else(|| if slot == 1 { state.combat_target } else { None });
                let Some(target_id) = target_id else {
                    continue;
                };
                if let Some(entity) = state.entities.iter().find(|e| e.id == target_id) {
                    if let Some((gx, gy)) = world_to_grid(
                        entity.transform.position.x,
                        entity.transform.position.y,
                        px,
                        py,
                        half_w,
                        half_h,
                        width,
                        height,
                    ) {
                        let idx = gy * width + gx;
                        if idx < cells_out.len() {
                            cells_out[idx] = true;
                        }
                    }
                }
            }
        }

        if options.paint_overlays {
            if let Some((tx, ty)) = map_target {
                if let Some((gx, gy)) = world_to_grid(tx, ty, px, py, half_w, half_h, width, height)
                {
                    let idx = gy * width + gx;
                    if idx < cells.len() {
                        cells[idx] = "X".into();
                        cell_fg[idx] = Some(RgbColor::YELLOW);
                    }
                }
            }
        }

        Self {
            width,
            height,
            cells,
            cell_fg,
            target_t1_cells,
            target_t2_cells,
            origin_x: px,
            origin_y: py,
            inside_building,
        }
    }
}

fn paint_presentation(
    cells: &mut [String],
    cell_fg: &mut [Option<RgbColor>],
    idx: usize,
    pres: &MapPresentation,
) {
    cells[idx] = pres.glyph.clone();
    cell_fg[idx] = Some(pres.color);
}

fn empty_ground_glyph() -> String {
    map_presentation::terrain_for(TerrainKindView::Grass).glyph
}

fn entity_presentation(
    entity: &flatland_protocol::EntityState,
    player_id: u64,
) -> Option<MapPresentation> {
    if entity.id == player_id {
        return Some(map_presentation::player_presentation());
    }
    if entity
        .vitals
        .as_ref()
        .is_some_and(|v| v.life_state == flatland_protocol::LifeState::Dead)
    {
        return Some(map_presentation::corpse_presentation());
    }
    Some(map_presentation::entity_fallback(&entity.label))
}

fn paint_interior_background(
    cells: &mut [String],
    cell_fg: &mut [Option<RgbColor>],
    _width: usize,
    _height: usize,
    interior: &InteriorMapView,
) {
    let bg = crate::color::parse_color(&interior.background_color).unwrap_or(RgbColor::BLACK);
    for idx in 0..cells.len() {
        cells[idx] = " ".into();
        cell_fg[idx] = Some(bg);
    }
}

fn paint_interior_rooms(
    cells: &mut [String],
    cell_fg: &mut [Option<RgbColor>],
    width: usize,
    height: usize,
    interior: &InteriorMapView,
    px: f32,
    py: f32,
    half_w: i32,
    half_h: i32,
) {
    let default_color = interior
        .default_floor_color
        .as_deref()
        .and_then(crate::color::parse_color)
        .unwrap_or(RgbColor::rgb(0x2a, 0x2a, 0x2a));
    for room in &interior.rooms {
        let floor_color = room
            .floor_color
            .as_deref()
            .and_then(crate::color::parse_color)
            .unwrap_or(default_color);
        let glyph = room.floor_glyph.as_deref().unwrap_or(".").to_string();
        let x0 = room.x0.floor() as i32;
        let y0 = room.y0.floor() as i32;
        let x1 = room.x1.ceil() as i32 - 1;
        let y1 = room.y1.ceil() as i32 - 1;
        for wy in y0..=y1 {
            for wx in x0..=x1 {
                if let Some((gx, gy)) =
                    world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
                {
                    let idx = gy * width + gx;
                    cells[idx] = glyph.clone();
                    cell_fg[idx] = Some(floor_color);
                }
            }
        }
    }
}

fn interior_door_gaps(
    interior: &InteriorMapView,
    doors: &[flatland_protocol::DoorView],
) -> Vec<(f32, f32)> {
    let mut gaps: Vec<(f32, f32)> = interior
        .room_doors
        .iter()
        .filter_map(|d| {
            doors
                .iter()
                .find(|door| door.id == d.id)
                .filter(|door| door.open)
                .map(|door| (door.x, door.y))
        })
        .collect();
    for door in doors {
        if door.portal.is_some() && door.open {
            gaps.push((door.x, door.y));
        }
    }
    gaps
}

fn near_door_gap(wx: i32, wy: i32, door_gaps: &[(f32, f32)]) -> bool {
    door_gaps
        .iter()
        .any(|(dx, dy)| (wx as f32 - dx).abs() < 0.75 && (wy as f32 - dy).abs() < 0.75)
}

fn paint_terrain(
    cells: &mut [String],
    cell_fg: &mut [Option<RgbColor>],
    width: usize,
    height: usize,
    state: &GameState,
    px: f32,
    py: f32,
    _half_w: i32,
    _half_h: i32,
) {
    for gy in 0..height {
        for gx in 0..width {
            let Some((wx, wy)) = grid_to_world(gx, gy, px, py, width, height) else {
                continue;
            };
            let zone = state.terrain_zone_at(wx, wy);
            let kind = zone.map(|z| z.kind).unwrap_or(TerrainKindView::Grass);
            let elev = zone.map(|z| z.elevation).unwrap_or(0.0);
            let style = map_presentation::terrain_for_zone(
                kind,
                elev,
                zone.and_then(|z| z.glyph.as_deref()),
                zone.and_then(|z| z.color.as_deref()),
            );
            let idx = gy * width + gx;
            paint_presentation(cells, cell_fg, idx, &style);
        }
    }
}

fn paint_well(
    cells: &mut [String],
    cell_fg: &mut [Option<RgbColor>],
    width: usize,
    height: usize,
    building: &BuildingView,
    px: f32,
    py: f32,
    half_w: i32,
    half_h: i32,
) {
    let hw = building.width_m / 2.0;
    let hd = building.depth_m / 2.0;
    let x0 = (building.x - hw).floor() as i32;
    let y0 = (building.y - hd).floor() as i32;
    let x1 = (building.x + hw).ceil() as i32 - 1;
    let y1 = (building.y + hd).ceil() as i32 - 1;
    let water = map_presentation::shallow_water_presentation();
    let center = map_presentation::well_center_presentation();

    for wy in y0..=y1 {
        for wx in x0..=x1 {
            let pres = if wx == building.x.round() as i32 && wy == building.y.round() as i32 {
                center.clone()
            } else {
                water.clone()
            };
            if let Some((gx, gy)) =
                world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
            {
                let idx = gy * width + gx;
                if !is_wall(&cells[idx]) {
                    paint_presentation(cells, cell_fg, idx, &pres);
                }
            }
        }
    }
}

fn paint_building_walls_centered(
    cells: &mut [String],
    cell_fg: &mut [Option<RgbColor>],
    width: usize,
    height: usize,
    building: &BuildingView,
    px: f32,
    py: f32,
    half_w: i32,
    half_h: i32,
) {
    let hw = building.width_m / 2.0;
    let hd = building.depth_m / 2.0;
    paint_building_walls(
        cells,
        cell_fg,
        width,
        height,
        building.x - hw,
        building.y - hd,
        building.width_m,
        building.depth_m,
        px,
        py,
        half_w,
        half_h,
        &[],
    );
}

/// Paint perimeter walls for an axis-aligned rectangle (origin = south-west corner).
fn paint_building_walls(
    cells: &mut [String],
    cell_fg: &mut [Option<RgbColor>],
    width: usize,
    height: usize,
    origin_x: f32,
    origin_y: f32,
    width_m: f32,
    depth_m: f32,
    px: f32,
    py: f32,
    half_w: i32,
    half_h: i32,
    door_gaps: &[(f32, f32)],
) {
    let x0 = origin_x.floor() as i32;
    let y0 = origin_y.floor() as i32;
    let x1 = (origin_x + width_m).ceil() as i32 - 1;
    let y1 = (origin_y + depth_m).ceil() as i32 - 1;

    if x1 < x0 || y1 < y0 {
        return;
    }

    for wx in x0..=x1 {
        if !near_door_gap(wx, y0, door_gaps) {
            paint_wall_cell(
                cells, cell_fg, width, height, wx, y0, px, py, half_w, half_h, "-",
            );
        }
        if !near_door_gap(wx, y1, door_gaps) {
            paint_wall_cell(
                cells, cell_fg, width, height, wx, y1, px, py, half_w, half_h, "-",
            );
        }
    }
    for wy in y0 + 1..y1 {
        if !near_door_gap(x0, wy, door_gaps) {
            paint_wall_cell(
                cells, cell_fg, width, height, x0, wy, px, py, half_w, half_h, "|",
            );
        }
        if !near_door_gap(x1, wy, door_gaps) {
            paint_wall_cell(
                cells, cell_fg, width, height, x1, wy, px, py, half_w, half_h, "|",
            );
        }
    }
    if !near_door_gap(x0, y0, door_gaps) {
        paint_wall_cell(
            cells, cell_fg, width, height, x0, y0, px, py, half_w, half_h, "+",
        );
    }
    if !near_door_gap(x1, y0, door_gaps) {
        paint_wall_cell(
            cells, cell_fg, width, height, x1, y0, px, py, half_w, half_h, "+",
        );
    }
    if !near_door_gap(x0, y1, door_gaps) {
        paint_wall_cell(
            cells, cell_fg, width, height, x0, y1, px, py, half_w, half_h, "+",
        );
    }
    if !near_door_gap(x1, y1, door_gaps) {
        paint_wall_cell(
            cells, cell_fg, width, height, x1, y1, px, py, half_w, half_h, "+",
        );
    }
}

fn paint_wall_cell(
    cells: &mut [String],
    cell_fg: &mut [Option<RgbColor>],
    width: usize,
    height: usize,
    wx: i32,
    wy: i32,
    px: f32,
    py: f32,
    half_w: i32,
    half_h: i32,
    ch: &str,
) {
    let Some((gx, gy)) = world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
    else {
        return;
    };
    let idx = gy * width + gx;
    let ground = empty_ground_glyph();
    if cells[idx] == ground || is_wall(&cells[idx]) {
        cells[idx] = merge_wall_corner(&cells[idx], ch, &ground);
        cell_fg[idx] = Some(map_presentation::wall_presentation().color);
    }
}

fn is_wall(glyph: &str) -> bool {
    matches!(glyph.chars().next(), Some('+' | '-' | '|'))
}

/// Overlays (resources, loot, chests, boards) paint on any non-wall cell.
fn can_paint_world_object(glyph: &str, _ground: &str, _player_glyph: &str) -> bool {
    !is_wall(glyph)
}

fn merge_wall_corner(existing: &str, incoming: &str, ground: &str) -> String {
    if existing == ground {
        return incoming.to_string();
    }
    if existing == incoming {
        return existing.to_string();
    }
    "+".to_string()
}

fn world_to_grid(
    x: f32,
    y: f32,
    px: f32,
    py: f32,
    half_w: i32,
    half_h: i32,
    width: usize,
    height: usize,
) -> Option<(usize, usize)> {
    let dx = (x - px).round() as i32;
    let dy = (y - py).round() as i32;

    if dx.abs() > half_w || dy.abs() > half_h {
        return None;
    }

    let gx = half_w + dx;
    let gy = half_h - dy;

    if gx < 0 || gy < 0 {
        return None;
    }
    let gx = gx as usize;
    let gy = gy as usize;
    if gx >= width || gy >= height {
        return None;
    }
    Some((gx, gy))
}

/// Inverse of [`world_to_grid`]: map view cell → world meters (cell center).
pub fn grid_to_world(
    gx: usize,
    gy: usize,
    px: f32,
    py: f32,
    view_w: usize,
    view_h: usize,
) -> Option<(f32, f32)> {
    if gx >= view_w || gy >= view_h {
        return None;
    }
    let half_w = (view_w / 2) as i32;
    let half_h = (view_h / 2) as i32;
    let dx = gx as i32 - half_w;
    let dy = half_h - gy as i32;
    Some((px + dx as f32, py + dy as f32))
}

#[cfg(test)]
mod tests {
    use super::*;
    use flatland_protocol::{
        BuildingView, EntityState, PlayerVitals, PrimaryAttributes, Transform, WorldCoord,
    };

    fn state_with_building(building: BuildingView) -> GameState {
        GameState {
            session_id: 1,
            entity_id: 1,
            character_id: None,
            tick: 0,
            chunk_rev: 0,
            content_rev: 0,
            publish_rev: 0,
            entities: vec![EntityState {
                id: 1,
                label: "You".into(),
                transform: Transform {
                    position: WorldCoord::surface(148.0, 118.0),
                    yaw: 0.0,
                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
                },
                vitals: Some(PlayerVitals::default()),
                attributes: Some(PrimaryAttributes::default()),
                skills: Some(flatland_protocol::PlayerSkills::default()),
                inside_building: None,
                tile_id: None,
                presentation_state: None,
                sprite_mode: None,
                progression_xp: None,
            }],
            player: None,
            resource_nodes: vec![],
            ground_drops: vec![],
            placed_containers: vec![],
            buildings: vec![building],
            doors: vec![],
            interior_map: None,
            npcs: vec![],
            blueprints: vec![],
            world_width_m: 256.0,
            world_height_m: 256.0,
            terrain_zones: vec![],
            z_platforms: vec![],
            z_transitions: vec![],
            world_clock: flatland_protocol::WorldClock::default(),
            inventory: Default::default(),
            inventory_hints: Default::default(),
            logs: Default::default(),
            intents_sent: 0,
            ticks_received: 0,
            connected: true,
            disconnect_reason: None,
            show_stats: false,
            show_craft_menu: false,
            craft_menu_index: 0,
            craft_batch_quantity: 1,
            show_shop_menu: false,
            shop_catalog: None,
            shop_tab: flatland_client_lib::ShopTab::default(),
            shop_menu_index: 0,
            shop_quantity: 1,
            shop_trade_log: std::collections::VecDeque::new(),
            show_npc_verb_menu: false,
            npc_verb_target: None,
            npc_verb_index: 0,
            show_npc_chat: false,
            npc_chat: None,
            show_inventory_menu: false,
            inventory_menu_index: 0,
            show_move_picker: false,
            show_rename_prompt: false,
            rename_buffer: String::new(),
            move_picker_index: 0,
            move_picker: None,
            show_destroy_picker: false,
            destroy_confirm_pending: false,
            destroy_picker: None,
            combat_target: None,
            combat_target_label: None,
            in_combat: false,
            auto_attack: true,
            combat_has_los: false,
            attack_cd_ticks: 0,
            gcd_ticks: 0,
            weapon_ability_id: "unarmed".into(),
            mainhand_template_id: None,
            mainhand_label: None,
            worn: std::collections::BTreeMap::new(),
            carry_mass: 0.0,
            carry_mass_max: 0.0,
            encumbrance: flatland_protocol::EncumbranceState::Light,
            inventory_stacks: Vec::new(),
            keychain_stacks: Vec::new(),
            combat_target_detail: None,
            cast_progress: None,
            ability_cooldowns: Vec::new(),
            blocking_active: false,
            max_target_slots: 1,
            combat_slots: Vec::new(),
            rotation_presets: Vec::new(),
            show_loadout_menu: false,
            show_keychain_menu: false,
            keychain_menu_index: 0,
            show_rotation_editor: false,
            loadout_menu_index: 0,
            rotation_editor: Default::default(),
            harvest_in_progress: false,
            harvest_started_at: None,
            pending_craft_ack: None,
            quest_log: Vec::new(),
            interactables: Vec::new(),
            show_quest_offer: false,
            pending_quest_offer: None,
            show_quest_menu: false,
            quest_menu_index: 0,
            quest_withdraw_confirm: false,
            progression_curve: None,
        }
    }

    #[test]
    fn shallow_water_terrain_paints_tilde() {
        use flatland_protocol::TerrainZoneView;
        let mut state = state_with_building(BuildingView {
            id: "x".into(),
            label: "X".into(),
            x: 128.0,
            y: 128.0,
            width_m: 1.0,
            depth_m: 1.0,
            interior_blueprint: None,
            tags: vec![],
        });
        state.terrain_zones.push(TerrainZoneView {
            id: "pond".into(),
            x0: 126.0,
            y0: 126.0,
            x1: 130.0,
            y1: 130.0,
            kind: TerrainKindView::ShallowWater,
            elevation: -0.5,
            glyph: None,
            color: None,
            tile_id: None,
            z_order: 0,
        });
        state.entities = vec![EntityState {
            id: 1,
            label: "You".into(),
            transform: Transform {
                position: WorldCoord::surface(128.0, 128.0),
                yaw: 0.0,
                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
            },
            vitals: Some(PlayerVitals::default()),
            attributes: Some(PrimaryAttributes::default()),
            skills: Some(flatland_protocol::PlayerSkills::default()),
            inside_building: None,
            tile_id: None,
            presentation_state: None,
            sprite_mode: None,
            progression_xp: None,
        }];
        state.player = state.entities.first().cloned();
        let view = WorldView::build_with_target(&state, 9, 9, None);
        let flat = view.cells.join("");
        let water = map_presentation::shallow_water_presentation();
        assert!(
            flat.contains(&water.glyph),
            "expected water tiles ({:?}): {flat}",
            water.glyph
        );
        assert!(
            view.cell_fg.iter().any(|c| *c == Some(water.color)),
            "expected water color on terrain cells"
        );
    }

    #[test]
    fn zone_glyph_and_color_overrides_paint_on_map() {
        use flatland_protocol::TerrainZoneView;
        let mut state = state_with_building(BuildingView {
            id: "x".into(),
            label: "X".into(),
            x: 128.0,
            y: 128.0,
            width_m: 1.0,
            depth_m: 1.0,
            interior_blueprint: None,
            tags: vec![],
        });
        state.terrain_zones.push(TerrainZoneView {
            id: "marked".into(),
            x0: 126.0,
            y0: 126.0,
            x1: 130.0,
            y1: 130.0,
            kind: TerrainKindView::Grass,
            elevation: 0.0,
            glyph: Some("%".into()),
            color: Some("magenta".into()),
            tile_id: None,
            z_order: 0,
        });
        state.entities = vec![EntityState {
            id: 1,
            label: "You".into(),
            transform: Transform {
                position: WorldCoord::surface(128.0, 128.0),
                yaw: 0.0,
                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
            },
            vitals: Some(PlayerVitals::default()),
            attributes: Some(PrimaryAttributes::default()),
            skills: Some(flatland_protocol::PlayerSkills::default()),
            inside_building: None,
            tile_id: None,
            presentation_state: None,
            sprite_mode: None,
            progression_xp: None,
        }];
        state.player = state.entities.first().cloned();
        let view = WorldView::build_with_target(&state, 9, 9, None);
        let flat = view.cells.join("");
        assert!(
            flat.contains('%'),
            "expected custom zone glyph on map: {flat}"
        );
        assert!(
            view.cell_fg.iter().any(|c| *c == Some(RgbColor::MAGENTA)),
            "expected custom zone color on terrain cells"
        );
    }

    #[test]
    fn well_paints_water_ring_and_center() {
        let building = BuildingView {
            id: "town_well".into(),
            label: "Well".into(),
            x: 122.0,
            y: 106.0,
            width_m: 3.0,
            depth_m: 3.0,
            interior_blueprint: None,
            tags: vec!["well".into()],
        };
        let mut state = state_with_building(building);
        state.entities = vec![EntityState {
            id: 1,
            label: "You".into(),
            transform: Transform {
                position: WorldCoord::surface(120.0, 106.0),
                yaw: 0.0,
                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
            },
            vitals: Some(PlayerVitals::default()),
            attributes: Some(PrimaryAttributes::default()),
            skills: Some(flatland_protocol::PlayerSkills::default()),
            inside_building: None,
            tile_id: None,
            presentation_state: None,
            sprite_mode: None,
            progression_xp: None,
        }];
        state.player = state.entities.first().cloned();
        let view = WorldView::build_with_target(&state, 9, 9, None);
        let flat = view.cells.join("");
        assert!(flat.contains('~'), "expected well water: {flat}");
        assert!(flat.contains('O'), "expected well center: {flat}");
    }

    #[test]
    fn broker_hut_draws_wall_outline() {
        let building = BuildingView {
            id: "broker_hut".into(),
            label: "Broker's Hut".into(),
            x: 148.0,
            y: 118.0,
            width_m: 8.0,
            depth_m: 6.0,
            interior_blueprint: None,
            tags: vec![],
        };
        let mut state = state_with_building(building);
        state.player = state.entities.first().cloned();
        let view = WorldView::build_with_target(&state, 25, 15, None);
        let flat = view.cells.join("");
        assert!(flat.contains('+'), "expected corners: {flat}");
        assert!(flat.contains('-'), "expected horiz walls: {flat}");
        assert!(flat.contains('|'), "expected vert walls: {flat}");
    }

    #[test]
    fn interior_map_renders_rooms_and_walls() {
        use flatland_protocol::{InteriorMapView, InteriorRoomView};
        let building = BuildingView {
            id: "broker_hut".into(),
            label: "Broker's Hut".into(),
            x: 148.0,
            y: 118.0,
            width_m: 8.0,
            depth_m: 6.0,
            interior_blueprint: Some("broker_hut".into()),
            tags: vec![],
        };
        let mut state = state_with_building(building);
        state.interior_map = Some(InteriorMapView {
            building_id: "broker_hut".into(),
            blueprint_id: "broker_hut".into(),
            background_color: "#000000".into(),
            default_floor_color: Some("#2a2a2a".into()),
            floor_height_m: 3.0,
            rooms: vec![InteriorRoomView {
                id: "main".into(),
                label: "Main".into(),
                floor: 0,
                x0: 0.0,
                y0: 0.0,
                x1: 8.5,
                y1: 7.0,
                floor_color: None,
                floor_glyph: None,
            }],
            room_doors: vec![],
        });
        state.entities = vec![EntityState {
            id: 1,
            label: "You".into(),
            transform: Transform {
                position: WorldCoord::surface(4.0, 3.0),
                yaw: 0.0,
                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
            },
            vitals: Some(PlayerVitals::default()),
            attributes: Some(PrimaryAttributes::default()),
            skills: Some(flatland_protocol::PlayerSkills::default()),
            inside_building: Some("broker_hut".into()),
            tile_id: None,
            presentation_state: None,
            sprite_mode: None,
            progression_xp: None,
        }];
        state.player = state.entities.first().cloned();
        let view = WorldView::build_with_target(&state, 25, 15, None);
        assert_eq!(view.inside_building.as_deref(), Some("broker_hut"));
        let flat = view.cells.join("");
        assert!(flat.contains('+'), "expected interior walls: {flat}");
        assert!(flat.contains('@'), "expected player marker: {flat}");
    }

    #[test]
    fn stale_interior_map_renders_outdoor_when_outside() {
        use flatland_protocol::{InteriorMapView, InteriorRoomView};
        let building = BuildingView {
            id: "town_hall".into(),
            label: "Town Hall".into(),
            x: 163.0,
            y: 137.0,
            width_m: 20.0,
            depth_m: 10.0,
            interior_blueprint: Some("town_hall".into()),
            tags: vec![],
        };
        let mut state = state_with_building(building);
        state.interior_map = Some(InteriorMapView {
            building_id: "town_hall".into(),
            blueprint_id: "town_hall".into(),
            background_color: "#000000".into(),
            default_floor_color: Some("#2a2a2a".into()),
            floor_height_m: 3.0,
            rooms: vec![InteriorRoomView {
                id: "main_hall".into(),
                label: "Main".into(),
                floor: 0,
                x0: -3.5,
                y0: -8.0,
                x1: 18.5,
                y1: 6.0,
                floor_color: None,
                floor_glyph: None,
            }],
            room_doors: vec![],
        });
        state.player = state.entities.first().cloned();
        let view = WorldView::build_with_target(&state, 25, 15, None);
        assert!(view.inside_building.is_none());
        let flat = view.cells.join("");
        let grass = map_presentation::terrain_for(TerrainKindView::Grass).glyph;
        assert!(
            flat.contains(&grass),
            "expected outdoor terrain, not stale interior background: {flat}"
        );
        assert!(
            !flat.chars().all(|c| c == ' ' || c == '@'),
            "stale interior_map must not paint black interior when outside"
        );
    }

    #[test]
    fn stale_inside_flag_still_renders_outdoor_world() {
        use flatland_protocol::ResourceNodeState;
        let building = BuildingView {
            id: "broker_hut".into(),
            label: "Broker's Hut".into(),
            x: 148.0,
            y: 118.0,
            width_m: 8.0,
            depth_m: 6.0,
            interior_blueprint: None,
            tags: vec![],
        };
        let mut state = state_with_building(building);
        state.entities = vec![EntityState {
            id: 1,
            label: "You".into(),
            transform: Transform {
                position: WorldCoord::surface(128.0, 128.0),
                yaw: 0.0,
                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
            },
            vitals: Some(PlayerVitals::default()),
            attributes: Some(PrimaryAttributes::default()),
            skills: Some(flatland_protocol::PlayerSkills::default()),
            inside_building: Some("broker_hut".into()),
            tile_id: None,
            presentation_state: None,
            sprite_mode: None,
            progression_xp: None,
        }];
        state.player = state.entities.first().cloned();
        state
            .resource_nodes
            .push(flatland_protocol::ResourceNodeView {
                id: "oak".into(),
                label: "Oak".into(),
                x: 126.0,
                y: 134.0,
                z: 0.0,
                item_template: "oak_log".into(),
                state: ResourceNodeState::Available,
                blocking: true,
                blocking_radius_m: 0.8,
                tile_id: None,
                sprite_mode: None,
                presentation_state: None,
            });
        let view = WorldView::build_with_target(&state, 25, 15, None);
        assert_eq!(
            view.inside_building.as_deref(),
            Some("broker_hut"),
            "server inside flag is authoritative"
        );
        let flat = view.cells.join("");
        let oak = map_presentation::resource_for(&flatland_protocol::ResourceNodeView {
            id: "oak".into(),
            label: "Oak".into(),
            x: 0.0,
            y: 0.0,
            z: 0.0,
            item_template: "oak_log".into(),
            state: flatland_protocol::ResourceNodeState::Available,
            blocking: true,
            blocking_radius_m: 0.8,
            tile_id: None,
            sprite_mode: None,
            presentation_state: None,
        });
        assert!(
            flat.contains(&oak.glyph),
            "expected nearby tree ({:?}): {flat}",
            oak.glyph
        );
        assert!(flat.contains('@'), "expected player: {flat}");
    }

    #[test]
    fn inside_building_flag_selects_active_instance() {
        let town = BuildingView {
            id: "town_hall".into(),
            label: "Town Hall".into(),
            x: 160.0,
            y: 136.0,
            width_m: 20.0,
            depth_m: 10.0,
            interior_blueprint: Some("town_hall".into()),
            tags: vec![],
        };
        let guild = BuildingView {
            id: "guild_hall".into(),
            label: "Guild Hall".into(),
            x: 164.0,
            y: 152.0,
            width_m: 20.0,
            depth_m: 14.0,
            interior_blueprint: Some("guild_hall".into()),
            tags: vec![],
        };
        let mut state = state_with_building(town);
        state.buildings.push(guild);
        state.entities = vec![EntityState {
            id: 1,
            label: "You".into(),
            transform: Transform {
                position: WorldCoord::surface(4.0, 3.0),
                yaw: 0.0,
                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
            },
            vitals: Some(PlayerVitals::default()),
            attributes: Some(PrimaryAttributes::default()),
            skills: Some(flatland_protocol::PlayerSkills::default()),
            inside_building: Some("guild_hall".into()),
            tile_id: None,
            presentation_state: None,
            sprite_mode: None,
            progression_xp: None,
        }];
        state.player = state.entities.first().cloned();
        state.world_width_m = 256.0;
        state.world_height_m = 256.0;

        let view = WorldView::build_with_target(&state, 25, 15, None);
        assert_eq!(view.inside_building.as_deref(), Some("guild_hall"));
    }

    #[test]
    fn combat_target_marks_creature_cell() {
        let building = BuildingView {
            id: "x".into(),
            label: "X".into(),
            x: 128.0,
            y: 128.0,
            width_m: 1.0,
            depth_m: 1.0,
            interior_blueprint: None,
            tags: vec![],
        };
        let mut state = state_with_building(building);
        state.entities = vec![
            EntityState {
                id: 1,
                label: "You".into(),
                transform: Transform {
                    position: WorldCoord::surface(100.0, 100.0),
                    yaw: 0.0,
                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
                },
                vitals: Some(PlayerVitals::default()),
                attributes: Some(PrimaryAttributes::default()),
                skills: Some(flatland_protocol::PlayerSkills::default()),
                inside_building: None,
                tile_id: None,
                presentation_state: None,
                sprite_mode: None,
                progression_xp: None,
            },
            EntityState {
                id: 42,
                label: "Rabbit".into(),
                transform: Transform {
                    position: WorldCoord::surface(103.0, 100.0),
                    yaw: 0.0,
                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
                },
                vitals: None,
                attributes: None,
                skills: None,
                inside_building: None,
                tile_id: None,
                presentation_state: None,
                sprite_mode: None,
                progression_xp: None,
            },
        ];
        state.player = state.entities.first().cloned();
        state.combat_target = Some(42);
        state.combat_target_label = Some("Rabbit".into());

        let view = WorldView::build_with_target(&state, 25, 15, None);
        let marked: usize = view
            .target_t1_cells
            .iter()
            .chain(view.target_t2_cells.iter())
            .filter(|b| **b)
            .count();
        assert_eq!(marked, 1, "exactly one targeted cell");
        let idx = view
            .target_t1_cells
            .iter()
            .chain(view.target_t2_cells.iter())
            .position(|b| *b)
            .expect("target cell");
        assert_eq!(view.cells[idx], "R");
    }

    #[test]
    fn grid_to_world_roundtrips_center() {
        let px = 10.0;
        let py = 20.0;
        let view_w = 11;
        let view_h = 11;
        let half_w = (view_w / 2) as i32;
        let half_h = (view_h / 2) as i32;
        let (gx, gy) =
            world_to_grid(12.0, 18.0, px, py, half_w, half_h, view_w, view_h).expect("in view");
        let (wx, wy) = grid_to_world(gx, gy, px, py, view_w, view_h).expect("inverse");
        assert!((wx - 12.0).abs() < 0.01);
        assert!((wy - 18.0).abs() < 0.01);
    }

    #[test]
    fn vertical_axis_quantizes_to_one_meter() {
        let px = 0.0;
        let py = 0.0;
        let view_w = 21;
        let view_h = 21;
        let half_w = (view_w / 2) as i32;
        let half_h = (view_h / 2) as i32;
        let (gx, gy) =
            world_to_grid(3.0, 3.0, px, py, half_w, half_h, view_w, view_h).expect("in view");
        let (wx, wy) = grid_to_world(gx, gy, px, py, view_w, view_h).expect("inverse");
        assert!(
            (wx - 3.0).abs() < 0.01,
            "x should stay exact to 1m: got {wx}"
        );
        assert!(
            (wy - 3.0).abs() < 0.01,
            "y should stay exact to 1m: got {wy}"
        );
    }

    #[test]
    fn square_extent_spans_equal_rows_and_columns() {
        let px = 0.0;
        let py = 0.0;
        let half_w = 50;
        let half_h = 50;
        let width = 101;
        let height = 101;
        let (gx0, gy0) =
            world_to_grid(-4.0, -4.0, px, py, half_w, half_h, width, height).expect("in view");
        let (gx1, gy1) =
            world_to_grid(4.0, 4.0, px, py, half_w, half_h, width, height).expect("in view");
        let cols_spanned = (gx1 as i32 - gx0 as i32).unsigned_abs();
        let rows_spanned = (gy1 as i32 - gy0 as i32).unsigned_abs();
        assert_eq!(cols_spanned, 8, "8m wide should span 8 columns");
        assert_eq!(rows_spanned, 8, "8m tall should span 8 rows");
    }

    #[test]
    fn resource_paints_on_terrain_cell_for_same_world_coords() {
        use flatland_protocol::{ResourceNodeState, ResourceNodeView, TerrainZoneView};

        let px = 128.0;
        let py = 128.0;
        let rx = 131.0;
        let ry = 132.0;
        let mut state = state_with_building(BuildingView {
            id: "x".into(),
            label: "X".into(),
            x: 128.0,
            y: 128.0,
            width_m: 1.0,
            depth_m: 1.0,
            interior_blueprint: None,
            tags: vec![],
        });
        state.terrain_zones.push(TerrainZoneView {
            id: "pond".into(),
            x0: rx,
            y0: ry,
            x1: rx + 1.0,
            y1: ry + 1.0,
            kind: TerrainKindView::ShallowWater,
            elevation: -0.5,
            glyph: None,
            color: None,
            tile_id: None,
            z_order: 0,
        });
        state.resource_nodes.push(ResourceNodeView {
            id: "oak".into(),
            label: "Oak".into(),
            x: rx,
            y: ry,
            z: 0.0,
            item_template: "oak_log".into(),
            state: ResourceNodeState::Available,
            blocking: true,
            blocking_radius_m: 0.8,
            tile_id: None,
            sprite_mode: None,
            presentation_state: None,
        });
        state.entities[0].transform.position = WorldCoord::surface(px, py);
        state.player = state.entities.first().cloned();

        let view = WorldView::build_with_target(&state, 25, 15, None);
        let half_w = (view.width / 2) as i32;
        let half_h = (view.height / 2) as i32;
        let (gx, gy) = world_to_grid(rx, ry, px, py, half_w, half_h, view.width, view.height)
            .expect("resource in view");
        let idx = gy * view.width + gx;
        let oak = map_presentation::resource_for(&state.resource_nodes[0]);
        assert_eq!(
            view.cells[idx], oak.glyph,
            "resource should paint on the grid cell for its world coords"
        );
        let (wx, wy) = grid_to_world(gx, gy, px, py, view.width, view.height).expect("inverse");
        assert!(
            (wx - rx).abs() < 0.01 && (wy - ry).abs() < 0.01,
            "resource grid cell should sample terrain at ({wx}, {wy}), expected ({rx}, {ry})"
        );
    }

    #[test]
    fn chest_and_loot_paint_on_non_grass_terrain() {
        use flatland_protocol::{GroundDropView, PlacedContainerView, TerrainZoneView};

        let px = 50.0;
        let py = 50.0;
        let cx = 53.0;
        let cy = 52.0;
        let lx = 54.0;
        let ly = 52.0;
        let mut state = state_with_building(BuildingView {
            id: "x".into(),
            label: "X".into(),
            x: 50.0,
            y: 50.0,
            width_m: 1.0,
            depth_m: 1.0,
            interior_blueprint: None,
            tags: vec![],
        });
        state.terrain_zones.push(TerrainZoneView {
            id: "trail".into(),
            x0: 52.0,
            y0: 51.0,
            x1: 56.0,
            y1: 54.0,
            kind: TerrainKindView::Trail,
            elevation: 0.0,
            glyph: None,
            color: None,
            tile_id: None,
            z_order: 0,
        });
        state.placed_containers.push(PlacedContainerView {
            id: "chest_1".into(),
            template_id: "wood_chest".into(),
            display_name: "Storage".into(),
            x: cx,
            y: cy,
            z: 0.0,
            locked: false,
            accessible: true,
            owner_character_id: None,
            contents: vec![],
            lock_id: None,
            capacity_volume: Some(40.0),
            item_instance_id: None,
            tile_id: None,
        });
        state.ground_drops.push(GroundDropView {
            id: "drop_1".into(),
            template_id: "lumber".into(),
            quantity: 2,
            x: lx,
            y: ly,
            z: 0.0,
            tile_id: None,
        });
        state.entities[0].transform.position = WorldCoord::surface(px, py);
        state.player = state.entities.first().cloned();

        let view = WorldView::build_with_target(&state, 25, 15, None);
        let half_w = (view.width / 2) as i32;
        let half_h = (view.height / 2) as i32;
        let (gx, gy) =
            world_to_grid(cx, cy, px, py, half_w, half_h, view.width, view.height).expect("chest");
        let chest = map_presentation::chest_presentation(false);
        assert_eq!(
            view.cells[gy * view.width + gx],
            chest.glyph,
            "chest must paint on trail/non-grass cells"
        );
        let (gx2, gy2) =
            world_to_grid(lx, ly, px, py, half_w, half_h, view.width, view.height).expect("loot");
        let loot = map_presentation::loot_presentation();
        assert_eq!(
            view.cells[gy2 * view.width + gx2],
            loot.glyph,
            "ground loot must paint on trail/non-grass cells"
        );
    }

    #[test]
    fn build_with_anchor_sets_view_origin() {
        let mut state = state_with_building(BuildingView {
            id: "x".into(),
            label: "X".into(),
            x: 128.0,
            y: 128.0,
            width_m: 1.0,
            depth_m: 1.0,
            interior_blueprint: None,
            tags: vec![],
        });
        state.entities[0].transform.position = WorldCoord::surface(100.0, 200.0);
        state.player = state.entities.first().cloned();
        let view = WorldView::build_with_anchor(
            &state,
            21,
            15,
            12.3,
            40.7,
            None,
            WorldViewOptions::terrain_only(),
        );
        assert!((view.origin_x - 12.3).abs() < 0.01);
        assert!((view.origin_y - 40.7).abs() < 0.01);
    }

    #[test]
    fn skip_local_player_glyph_when_paint_local_player_false() {
        let mut state = state_with_building(BuildingView {
            id: "x".into(),
            label: "X".into(),
            x: 10.0,
            y: 10.0,
            width_m: 1.0,
            depth_m: 1.0,
            interior_blueprint: None,
            tags: vec![],
        });
        state.entities[0].transform.position = WorldCoord::surface(128.0, 128.0);
        state.player = state.entities.first().cloned();
        let player_glyph = map_presentation::player_presentation().glyph;

        let with_player =
            WorldView::build_with_options(&state, 21, 15, None, WorldViewOptions::default());
        let cx = with_player.width / 2;
        let cy = with_player.height / 2;
        assert_eq!(
            with_player.cells[cy * with_player.width + cx],
            player_glyph,
            "default build paints @"
        );

        let without =
            WorldView::build_with_options(&state, 21, 15, None, WorldViewOptions::terrain_only());
        assert_ne!(
            without.cells[cy * without.width + cx],
            player_glyph,
            "gfx sprite mode must not paint local player @"
        );
    }
}