rust_pixel 2.4.0

2d pixel-art game engine & rapid prototype tools support terminal, wgpu and web...
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
// RustPixel
// copyright zipxing@hotmail.com 2022~2026

//! Layered Symbol Map — Texture2DArray with Mipmap Levels
//!
//! Maps symbol strings to Tile (cell dimensions + 3 mipmap UV levels) for
//! GPU rendering via Texture2DArray.
//!
//! # Architecture
//! - Symbols are packed into multiple 2048×2048 layers (Texture2DArray)
//! - Each symbol has 3 mipmap levels (high/mid/low resolution)
//! - LayeredSymbolMap is loaded from `layered_symbol_map.json`
//! - Cell caches Tile on `set_symbol()` — zero lookup on hot render path
//!
//! # Symbol Types
//! - **Sprite**: PUA-encoded (U+F0000-U+F9FFF), 1×1 cell, game graphics
//! - **TUI**: ASCII + Box Drawing + Braille + NerdFont, 1×2 cell
//! - **Emoji**: Pre-rendered color emoji, 2×2 cell
//! - **CJK**: Common Chinese characters, 2×2 cell
//!
//! # Usage
//! ```rust,ignore
//! let map = get_layered_symbol_map().unwrap();
//! let tile = map.resolve("A");      // TUI character
//! let tile = map.resolve("😀");     // Emoji
//! let tile = map.resolve("\u{F0000}"); // PUA sprite
//! ```

use super::cell::{cellsym_block, decode_pua};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::OnceLock;

/// Path to layered_symbol_map.json file
pub const PIXEL_LAYERED_SYMBOL_MAP_FILE: &str = "assets/pix/layered_symbol_map.json";

// ============================================================================
// Core Types
// ============================================================================

/// UV coordinates for one mipmap level in a texture array layer
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct MipUV {
    /// Layer index in Texture2DArray
    pub layer: u16,
    /// Normalized UV x coordinate (0.0-1.0)
    pub x: f32,
    /// Normalized UV y coordinate (0.0-1.0)
    pub y: f32,
    /// Normalized UV width (0.0-1.0)
    pub w: f32,
    /// Normalized UV height (0.0-1.0)
    pub h: f32,
}

/// Resolved symbol with 3 mipmap levels of UV coordinates.
/// Cached in Cell after first resolution — zero lookup on subsequent frames.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Tile {
    /// Cell width in grid units (1 for normal, 2 for wide chars like CJK/Emoji)
    pub cell_w: u8,
    /// Cell height in grid units (1 for single-height, 2 for tall chars like TUI/CJK/Emoji)
    pub cell_h: u8,
    /// True if this is a pre-rendered emoji (should not apply color modulation)
    pub is_emoji: bool,
    /// 3 mipmap levels: [Level 0 (high), Level 1 (mid), Level 2 (low)]
    pub mips: [MipUV; 3],
}

/// Default tile returned for unknown symbols (transparent/empty)
const DEFAULT_TILE: Tile = Tile {
    cell_w: 1,
    cell_h: 1,
    is_emoji: false,
    mips: [MipUV { layer: 0, x: 0.0, y: 0.0, w: 0.0, h: 0.0 }; 3],
};

// ============================================================================
// LayeredSymbolMap
// ============================================================================

