openstranded-map-tool 0.2.0

Convert Stranded II .s2 map files to .osmap (OpenStranded MAP) format
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
// openstranded-map-tool — convert Stranded II .s2 maps to .osmap format
// Copyright (C) 2026  OpenStranded contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Binary parser for Stranded II `.s2` map files.
//!
//! **Authoritative reference:** `original-source/source/includes/e_save_map.bb`
//! — the actual Blitz3D save routine. The `.s2-map-format.md` doc has several
//! errors; the source is the source of truth.

use std::io::{Cursor, Read};

use crate::types::*;

/// Errors that can occur during `.s2` parsing.
#[derive(Debug)]
pub enum S2Error {
    Io(std::io::Error),
    InvalidHeader(String),
    UnexpectedEof,
    InvalidTrailer(String),
    UnsupportedFormat(String),
}

impl std::fmt::Display for S2Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            S2Error::Io(e) => write!(f, "I/O error: {e}"),
            S2Error::InvalidHeader(s) => write!(f, "invalid header: {s}"),
            S2Error::UnexpectedEof => write!(f, "unexpected end of file"),
            S2Error::InvalidTrailer(s) => write!(f, "invalid trailer: {s}"),
            S2Error::UnsupportedFormat(s) => write!(f, "unsupported format: {s}"),
        }
    }
}

impl std::error::Error for S2Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            S2Error::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for S2Error {
    fn from(e: std::io::Error) -> Self {
        S2Error::Io(e)
    }
}

/// Specialized result type for `.s2` parsing.
pub type S2Result<T> = Result<T, S2Error>;

// ---------------------------------------------------------------------------
// Helper: reading primitives from a Cursor
// ---------------------------------------------------------------------------

fn read_u8(c: &mut Cursor<&[u8]>) -> S2Result<u8> {
    let mut buf = [0u8; 1];
    c.read_exact(&mut buf)?;
    Ok(buf[0])
}

fn read_u16_le(c: &mut Cursor<&[u8]>) -> S2Result<u16> {
    let mut buf = [0u8; 2];
    c.read_exact(&mut buf)?;
    Ok(u16::from_le_bytes(buf))
}

fn read_u32_le(c: &mut Cursor<&[u8]>) -> S2Result<u32> {
    let mut buf = [0u8; 4];
    c.read_exact(&mut buf)?;
    Ok(u32::from_le_bytes(buf))
}

fn read_f32_le(c: &mut Cursor<&[u8]>) -> S2Result<f32> {
    let mut buf = [0u8; 4];
    c.read_exact(&mut buf)?;
    Ok(f32::from_le_bytes(buf))
}

fn read_exact(c: &mut Cursor<&[u8]>, n: usize) -> S2Result<Vec<u8>> {
    let mut buf = vec![0u8; n];
    c.read_exact(&mut buf)?;
    Ok(buf)
}

/// Read a Blitz3D `WriteString`: u32 LE length prefix + data (Windows-1252).
/// Uses lossy UTF-8 conversion for non-UTF-8 bytes.
fn read_s2_string(c: &mut Cursor<&[u8]>) -> S2Result<String> {
    let len = read_u32_le(c)? as usize;
    if len == 0 {
        return Ok(String::new());
    }
    let bytes = read_exact(c, len)?;
    Ok(String::from_utf8_lossy(&bytes).into_owned())
}

/// Read a Blitz3D `WriteLine`: read until `\r\n`. Uses lossy UTF-8 conversion.
fn read_s2_line(c: &mut Cursor<&[u8]>) -> S2Result<String> {
    let mut bytes = Vec::new();
    loop {
        let b = read_u8(c)?;
        if b == b'\r' {
            let next = read_u8(c)?;
            if next == b'\n' {
                break;
            }
            bytes.push(b);
            bytes.push(next);
        } else {
            bytes.push(b);
        }
    }
    Ok(String::from_utf8_lossy(&bytes).into_owned())
}

// ---------------------------------------------------------------------------
// Main parser
// ---------------------------------------------------------------------------