/// Layered symbol map — maps symbol strings to Tile with mip UV coordinates.
///
/// Loaded from `layered_symbol_map.json` generated by `cargo pixel symbols`.
/// Used by Texture2DArray rendering path (WGPU adapter).
pub struct LayeredSymbolMap {
    /// Layer size in pixels (all layers are square, typically 2048)
    pub layer_size: u32,
    /// Number of layers
    pub layer_count: u32,
    /// Screen pixels per 1×1 cell at ratio=1.0 (derived from sprite mip1 width)
    /// Used for window size calculation and mouse coordinate conversion.
    /// E.g., 32 means a 1×1 cell occupies 32×32 screen pixels.
    pub cell_pixel_size: u32,
    /// Relative paths to layer PNG files
    pub layer_files: Vec<String>,
    /// Symbol string → Tile mapping
    symbols: HashMap<String, Tile>,
    /// Reverse mapping: symbol string → (block, idx) for .pix serialization
    reverse: HashMap<String, (u8, u8)>,
    /// PETSCII mapping: Unicode char → PUA-encoded string
    ///
    /// Maps ASCII letters, digits, punctuation and box-drawing characters
    /// to their corresponding C64 PETSCII sprite positions.
    /// Built from the C64 character set layout:
    /// - sprite_symbols: @abcdefghijklmnopqrstuvwxyz[£]↑← !"#$%&'()*+,-./0123456789:;<=>?─ABCDEFGHIJKLMNOPQRSTUVWXYZ┼
    /// - sprite_extras: ▇▒∙│┐╮┌╭└╰┘╯_ → specific block 1/2 positions
    petscii: HashMap<String, String>,
}

/// Statistics for layered symbol map
#[derive(Debug, Clone)]
pub struct LayeredSymbolMapStats {
    pub layer_size: u32,
    pub layer_count: u32,
    pub symbol_count: usize,
}

// ============================================================================
// Global Instance
// ============================================================================

/// Global layered symbol map instance
static GLOBAL_LAYERED_SYMBOL_MAP: OnceLock<LayeredSymbolMap> = OnceLock::new();

/// Initialize the global layered symbol map from JSON string
pub fn init_layered_symbol_map_from_json(json: &str) -> Result<(), String> {
    let map = LayeredSymbolMap::from_json(json)?;
    GLOBAL_LAYERED_SYMBOL_MAP
        .set(map)
        .map_err(|_| "Layered symbol map already initialized".to_string())
}

/// Initialize the global layered symbol map from file path
#[cfg(all(not(target_arch = "wasm32"), graphics_mode))]
pub fn init_layered_symbol_map_from_file(path: &str) -> Result<(), String> {
    let map = LayeredSymbolMap::load(path)?;
    GLOBAL_LAYERED_SYMBOL_MAP
        .set(map)
        .map_err(|_| "Layered symbol map already initialized".to_string())?;
    log::info!("Loaded layered symbol map from {}", path);
    Ok(())
}

/// Get the global layered symbol map, if initialized
pub fn get_layered_symbol_map() -> Option<&'static LayeredSymbolMap> {
    GLOBAL_LAYERED_SYMBOL_MAP.get()
}

/// Check if layered symbol map is available
pub fn has_layered_symbol_map() -> bool {
    GLOBAL_LAYERED_SYMBOL_MAP.get().is_some()
}

// ============================================================================
// LayeredSymbolMap Implementation
// ============================================================================