/// Parse a complete `.s2` file from a byte slice.
pub fn parse_s2(data: &[u8]) -> S2Result<S2Map> {
    let mut c = Cursor::new(data);

    // ---- 1. Header — dynamic lines until "###\r\n" ----
    let header = parse_header(&mut c)?;

    // ---- 2. Minimap (96×72×3 = 20736 bytes, 24-bit RGB) ----
    let minimap = read_exact(&mut c, 20736)?;

    // ---- 3. Password header ----
    // From source: WriteByte(stream, pwkey) + WriteLine(stream, encodedpw$)
    let pw_key = read_u8(&mut c)?;
    let encoded_pw = read_s2_line(&mut c)?;

    // ---- 4. Environment variables ----
    let env_vars = parse_env_vars(&mut c)?;

    // ---- 5. Quickslots (10 × WriteString) ----
    let quickslots = parse_quickslots(&mut c)?;

    // ---- 6. Colormap ----
    let colormap_dim = read_u32_le(&mut c)?;
    let colormap_size = (colormap_dim * colormap_dim * 3) as usize;
    let colormap = read_exact(&mut c, colormap_size)?;

    // ---- 7. Heightmap ----
    let terrain_size = read_u32_le(&mut c)?;
    let height_count = ((terrain_size + 1) * (terrain_size + 1)) as usize;
    let mut heights = Vec::with_capacity(height_count);
    for _ in 0..height_count {
        heights.push(read_f32_le(&mut c)?);
    }

    // ---- 8. Grass layer (colormap_dim+1)² bytes, column-major ----
    let grass_dim = colormap_dim + 1;
    let grass_size = (grass_dim * grass_dim) as usize;
    let grass = read_exact(&mut c, grass_size)?;

    // ---- 9. Footer: entity sections + trailer ----
    // Type-format from header is authoritative. The save function wrote the
    // format flags based on entity counts at save time; reading them back must
    // use the same flags regardless of whether counts changed.
    let tf = TypeFormat::from_string(&header.type_format);
    let (objects, units, items, infos, states, extensions, trailer) = parse_footer(&mut c, tf)?;

    // Detect password from encoded form
    let decoded_pw = decode_password(&encoded_pw, pw_key);

    Ok(S2Map {
        header,
        minimap,
        password: S2Password {
            key: pw_key,
            encoded: encoded_pw,
            decoded: decoded_pw,
        },
        env_vars,
        quickslots,
        colormap_dim,
        colormap,
        terrain_size,
        heights,
        grass,
        objects,
        units,
        items,
        infos,
        states,
        extensions,
        trailer,
    })
}

/// Simple XOR-based password decoder from the Blitz3D source's `code()` function.
fn decode_password(encoded: &str, key: u8) -> String {
    let bytes = encoded.as_bytes();
    let decoded: Vec<u8> = bytes.iter().map(|&b| b ^ key).collect();
    String::from_utf8_lossy(&decoded).into_owned()
}

// ---------------------------------------------------------------------------
// Header
// ---------------------------------------------------------------------------

fn parse_header(c: &mut Cursor<&[u8]>) -> S2Result<S2Header> {
    let mut lines: Vec<String> = Vec::new();
    loop {
        let line = read_s2_line(c)?;
        if line == "###" {
            break;
        }
        lines.push(line);
    }

    if lines.len() < 11 {
        return Err(S2Error::InvalidHeader(format!(
            "expected 11+ header lines before '###', got {}",
            lines.len()
        )));
    }

    // Line 0: "### Stranded II Mapfile ..."
    if !lines[0].starts_with("### Stranded II Mapfile") {
        return Err(S2Error::InvalidHeader(format!(
            "not a Stranded II map file: {:?}",
            lines[0]
        )));
    }

    // Lines 1-5 (indices 1-5)
    let version = lines.get(1).cloned().unwrap_or_default();
    let date = lines.get(2).cloned().unwrap_or_default();
    let time = lines.get(3).cloned().unwrap_or_default();
    let author = lines.get(4).cloned().unwrap_or_default();
    let map_type = lines.get(5).cloned().unwrap_or_default();

    // Line 6 (index 6): type format string (e.g. "001", "100") or empty for all u8
    let type_format = lines.get(6).cloned().unwrap_or_default();

    // Lines 7-10: blank lines, ignored

    Ok(S2Header {
        version,
        date,
        time,
        author,
        map_type,
        type_format,
    })
}

// ---------------------------------------------------------------------------
// Environment variables
// ---------------------------------------------------------------------------
// Source order (e_save_map.bb lines 70-84):
//   WriteInt(day) → 4
//   WriteByte(hour) → 1
//   WriteByte(minute) → 1
//   WriteByte(freezetime) → 1
//   WriteString(skybox) → 4 + len
//   WriteByte(multiplayer) → 1
//   WriteByte(climate) → 1
//   WriteString(music) → 4 + len
//   WriteString(briefing) → 4 + len
//   WriteByte(fog_r) → 1
//   WriteByte(fog_g) → 1
//   WriteByte(fog_b) → 1
//   WriteByte(fog_mode) → 1
//   WriteByte(extra) → 1

fn parse_env_vars(c: &mut Cursor<&[u8]>) -> S2Result<S2EnvVars> {
    let day = read_u32_le(c)?;
    let hour = read_u8(c)?;
    let minute = read_u8(c)?;
    let freezetime = read_u8(c)?;
    let skybox = read_s2_string(c)?;
    let multiplayer = read_u8(c)?;
    let climate = read_u8(c)?;
    let music = read_s2_string(c)?;
    let briefing = read_s2_string(c)?;
    let f_r = read_u8(c)?;
    let f_g = read_u8(c)?;
    let f_b = read_u8(c)?;
    let f_mode = read_u8(c)?;
    let extra = read_u8(c)?;

    Ok(S2EnvVars {
        day,
        hour,
        minute,
        freezetime,
        skybox,
        multiplayer,
        climate,
        music,
        briefing,
        fog: [f_r, f_g, f_b, f_mode],
        extra,
    })
}

// ---------------------------------------------------------------------------
// Quickslots
// ---------------------------------------------------------------------------

fn parse_quickslots(c: &mut Cursor<&[u8]>) -> S2Result<Vec<String>> {
    let mut slots = Vec::with_capacity(10);
    for _ in 0..10 {
        slots.push(read_s2_string(c)?);
    }
    Ok(slots)
}

// ---------------------------------------------------------------------------
// Type format flags
// ---------------------------------------------------------------------------

/// Type-format flags parsed from the header's type_format string.
/// "001" → tf_item=true, rest false. Empty → all false.
#[derive(Debug, Clone, Copy)]
struct TypeFormat {
    tf_object: bool,
    tf_unit: bool,
    tf_item: bool,
}

impl TypeFormat {
    /// Parse from the 3-character type_format header line (or empty).
    /// Characters are '0' (u8) or '1' (u16) for object/unit/item.
    fn from_string(s: &str) -> Self {
        let chars: Vec<char> = s.chars().collect();
        TypeFormat {
            tf_object: chars.first().copied() == Some('1'),
            tf_unit: chars.get(1).copied() == Some('1'),
            tf_item: chars.get(2).copied() == Some('1'),
        }
    }

}

// ---------------------------------------------------------------------------
// Footer
// ---------------------------------------------------------------------------
//
// IMPORTANT: The counts and their data sections are INTERLEAVED, not batched.
//
//   WriteInt(object_count)     → count
//   For each object: record    → data
//   WriteInt(unit_count)       → count
//   For each unit: record      → data
//   WriteInt(item_count)       → count
//   For each item: record      → data
//   WriteInt(info_count)       → count
//   For each info: record      → data
//   WriteInt(state_count)      → count
//   For each state: record     → data
//   WriteInt(ext_count)        → count
//   For each ext: record       → data
//   Trailer                    → 3 lines
//
// (Confirmed from e_save_map.bb lines 131-373)