/// Build the PETSCII mapping table.
///
/// Maps Unicode characters (ASCII letters, digits, punctuation, box-drawing)
/// to PUA-encoded strings corresponding to C64 sprite positions.
///
/// The mapping follows the C64 character ROM layout:
/// - `sprite_symbols` defines the sequential mapping at block 0 (92 chars)
/// - `sprite_extras` maps specific Unicode chars to other sprite blocks
fn build_petscii_map() -> HashMap<String, String> {
    // C64 character set layout: each char maps to block 0, idx = position
    // 92 characters: @a-z[£]↑←<space>!"#$%&'()*+,-./0-9:;<=>?─A-Z┼
    let sprite_symbols: &str = "@abcdefghijklmnopqrstuvwxyz[£]↑← !\"#$%&'()*+,-./0123456789:;<=>?─ABCDEFGHIJKLMNOPQRSTUVWXYZ┼";

    let mut map = HashMap::new();

    // Sequential mapping from sprite_symbols (block 0)
    for (idx, ch) in sprite_symbols.chars().enumerate() {
        let block = (idx / 256) as u8;
        let i = (idx % 256) as u8;
        map.insert(ch.to_string(), cellsym_block(block, i));
    }

    // Sprite extras: special Unicode chars mapped to specific C64 sprite positions
    let extras: &[(&str, u8, u8)] = &[
        ("", 1, 209),  // ▇ UPPER SEVEN EIGHTHS BLOCK
        ("", 1, 94),    // ▒ MEDIUM SHADE
        ("", 1, 122),      // ∙ BULLET OPERATOR
        ("", 1, 93),     // │ BOX DRAWINGS LIGHT VERTICAL
        ("", 1, 110),      // ┐ BOX DRAWINGS LIGHT DOWN AND LEFT
        ("", 1, 73),   // ╮ BOX DRAWINGS LIGHT ARC DOWN AND LEFT
        ("", 1, 112),      // ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT
        ("", 1, 85),   // ╭ BOX DRAWINGS LIGHT ARC DOWN AND RIGHT
        ("", 1, 109),      // └ BOX DRAWINGS LIGHT UP AND RIGHT
        ("", 1, 74),   // ╰ BOX DRAWINGS LIGHT ARC UP AND RIGHT
        ("", 1, 125),      // ┘ BOX DRAWINGS LIGHT UP AND LEFT
        ("", 1, 75),   // ╯ BOX DRAWINGS LIGHT ARC UP AND LEFT
        ("_", 2, 30),              // _ UNDERSCORE
    ];

    for &(sym, block, idx) in extras {
        map.insert(sym.to_string(), cellsym_block(block, idx));
    }

    map
}