fn parse_footer(
    c: &mut Cursor<&[u8]>,
    tf: TypeFormat,
) -> S2Result<(
    Vec<S2Object>,
    Vec<S2Unit>,
    Vec<S2Item>,
    Vec<S2Info>,
    Vec<S2State>,
    Vec<S2Extension>,
    S2Trailer,
)> {
    // --- Objects: count then data ---
    let obj_count = read_u32_le(c)?;
    let mut objects = Vec::with_capacity(obj_count as usize);
    for _ in 0..obj_count {
        objects.push(parse_object(c, tf.tf_object)?);
    }

    // --- Units: count then data ---
    let unit_count = read_u32_le(c)?;
    let mut units = Vec::with_capacity(unit_count as usize);
    for _ in 0..unit_count {
        units.push(parse_unit(c, tf.tf_unit)?);
    }

    // --- Items: count then data ---
    let item_count = read_u32_le(c)?;
    let mut items = Vec::with_capacity(item_count as usize);
    for _ in 0..item_count {
        items.push(parse_item(c, tf.tf_item)?);
    }

    // --- Infos: count then data ---
    let info_count = read_u32_le(c)?;
    let mut infos = Vec::with_capacity(info_count as usize);
    for _ in 0..info_count {
        infos.push(parse_info(c)?);
    }

    // --- States: count then data ---
    let state_count = read_u32_le(c)?;
    let mut states = Vec::with_capacity(state_count as usize);
    for _ in 0..state_count {
        states.push(parse_state(c)?);
    }

    // --- Extensions: count then data ---
    let ext_count = read_u32_le(c)?;
    let mut extensions = Vec::with_capacity(ext_count as usize);
    for _ in 0..ext_count {
        extensions.push(parse_extension(c)?);
    }

    // --- Trailer ---
    let blank = read_s2_line(c)?;
    let eof_marker = read_s2_line(c)?;
    let url = read_s2_line(c)?;

    if !eof_marker.is_empty() && eof_marker != "### EOF Map File" {
        return Err(S2Error::InvalidTrailer(format!(
            "expected '### EOF Map File', got {:?}",
            eof_marker
        )));
    }
    if !url.is_empty() && url != "www.unrealsoftware.de" {
        return Err(S2Error::InvalidTrailer(format!(
            "expected 'www.unrealsoftware.de', got {:?}",
            url
        )));
    }

    let trailer = S2Trailer {
        blank,
        eof_marker,
        url,
    };

    Ok((objects, units, items, infos, states, extensions, trailer))
}

// ---------------------------------------------------------------------------
// Entity parsers (all from e_save_map.bb)
// ---------------------------------------------------------------------------

/// Object record (e_save_map.bb lines 137-148):
///   WriteInt(id), If tf: WriteShort(typ)/WriteByte(typ),
///   WriteFloat(x), WriteFloat(z), WriteFloat(yaw),
///   WriteFloat(health), WriteFloat(health_max), WriteInt(daytimer)
fn parse_object(c: &mut Cursor<&[u8]>, tf: bool) -> S2Result<S2Object> {
    let id = read_u32_le(c)?;
    let typ = if tf {
        read_u16_le(c)? as u32
    } else {
        read_u8(c)? as u32
    };
    let x = read_f32_le(c)?;
    let z = read_f32_le(c)?;
    let yaw = read_f32_le(c)?;
    let health = read_f32_le(c)?;
    let health_max = read_f32_le(c)?;
    let day_timer = read_u32_le(c)?;
    Ok(S2Object {
        id,
        typ,
        x,
        z,
        yaw,
        health,
        health_max,
        day_timer,
    })
}

/// Unit record (e_save_map.bb lines 166-182):
///   WriteInt(id), If tf: WriteShort(typ)/WriteByte(typ),
///   WriteFloat(x), WriteFloat(y), WriteFloat(z), WriteFloat(yaw),
///   WriteFloat(health), WriteFloat(health_max),
///   WriteFloat(hunger), WriteFloat(thirst), WriteFloat(exhaustion),
///   WriteFloat(ai_cx), WriteFloat(ai_cz)
fn parse_unit(c: &mut Cursor<&[u8]>, tf: bool) -> S2Result<S2Unit> {
    let id = read_u32_le(c)?;
    let typ = if tf {
        read_u16_le(c)? as u32
    } else {
        read_u8(c)? as u32
    };
    let x = read_f32_le(c)?;
    let y = read_f32_le(c)?;
    let z = read_f32_le(c)?;
    let yaw = read_f32_le(c)?;
    let health = read_f32_le(c)?;
    let health_max = read_f32_le(c)?;
    let hunger = read_f32_le(c)?;
    let thirst = read_f32_le(c)?;
    let exhaustion = read_f32_le(c)?;
    let ai_center_x = read_f32_le(c)?;
    let ai_center_z = read_f32_le(c)?;

    Ok(S2Unit {
        id,
        typ,
        x,
        y,
        z,
        yaw,
        health,
        health_max,
        hunger,
        thirst,
        exhaustion,
        ai_center_x,
        ai_center_z,
    })
}