impl LayeredSymbolMap {
    /// Load from JSON file path
    pub fn load(path: &str) -> Result<Self, String> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| format!("Failed to read {}: {}", path, e))?;
        Self::from_json(&content)
    }

    /// Parse from JSON string
    pub fn from_json(json: &str) -> Result<Self, String> {
        let root: Value = serde_json::from_str(json)
            .map_err(|e| format!("JSON parse error: {}", e))?;

        let version = root["version"].as_u64().unwrap_or(0) as u32;
        if version != 2 {
            return Err(format!("Unsupported layered symbol map version: {} (expected 2)", version));
        }

        let layer_size = root["layer_size"].as_u64()
            .ok_or("Missing layer_size")? as u32;
        let layer_count = root["layer_count"].as_u64()
            .ok_or("Missing layer_count")? as u32;

        // cell_pixel_size: screen pixels per 1×1 cell at ratio=1.0
        // Default to 32 (= PIXEL_SYMBOL_SIZE * 2) for backward compatibility
        let cell_pixel_size = root["cell_pixel_size"].as_u64().unwrap_or(32) as u32;

        let layer_files: Vec<String> = root["layer_files"]
            .as_array()
            .ok_or("Missing layer_files")?
            .iter()
            .filter_map(|v| v.as_str().map(|s| s.to_string()))
            .collect();

        if layer_files.len() != layer_count as usize {
            return Err(format!(
                "layer_count ({}) != layer_files length ({})",
                layer_count, layer_files.len()
            ));
        }

        let symbols_obj = root["symbols"]
            .as_object()
            .ok_or("Missing symbols")?;

        let inv = 1.0 / layer_size as f32;
        let mut symbols = HashMap::with_capacity(symbols_obj.len());
        let mut reverse = HashMap::with_capacity(symbols_obj.len());

        // Counters for assigning (block, idx) to non-PUA symbols
        let mut tui_count: u16 = 0;
        let mut emoji_count: u16 = 0;
        let mut cjk_count: u16 = 0;

        for (key, val) in symbols_obj {
            // Flat array format (17 numbers):
            //   [0]: cell_w, [1]: cell_h
            //   [2-6]: mip0 (layer, x, y, w, h)
            //   [7-11]: mip1 (layer, x, y, w, h)
            //   [12-16]: mip2 (layer, x, y, w, h)
            let arr = val.as_array().ok_or_else(|| format!("Symbol '{}' is not an array", key))?;
            if arr.len() < 17 {
                return Err(format!("Symbol '{}' array too short: {} < 17", key, arr.len()));
            }

            let cell_w = arr[0].as_u64().unwrap_or(1) as u8;
            let cell_h = arr[1].as_u64().unwrap_or(1) as u8;

            let mut mips = [MipUV::default(); 3];
            for i in 0..3 {
                let base = 2 + i * 5;
                mips[i] = MipUV {
                    layer: arr[base].as_u64().unwrap_or(0) as u16,
                    x: arr[base + 1].as_u64().unwrap_or(0) as f32 * inv,
                    y: arr[base + 2].as_u64().unwrap_or(0) as f32 * inv,
                    w: arr[base + 3].as_u64().unwrap_or(0) as f32 * inv,
                    h: arr[base + 4].as_u64().unwrap_or(0) as f32 * inv,
                };
            }

            // Determine if this symbol is an emoji (should not apply color modulation)
            let is_emoji = key.chars().next().map_or(false, |ch| {
                let cp = ch as u32;
                // Emoji Unicode ranges:
                // - U+1F000-U+1FAFF: Main emoji block (emoticons, symbols, hands, etc.)
                // - U+2300-U+23FF: Miscellaneous Technical (⏰⌛ etc.)
                // - U+2600-U+26FF: Miscellaneous Symbols (⚓⚡⚽⛵ etc.)
                // - U+2700-U+27BF: Dingbats (✅✌✏ etc.)
                // - U+2B00-U+2BFF: Miscellaneous Symbols and Arrows (⭐⬛⬜ etc.)
                (0x1F000..=0x1FAFF).contains(&cp)
                    || (0x2300..=0x23FF).contains(&cp)
                    || (0x2600..=0x26FF).contains(&cp)
                    || (0x2700..=0x27BF).contains(&cp)
                    || (0x2B00..=0x2BFF).contains(&cp)
            });

            symbols.insert(key.clone(), Tile { cell_w, cell_h, is_emoji, mips });

            // Build reverse mapping: symbol → (block, idx)
            if let Some(ch) = key.chars().next() {
                if let Some((block, idx)) = decode_pua(ch) {
                    // PUA sprite: decode directly
                    reverse.insert(key.clone(), (block, idx));
                } else {
                    let cp = ch as u32;
                    // Use same emoji range check for reverse mapping
                    let is_emoji_cp = (0x1F000..=0x1FAFF).contains(&cp)
                        || (0x2300..=0x23FF).contains(&cp)
                        || (0x2600..=0x26FF).contains(&cp)
                        || (0x2700..=0x27BF).contains(&cp)
                        || (0x2B00..=0x2BFF).contains(&cp);
                    if is_emoji_cp {
                        // Emoji range → block 170+
                        let block = 170 + (emoji_count / 128) as u8;
                        let idx = (emoji_count % 128) as u8;
                        reverse.insert(key.clone(), (block, idx));
                        emoji_count += 1;
                    } else if (0x4E00..=0x9FFF).contains(&cp) {
                        // CJK range → block 176+
                        let block = 176 + (cjk_count / 64) as u8;
                        let idx = (cjk_count % 64) as u8;
                        reverse.insert(key.clone(), (block, idx));
                        cjk_count += 1;
                    } else {
                        // TUI (ASCII, Box Drawing, Braille, etc.) → block 160+
                        let block = 160 + (tui_count / 256) as u8;
                        let idx = (tui_count % 256) as u8;
                        reverse.insert(key.clone(), (block, idx));
                        tui_count += 1;
                    }
                }
            }
        }

        Ok(Self {
            layer_size,
            layer_count,
            cell_pixel_size,
            layer_files,
            symbols,
            reverse,
            petscii: build_petscii_map(),
        })
    }

    /// Resolve a symbol string to a Tile with 3 mipmap UV levels.
    /// Returns the default tile (empty/transparent) for unknown symbols.
    #[inline]
    pub fn resolve(&self, symbol: &str) -> &Tile {
        self.symbols.get(symbol).unwrap_or(&DEFAULT_TILE)
    }

    /// Check if a symbol exists in the map
    #[inline]
    pub fn contains(&self, symbol: &str) -> bool {
        self.symbols.contains_key(symbol)
    }

    /// Reverse lookup: symbol string → (block, idx) for .pix serialization.
    /// Returns None for unknown symbols.
    #[inline]
    pub fn reverse_lookup(&self, symbol: &str) -> Option<(u8, u8)> {
        self.reverse.get(symbol).copied()
    }

    /// PETSCII lookup: Unicode char → PUA-encoded string for C64 sprite rendering.
    ///
    /// Used by `ascii_to_petscii` and `set_border_sym` to map Unicode characters
    /// (letters, digits, box-drawing) to their C64 PETSCII sprite equivalents.
    /// Returns None if the character has no PETSCII mapping.
    #[inline]
    pub fn petscii_lookup(&self, symbol: &str) -> Option<&str> {
        self.petscii.get(symbol).map(|s| s.as_str())
    }

    /// Get total number of symbols
    pub fn symbol_count(&self) -> usize {
        self.symbols.len()
    }

    /// Get statistics
    pub fn stats(&self) -> LayeredSymbolMapStats {
        LayeredSymbolMapStats {
            layer_size: self.layer_size,
            layer_count: self.layer_count,
            symbol_count: self.symbols.len(),
        }
    }
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Convert ASCII string to PETSCII PUA-encoded string.
///
/// Each character is looked up in the PETSCII mapping table which maps
/// Unicode characters to their C64 sprite equivalents (PUA-encoded).
/// Falls back to block 0 with ASCII code as index for unmapped characters.
pub fn ascii_to_petscii(s: &str) -> String {
    if let Some(map) = get_layered_symbol_map() {
        let mut result = String::with_capacity(s.len() * 4);
        for ch in s.chars() {
            let ch_str = ch.to_string();
            // Look up in PETSCII table (sprite_symbols + sprite_extras)
            if let Some(pua) = map.petscii_lookup(&ch_str) {
                result.push_str(pua);
            } else {
                // Fallback: block 0 with ASCII code
                result.push_str(&cellsym_block(0, ch as u8));
            }
        }
        result
    } else {
        // No layered map loaded — simple fallback
        s.chars()
            .map(|ch| cellsym_block(0, ch as u8))
            .collect()
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    fn sample_layered_json() -> String {
        // Build JSON with actual Unicode characters (PUA U+F0000 needs surrogate pairs in JSON)
        let pua_char = '\u{F0000}'; // PUA sprite: block 0, idx 0
        let emoji_char = '\u{1F600}'; // 😀
        format!(
            r#"{{
            "version": 2,
            "layer_size": 2048,
            "layer_count": 2,
            "layer_files": ["layers/layer_0.png", "layers/layer_1.png"],
            "symbols": {{
                "A": {{
                    "w": 1, "h": 2,
                    "mip0": {{"layer": 0, "x": 64, "y": 0, "w": 64, "h": 128}},
                    "mip1": {{"layer": 0, "x": 1024, "y": 1024, "w": 32, "h": 64}},
                    "mip2": {{"layer": 1, "x": 0, "y": 0, "w": 16, "h": 32}}
                }},
                "{}": {{
                    "w": 1, "h": 1,
                    "mip0": {{"layer": 0, "x": 0, "y": 128, "w": 64, "h": 64}},
                    "mip1": {{"layer": 0, "x": 1024, "y": 1088, "w": 32, "h": 32}},
                    "mip2": {{"layer": 1, "x": 16, "y": 0, "w": 16, "h": 16}}
                }},
                "{}": {{
                    "w": 2, "h": 2,
                    "mip0": {{"layer": 0, "x": 0, "y": 192, "w": 128, "h": 128}},
                    "mip1": {{"layer": 0, "x": 1024, "y": 1120, "w": 64, "h": 64}},
                    "mip2": {{"layer": 1, "x": 32, "y": 0, "w": 32, "h": 32}}
                }},
                "中": {{
                    "w": 2, "h": 2,
                    "mip0": {{"layer": 0, "x": 128, "y": 192, "w": 128, "h": 128}},
                    "mip1": {{"layer": 0, "x": 1088, "y": 1120, "w": 64, "h": 64}},
                    "mip2": {{"layer": 1, "x": 64, "y": 0, "w": 32, "h": 32}}
                }}
            }}
        }}"#,
            pua_char, emoji_char
        )
    }

    #[test]
    fn test_layered_parse_basic() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        assert_eq!(map.layer_size, 2048);
        assert_eq!(map.layer_count, 2);
        assert_eq!(map.layer_files.len(), 2);
        assert_eq!(map.symbol_count(), 4);
    }

    #[test]
    fn test_layered_resolve_tui() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        let tile = map.resolve("A");
        assert_eq!(tile.cell_w, 1);
        assert_eq!(tile.cell_h, 2);
        // mip0: layer=0, x=64/2048, y=0/2048, w=64/2048, h=128/2048
        assert_eq!(tile.mips[0].layer, 0);
        assert!((tile.mips[0].x - 64.0 / 2048.0).abs() < 1e-6);
        assert!((tile.mips[0].y - 0.0).abs() < 1e-6);
        assert!((tile.mips[0].w - 64.0 / 2048.0).abs() < 1e-6);
        assert!((tile.mips[0].h - 128.0 / 2048.0).abs() < 1e-6);
    }

    #[test]
    fn test_layered_resolve_sprite_pua() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        // U+F0000 = PUA sprite (block 0, idx 0)
        let pua = "\u{F0000}";
        let tile = map.resolve(pua);
        assert_eq!(tile.cell_w, 1);
        assert_eq!(tile.cell_h, 1);
        assert_eq!(tile.mips[0].layer, 0);
        assert_eq!(tile.mips[2].layer, 1);
    }

    #[test]
    fn test_layered_resolve_emoji() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        let tile = map.resolve("\u{1F600}");
        assert_eq!(tile.cell_w, 2);
        assert_eq!(tile.cell_h, 2);
        // mip0: 128x128 at layer 0
        assert!((tile.mips[0].w - 128.0 / 2048.0).abs() < 1e-6);
        assert!((tile.mips[0].h - 128.0 / 2048.0).abs() < 1e-6);
    }

    #[test]
    fn test_layered_resolve_cjk() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        let tile = map.resolve("");
        assert_eq!(tile.cell_w, 2);
        assert_eq!(tile.cell_h, 2);
        assert_eq!(tile.mips[1].layer, 0);
        assert!((tile.mips[1].w - 64.0 / 2048.0).abs() < 1e-6);
    }

    #[test]
    fn test_layered_resolve_unknown() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        let tile = map.resolve("NONEXISTENT");
        // Should return default tile
        assert_eq!(tile.cell_w, 1);
        assert_eq!(tile.cell_h, 1);
        assert!((tile.mips[0].w).abs() < 1e-6); // zero width = empty
    }

    #[test]
    fn test_layered_uv_range() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        // All UV coordinates should be in [0.0, 1.0]
        for tile in map.symbols.values() {
            for mip in &tile.mips {
                assert!(mip.x >= 0.0 && mip.x <= 1.0, "x out of range: {}", mip.x);
                assert!(mip.y >= 0.0 && mip.y <= 1.0, "y out of range: {}", mip.y);
                assert!(mip.w >= 0.0 && mip.w <= 1.0, "w out of range: {}", mip.w);
                assert!(mip.h >= 0.0 && mip.h <= 1.0, "h out of range: {}", mip.h);
                assert!(mip.x + mip.w <= 1.0 + 1e-6, "x+w out of range");
                assert!(mip.y + mip.h <= 1.0 + 1e-6, "y+h out of range");
            }
        }
    }

    #[test]
    fn test_layered_layer_bounds() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        // All layer indices should be < layer_count
        for tile in map.symbols.values() {
            for mip in &tile.mips {
                assert!(
                    (mip.layer as u32) < map.layer_count,
                    "layer {} >= layer_count {}",
                    mip.layer, map.layer_count
                );
            }
        }
    }

    #[test]
    fn test_layered_version_check() {
        let bad_json = r#"{"version": 1, "layer_size": 2048, "layer_count": 0, "layer_files": [], "symbols": {}}"#;
        assert!(LayeredSymbolMap::from_json(bad_json).is_err());
    }

    #[test]
    fn test_layered_stats() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        let stats = map.stats();
        assert_eq!(stats.layer_size, 2048);
        assert_eq!(stats.layer_count, 2);
        assert_eq!(stats.symbol_count, 4);
    }

    #[test]
    fn test_tile_size() {
        // Tile should be compact — verify it fits in a reasonable size
        assert!(std::mem::size_of::<Tile>() <= 64, "Tile too large: {} bytes", std::mem::size_of::<Tile>());
        // MipUV should be Copy
        let m = MipUV::default();
        let m2 = m; // Copy
        assert_eq!(m2.layer, 0);
    }

    #[test]
    fn test_reverse_lookup_pua() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        // PUA sprite should decode to (block=0, idx=0)
        let pua = "\u{F0000}";
        assert_eq!(map.reverse_lookup(pua), Some((0, 0)));
    }

    #[test]
    fn test_reverse_lookup_tui() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        // TUI char "A" should get block 160+
        let result = map.reverse_lookup("A");
        assert!(result.is_some());
        let (block, _idx) = result.unwrap();
        assert!(block >= 160 && block < 170, "TUI block should be 160-169, got {}", block);
    }

    #[test]
    fn test_reverse_lookup_emoji() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        let result = map.reverse_lookup("\u{1F600}");
        assert!(result.is_some());
        let (block, _idx) = result.unwrap();
        assert!(block >= 170 && block < 176, "Emoji block should be 170-175, got {}", block);
    }

    #[test]
    fn test_reverse_lookup_cjk() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        let result = map.reverse_lookup("");
        assert!(result.is_some());
        let (block, _idx) = result.unwrap();
        assert!(block >= 176, "CJK block should be >= 176, got {}", block);
    }

    #[test]
    fn test_reverse_lookup_unknown() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        assert_eq!(map.reverse_lookup("NONEXISTENT"), None);
    }

    #[test]
    fn test_petscii_lookup_letters() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        // 'A' should map to block 0, idx 65 (position in sprite_symbols)
        let pua_a = map.petscii_lookup("A");
        assert!(pua_a.is_some(), "A should have PETSCII mapping");
        let pua_a = pua_a.unwrap();
        assert_eq!(pua_a, &cellsym_block(0, 65));

        // 'P' -> block 0, idx 80
        assert_eq!(map.petscii_lookup("P").unwrap(), &cellsym_block(0, 80));

        // '0' -> block 0, idx 48
        assert_eq!(map.petscii_lookup("0").unwrap(), &cellsym_block(0, 48));
    }

    #[test]
    fn test_petscii_lookup_extras() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        // Box-drawing extras should map to specific sprite positions
        // U+2502 (|) -> block 1, idx 93
        assert_eq!(
            map.petscii_lookup("\u{2502}").unwrap(),
            &cellsym_block(1, 93),
        );
        // U+250C -> block 1, idx 112
        assert_eq!(
            map.petscii_lookup("\u{250C}").unwrap(),
            &cellsym_block(1, 112),
        );
        // U+256D -> block 1, idx 85
        assert_eq!(
            map.petscii_lookup("\u{256D}").unwrap(),
            &cellsym_block(1, 85),
        );
        // _ -> block 2, idx 30
        assert_eq!(
            map.petscii_lookup("_").unwrap(),
            &cellsym_block(2, 30),
        );
    }

    #[test]
    fn test_petscii_lookup_nonexistent() {
        let map = LayeredSymbolMap::from_json(&sample_layered_json()).unwrap();
        // Characters not in PETSCII table should return None
        assert!(map.petscii_lookup("\u{1F600}").is_none()); // emoji
        assert!(map.petscii_lookup("\u{4E2D}").is_none()); // CJK
    }
}