/// Item record (e_save_map.bb lines 192-207):
///   WriteInt(id), If tf: WriteShort(typ)/WriteByte(typ),
///   WriteFloat(x), WriteFloat(y), WriteFloat(z), WriteFloat(yaw),
///   WriteFloat(health), WriteInt(count),
///   WriteByte(parent_class), WriteByte(parent_mode), WriteInt(parent_id)
fn parse_item(c: &mut Cursor<&[u8]>, tf: bool) -> S2Result<S2Item> {
    let id = read_u32_le(c)?;
    let typ = if tf {
        read_u16_le(c)? as u32
    } else {
        read_u8(c)? as u32
    };
    let x = read_f32_le(c)?;
    let y = read_f32_le(c)?;
    let z = read_f32_le(c)?;
    let yaw = read_f32_le(c)?;
    let health = read_f32_le(c)?;
    let count = read_u32_le(c)?;
    let parent_class = read_u8(c)?;
    let parent_mode = read_u8(c)?;
    let parent_id = read_u32_le(c)?;
    Ok(S2Item {
        id,
        typ,
        x,
        y,
        z,
        yaw,
        health,
        count,
        parent_class,
        parent_mode,
        parent_id,
    })
}

/// Info record (e_save_map.bb lines 243-251):
///   WriteInt(id), WriteByte(typ),
///   WriteFloat(x), WriteFloat(y), WriteFloat(z),
///   WriteFloat(pitch), WriteFloat(yaw),
///   WriteString(vars)
fn parse_info(c: &mut Cursor<&[u8]>) -> S2Result<S2Info> {
    let id = read_u32_le(c)?;
    let typ = read_u8(c)?;
    let x = read_f32_le(c)?;
    let y = read_f32_le(c)?;
    let z = read_f32_le(c)?;
    let pitch = read_f32_le(c)?;
    let yaw = read_f32_le(c)?;
    let vars = read_s2_string(c)?;
    Ok(S2Info {
        id,
        typ,
        x,
        y,
        z,
        pitch,
        yaw,
        vars,
    })
}

/// State record (e_save_map.bb lines 260-272):
///   WriteByte(typ), WriteByte(parent_class), WriteInt(parent_id),
///   WriteFloat(x), WriteFloat(y), WriteFloat(z),
///   WriteFloat(fx), WriteFloat(fy), WriteFloat(fz),
///   WriteInt(value), WriteFloat(value_f), WriteString(value_s)
fn parse_state(c: &mut Cursor<&[u8]>) -> S2Result<S2State> {
    let typ = read_u8(c)? as u32;
    let parent_class = read_u8(c)? as u32;
    let parent_id = read_u32_le(c)?;
    let x = read_f32_le(c)?;
    let y = read_f32_le(c)?;
    let z = read_f32_le(c)?;
    let fx = read_f32_le(c)?;
    let fy = read_f32_le(c)?;
    let fz = read_f32_le(c)?;
    let value = read_u32_le(c)?;
    let value_f = read_f32_le(c)?;
    let value_s = read_s2_string(c)?;
    Ok(S2State {
        typ,
        parent_class,
        parent_id,
        x,
        y,
        z,
        fx,
        fy,
        fz,
        value,
        value_f,
        value_s,
    })
}

/// Extension record (e_save_map.bb lines 314-327):
///   WriteByte(typ), WriteByte(parent_class), WriteInt(parent_id),
///   WriteInt(mode),
///   If mode=0: WriteString("") Else WriteString(key),
///   WriteString(value), WriteString(stuff)
fn parse_extension(c: &mut Cursor<&[u8]>) -> S2Result<S2Extension> {
    let typ = read_u8(c)?;
    let parent_class = read_u8(c)?;
    let parent_id = read_u32_le(c)?;
    let mode = read_u32_le(c)?;
    let key = if mode == 0 {
        // Script keys not saved (mode=0)
        let _empty = read_s2_string(c)?;
        String::new()
    } else {
        read_s2_string(c)?
    };
    let value = read_s2_string(c)?;
    let stuff = read_s2_string(c)?;
    Ok(S2Extension {
        typ,
        parent_class,
        parent_id,
        mode,
        key,
        value,
        stuff,
    })
}

// ---------------------------------------------------------------------------
// Utility
// ---------------------------------------------------------------------------

/// Load a `.s2` file from disk and parse it.
pub fn parse_s2_file(path: impl AsRef<std::path::Path>) -> S2Result<S2Map> {
    let data = std::fs::read(path.as_ref()).map_err(S2Error::Io)?;
    parse_s2(&data)
}

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

    #[test]
    fn test_read_s2_string_empty() {
        let data: &[u8] = &[0, 0, 0, 0];
        let mut c = Cursor::new(data);
        let s = read_s2_string(&mut c).unwrap();
        assert_eq!(s, "");
        assert_eq!(c.position(), 4);
    }

    #[test]
    fn test_read_s2_string_hello() {
        let data: &[u8] = &[5, 0, 0, 0, b'H', b'e', b'l', b'l', b'o'];
        let mut c = Cursor::new(data);
        let s = read_s2_string(&mut c).unwrap();
        assert_eq!(s, "Hello");
    }

    #[test]
    fn test_parse_quickslots() {
        let mut data = Vec::new();
        for _ in 0..10 {
            data.extend_from_slice(&[1, 0, 0, 0, b'0']);
        }
        let mut c = Cursor::new(data.as_slice());
        let slots = parse_quickslots(&mut c).unwrap();
        assert_eq!(slots.len(), 10);
        assert!(slots.iter().all(|s| s == "0"));
    }

    #[test]
    fn test_decode_password_empty() {
        let pw = decode_password("", 0);
        assert_eq!(pw, "");
    }

    #[test]
    fn test_decode_password_xor() {
        // "123":
        //   '1' (0x31) ^ 50 = 0x31 ^ 0x32 = 0x03
        //   '2' (0x32) ^ 50 = 0x32 ^ 0x32 = 0x00
        //   '3' (0x33) ^ 50 = 0x33 ^ 0x32 = 0x01
        let encoded = "\x03\x00\x01";
        let pw = decode_password(encoded, 50);
        assert_eq!(pw, "123");
    }

    /// Build a minimal valid .s2 file for testing.
    /// 16×16 terrain, black colormap, no entities, no password, lasttime extension.
    fn build_minimal_s2() -> Vec<u8> {
        let mut buf = Vec::new();

        // 1. Header (variable-sized, terminated by "###\r\n")
        // NOTE: © is single byte \xa9 (Windows-1252), not UTF-8 \xc2\xa9
        buf.extend_from_slice(b"### Stranded II Mapfile \xa9by Unreal Software 2004-2007\r\n");
        buf.extend_from_slice(b"1.0.0.1\r\n");
        buf.extend_from_slice(b"10 Jul 2026\r\n");
        buf.extend_from_slice(b"18:10:56\r\n");
        buf.extend_from_slice(b"default\r\n");
        buf.extend_from_slice(b"map\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"###\r\n");

        // 2. Minimap (20736 bytes of zeros)
        buf.extend(std::iter::repeat(0u8).take(20736));

        // 3. Password header: key=0, empty password → WriteByte(0) + WriteLine("")
        buf.push(0); // pwkey
        buf.extend_from_slice(b"\r\n"); // WriteLine("")

        // 4. Env vars
        buf.extend_from_slice(&1u32.to_le_bytes()); // day
        buf.push(9); // hour
        buf.push(0); // minute
        buf.push(3); // freezetime
        buf.extend_from_slice(&3u32.to_le_bytes()); // skybox "sky"
        buf.extend_from_slice(b"sky");
        buf.push(0); // multiplayer
        buf.push(0); // climate
        let music = b"amb_jungle.mp3";
        buf.extend_from_slice(&(music.len() as u32).to_le_bytes());
        buf.extend_from_slice(music);
        buf.extend_from_slice(&0u32.to_le_bytes()); // briefing (empty)
        buf.extend_from_slice(&[205, 210, 245, 0]); // fog
        buf.push(0); // extra

        // 5. Quickslots
        for _ in 0..10 {
            buf.extend_from_slice(&[1, 0, 0, 0, b'0']);
        }

        // 6. Colormap: dim=128, all zeros
        buf.extend_from_slice(&128u32.to_le_bytes());
        buf.extend(std::iter::repeat(0u8).take(128 * 128 * 3));

        // 7. Heightmap: size=16, 289 f32 values (0.447)
        buf.extend_from_slice(&16u32.to_le_bytes());
        for _ in 0..289 {
            buf.extend_from_slice(&0.447_f32.to_le_bytes());
        }

        // 8. Grass: (128+1)*(128+1) = 16641 bytes of zeros
        buf.extend(std::iter::repeat(0u8).take(16641));

        // 9. Footer: 0 entities, 1 extension (lasttime)
        buf.extend_from_slice(&0u32.to_le_bytes()); // objects
        buf.extend_from_slice(&0u32.to_le_bytes()); // units
        buf.extend_from_slice(&0u32.to_le_bytes()); // items
        buf.extend_from_slice(&0u32.to_le_bytes()); // infos
        buf.extend_from_slice(&0u32.to_le_bytes()); // states
        buf.extend_from_slice(&1u32.to_le_bytes()); // extensions

        // Extension: lasttime (mode=6)
        buf.push(0); // typ
        buf.push(0); // parent_class
        buf.extend_from_slice(&0u32.to_le_bytes()); // parent_id
        buf.extend_from_slice(&6u32.to_le_bytes()); // mode
        // mode=6, so key is saved
        buf.extend_from_slice(&8u32.to_le_bytes()); // key len
        buf.extend_from_slice(b"lasttime");
        buf.extend_from_slice(&0u32.to_le_bytes()); // value len (empty)
        buf.extend_from_slice(&5u32.to_le_bytes()); // stuff len
        buf.extend_from_slice(b"1,9,2"); // stuff

        // Trailer
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"### EOF Map File\r\n");
        buf.extend_from_slice(b"www.unrealsoftware.de\r\n");

        buf
    }

    #[test]
    fn test_parse_minimal_s2() {
        let data = build_minimal_s2();
        let result = parse_s2(&data);
        assert!(result.is_ok(), "parse failed: {:?}", result.err());
        let map = result.unwrap();
        assert_eq!(map.header.version, "1.0.0.1");
        assert_eq!(map.terrain_size, 16);
        assert!(map.objects.is_empty());
        assert!(map.units.is_empty());
        assert!(map.items.is_empty());
        assert!(map.infos.is_empty());
        assert!(map.states.is_empty());
        assert_eq!(map.extensions.len(), 1);
        assert_eq!(map.extensions[0].key, "lasttime");
    }

    #[test]
    fn test_parse_minimal_s2_with_password() {
        let mut buf = Vec::new();

        // Same header
        buf.extend_from_slice(b"### Stranded II Mapfile \xa9by Unreal Software 2004-2007\r\n");
        buf.extend_from_slice(b"1.0.0.1\r\n");
        buf.extend_from_slice(b"10 Jul 2026\r\n");
        buf.extend_from_slice(b"18:10:56\r\n");
        buf.extend_from_slice(b"default\r\n");
        buf.extend_from_slice(b"map\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"###\r\n");

        // Minimap
        buf.extend(std::iter::repeat(0u8).take(20736));

        // Password: key=50, "123" XOR 50:
        //   '1'(0x31)^50 = 0x03, '2'(0x32)^50 = 0x00, '3'(0x33)^50 = 0x01
        buf.push(50); // key
        buf.extend_from_slice(b"\x03\x00\x01\r\n"); // WriteLine with encoded pw + \r\n

        // Rest same as minimal
        buf.extend_from_slice(&1u32.to_le_bytes()); // day
        buf.push(9);
        buf.push(0);
        buf.push(3);
        buf.extend_from_slice(&3u32.to_le_bytes());
        buf.extend_from_slice(b"sky");
        buf.push(0);
        buf.push(0);
        let music = b"amb_jungle.mp3";
        buf.extend_from_slice(&(music.len() as u32).to_le_bytes());
        buf.extend_from_slice(music);
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&[205, 210, 245, 0]);
        buf.push(0);
        for _ in 0..10 {
            buf.extend_from_slice(&[1, 0, 0, 0, b'0']);
        }
        buf.extend_from_slice(&128u32.to_le_bytes());
        buf.extend(std::iter::repeat(0u8).take(128 * 128 * 3));
        buf.extend_from_slice(&16u32.to_le_bytes());
        for _ in 0..289 {
            buf.extend_from_slice(&0.447_f32.to_le_bytes());
        }
        buf.extend(std::iter::repeat(0u8).take(16641));
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&1u32.to_le_bytes());
        buf.push(0);
        buf.push(0);
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&6u32.to_le_bytes());
        buf.extend_from_slice(&8u32.to_le_bytes());
        buf.extend_from_slice(b"lasttime");
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&5u32.to_le_bytes());
        buf.extend_from_slice(b"1,9,2");
        buf.extend_from_slice(b"\r\n");
        buf.extend_from_slice(b"### EOF Map File\r\n");
        buf.extend_from_slice(b"www.unrealsoftware.de\r\n");

        let result = parse_s2(&buf);
        assert!(result.is_ok(), "parse failed: {:?}", result.err());
        let map = result.unwrap();
        assert_eq!(map.password.key, 50);
        assert_eq!(map.password.decoded, "123");
    }
}