libgm 0.8.0

A tool for unpacking and modding GameMaker games
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
// SPDX-License-Identifier: GPL-3.0-only
//
// TODO: clean up this file
use std::collections::HashMap;

use crate::gml::Code;
use crate::gml::ModernCodeData;
use crate::gml::instruction::AssetReference;
use crate::gml::instruction::BinaryOp;
use crate::gml::instruction::CodeVariable;
use crate::gml::instruction::ComparisonType;
use crate::gml::instruction::DataType;
use crate::gml::instruction::InstanceType;
use crate::gml::instruction::Instruction;
use crate::gml::instruction::PushValue;
use crate::gml::instruction::ReferenceType;
use crate::gml::instruction::VariableType;
use crate::gml::opcode;
use crate::prelude::*;
use crate::util::fmt::hexdump;
use crate::util::init::vec_with_capacity;
use crate::wad::GMVersion;
use crate::wad::chunk::gm_list_chunk;
use crate::wad::elem::GMElement;
use crate::wad::elem::function::Function;
use crate::wad::elem::string::Strings;
use crate::wad::elem::variable::Variable;
use crate::wad::load::reader::DataReader;
use crate::wad::reference::GMRef;
use crate::wad::save::writer::DataWriter;

#[derive(Debug, Clone, Default, PartialEq)]
pub struct Codes {
    pub elems: Vec<Code>,
}

impl Codes {
    /// Finds a code entry by its mangled name.
    ///
    /// This function exists for convenience, you should try to get code entries via
    /// scripts or game object events when possible for stability.
    pub fn ref_by_name(&self, name: &str, gm_strings: &Strings) -> Result<GMRef<Code>> {
        for (gmref, code) in self.element_refs() {
            let code_name = gm_strings.by_ref(code.name)?;
            if name == code_name {
                return Ok(gmref);
            }
        }
        Err(err!("Could not find code entry with name {name:?}"))
    }

    /// Finds a code entry by its mangled name.
    ///
    /// This function exists for convenience, you should try to get code entries via
    /// scripts or game object events when possible for stability.
    pub fn by_name(&self, name: &str, gm_strings: &Strings) -> Result<&Code> {
        self.ref_by_name(name, gm_strings).map(|gmref| self.by_ref(gmref).unwrap())
    }

    /// Finds a code entry by its mangled name.
    ///
    /// This function exists for convenience, you should try to get code entries via
    /// scripts or game object events when possible for stability.
    pub fn by_name_mut(&mut self, name: &str, gm_strings: &Strings) -> Result<&mut Code> {
        self.ref_by_name(name, gm_strings).map(|gmref| self.by_ref_mut(gmref).unwrap())
    }
}

gm_list_chunk!(CODE, Codes, Code);

impl GMElement for Codes {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        // This can happen with YYC.
        if reader.chunk.is_empty() {
            return Ok(Self { elems: vec![] });
        }

        let pointers: Vec<u32> = reader.read_simple_list()?;
        let count: usize = pointers.len();

        let Some(&first_pos) = pointers.first() else {
            return Ok(Self { elems: vec![] });
        };
        reader.cur_pos = first_pos;

        let mut elems: Vec<Code> = vec_with_capacity(count as u32)?;
        let mut instructions_ranges: Vec<(u32, u32)> = Vec::with_capacity(count);
        let mut codes_by_pos: HashMap<u32, GMRef<Code>> = HashMap::new();
        let mut last_code_entry_pos = reader.cur_pos;

        for pointer in pointers {
            reader.assert_pos(pointer, "Code")?;
            let name: GMRef<String> = reader.read_gm_string()?;
            let code_length = reader.read_u32()?;

            let instructions_start_pos;
            let instructions_end_pos;
            let modern_data: Option<ModernCodeData>;

            if reader.version < GMVersion::Wad15 {
                instructions_start_pos = reader.cur_pos; // Instructions are placed immediately after code metadata; how convenient!
                reader.cur_pos += code_length; // Skip over them; they will get decoded in the next loops
                instructions_end_pos = reader.cur_pos;
                modern_data = None;
            } else {
                let local_count = reader.read_u16()?;
                let arguments_count_raw = reader.read_u16()?;
                let arg_count: u16 = arguments_count_raw & 0x7FFF;
                let weird_local_flag: bool = arguments_count_raw & 0x8000 != 0;

                let position = reader.cur_pos;
                let instructions_start_offset = reader.read_i32()?;
                instructions_start_pos = position
                    .checked_add_signed(instructions_start_offset)
                    .ok_or("Instruction start position overflowed")?;

                let execution_offset = reader.read_u32()?;

                instructions_end_pos = instructions_start_pos
                    .checked_add(code_length)
                    .ok_or("Instruction end position overflowed")?;

                let data = ModernCodeData {
                    local_count,
                    arg_count,
                    weird_local_flag,
                    execution_offset,
                    parent: GMRef::none(),
                };
                modern_data = Some(data);
            }

            elems.push(Code { name, instructions: vec![], modern_data });

            instructions_ranges.push((instructions_start_pos, instructions_end_pos));
            last_code_entry_pos = reader.cur_pos;
        }

        for (i, (start, end)) in instructions_ranges.into_iter().enumerate() {
            let code: &mut Code = &mut elems[i];
            let length = end - start;

            // If WAD15+ and the instructions pointer is known, then it's a child code entry
            if length > 0
                && let Some(parent_code) = codes_by_pos.get(&start)
                && let Some(data) = &mut code.modern_data
            {
                data.parent = *parent_code;
                continue;
            }

            reader.cur_pos = start;
            // Estimated Size: https://discord.com/channels/566861759210586112/568625491876118528/1424403240258371615
            code.instructions = vec_with_capacity(length / 5)?;

            if length > 0 {
                // Update information to mark this entry as the root (if we have at least 1 instruction)
                codes_by_pos.insert(start, i.into());
            }

            while reader.cur_pos < end {
                let instruction = Instruction::deserialize(reader)
                    .ctx(|| {
                        format!(
                            "decoding Instruction #{} at position {}",
                            code.instructions.len(),
                            reader.cur_pos,
                        )
                    })
                    .ctx(|| format!("decoding code entry at position {start}"))?;
                code.instructions.push(instruction);
            }
        }

        reader.cur_pos = last_code_entry_pos;
        // Set pos to the supposed chunk end (since instructions are stored separately in WAD15+)

        Ok(Self { elems })
    }

    fn serialize(&self, writer: &mut DataWriter) -> Result<()> {
        writer.write_usize(self.elems.len())?;
        let pointer_list_pos: u32 = writer.pos();
        for _ in 0..self.elems.len() {
            writer.write_u32(0xDEAD_C0DE);
        }

        // WAD < 15 my beloved
        if writer.version() < GMVersion::Wad15 {
            for (i, code) in self.elems.iter().enumerate() {
                writer.patch_pointer_list(pointer_list_pos, i)?;
                writer.write_gm_string(code.name)?;
                let length_placeholder_pos = writer.pos();
                writer.write_u32(0xDEAD_C0DE);
                let start = writer.pos();

                // In WAD < 15, instructions are written immediately
                for (i, instruction) in code.instructions.iter().enumerate() {
                    writer.write_elem(instruction).ctx(|| format!("serializing code #{i}"))?;
                }

                let code_length = writer.pos() - start;
                writer.patch_u32(code_length, length_placeholder_pos)?;
            }
            return Ok(());
        }

        // In WAD 15+, the codes' instructions are written before the codes metadata
        let mut instructions_ranges: Vec<(u32, u32)> = Vec::with_capacity(self.elems.len());

        for (i, code) in self.elems.iter().enumerate() {
            if !code.is_root() {
                // If this is a child code entry, don't write instructions; just repeat last pointer
                let prev_range =
                    instructions_ranges.last().ok_or("First code entry is a child code entry")?;
                instructions_ranges.push(*prev_range);
                continue;
            }

            let start: u32 = writer.pos();
            for instruction in &code.instructions {
                writer.write_elem(instruction).ctx(|| format!("serializing code #{i}"))?;
            }
            let end: u32 = writer.pos();
            instructions_ranges.push((start, end));
        }

        for (i, code) in self.elems.iter().enumerate() {
            writer.patch_pointer_list(pointer_list_pos, i)?;
            let (start, end) = instructions_ranges[i];
            let length: u32 = end - start;
            let data: &ModernCodeData = code.modern_data.as_ref().ok_or_else(|| {
                format!("Code WAD15+ data not set in version {}", writer.version())
            })?;

            writer.write_gm_string(code.name)?;
            writer.write_u32(length);
            writer.write_u16(data.local_count);
            writer.write_u16(data.arg_count | if data.weird_local_flag { 0x8000 } else { 0 });
            let instructions_start_offset: i32 = start as i32 - writer.pos() as i32;
            writer.write_i32(instructions_start_offset);
            writer.write_u32(data.execution_offset);
        }

        Ok(())
    }
}

impl GMElement for Code {
    fn deserialize(_: &mut DataReader) -> Result<Self> {
        unimplemented!() // TODO: bruh i cant mutate context kill me
    }

    fn serialize(&self, _: &mut DataWriter) -> Result<()> {
        unimplemented!()
    }
}

impl GMElement for Instruction {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        let word = reader.read_u32()?;
        let mut opcode = ((word & 0xFF00_0000) >> 24) as u8;
        let b2 = ((word & 0x00FF_0000) >> 16) as u8;
        let b1 = ((word & 0x0000_FF00) >> 8) as u8;
        let b0 = (word & 0x0000_00FF) as u8;
        let mut b = [b0, b1, b2];

        if reader.version < GMVersion::Wad15 {
            if matches!(opcode, 0x10..=0x16) {
                // This is needed to preserve the comparison type for WAD < 15
                reader.assert_zero_b1(b)?;
                b[1] = opcode - 0x10;
            }
            opcode = opcode::old_to_new(opcode);
        }

        // log::debug!("{} // {:02X} {:02X} {:02X} {:02X}", reader.cur_pos-4, b[0], b[1], b[2], opcode);

        Ok(match opcode {
            opcode::CONV => {
                let types = reader.decode_double_type(b)?;
                Self::Convert { from: types[0], to: types[1] }
            }
            opcode::MUL => reader.decode_binary(b, BinaryOp::Multiply)?,
            opcode::DIV => reader.decode_binary(b, BinaryOp::Divide)?,
            opcode::REM => reader.decode_binary(b, BinaryOp::Remainder)?,
            opcode::MOD => reader.decode_binary(b, BinaryOp::Modulus)?,
            opcode::ADD => reader.decode_binary(b, BinaryOp::Add)?,
            opcode::SUB => reader.decode_binary(b, BinaryOp::Subtract)?,
            opcode::AND => reader.decode_binary(b, BinaryOp::And)?,
            opcode::OR => reader.decode_binary(b, BinaryOp::Or)?,
            opcode::XOR => reader.decode_binary(b, BinaryOp::Xor)?,
            opcode::NEG => Self::Negate { data_type: reader.decode_single_type(b)? },
            opcode::NOT => Self::Not { data_type: reader.decode_single_type(b)? },
            opcode::SHL => reader.decode_binary(b, BinaryOp::ShiftLeft)?,
            opcode::SHR => reader.decode_binary(b, BinaryOp::ShiftRight)?,
            opcode::SET => reader.decode_comparison(b).ctx("decoding Comparison Instruction")?,
            opcode::POP => reader.decode_pop(b).ctx("decoding Pop Instruction")?,
            opcode::DUP => reader.decode_duplicate(b).ctx("decoding Duplicate Instruction")?,
            opcode::RET => {
                let ctx = "decoding Return Instruction";
                let data_type = reader.decode_single_type(b).ctx(ctx)?;
                reader.assert_type(DataType::Variable, data_type).ctx(ctx)?;
                Self::Return
            }
            opcode::EXIT => {
                let ctx = "decoding Exit Instruction";
                let data_type = reader.decode_single_type(b).ctx(ctx)?;
                reader.assert_type(DataType::Int, data_type).ctx(ctx)?;
                Self::Exit
            }
            opcode::POPZ => {
                let data_type =
                    reader.decode_single_type(b).ctx("decoding Pop Discard Instruction")?;
                Self::PopDiscard { data_type }
            }
            opcode::B => Self::Branch { jump_offset: reader.decode_branch(b) },
            opcode::BT => Self::BranchIf { jump_offset: reader.decode_branch(b) },
            opcode::BF => Self::BranchUnless { jump_offset: reader.decode_branch(b) },
            opcode::PUSHENV => Self::PushWithContext { jump_offset: reader.decode_branch(b) },
            opcode::POPENV if b == [0x00, 0x00, 0xF0] => Self::PopWithContextExit,
            opcode::POPENV => Self::PopWithContext { jump_offset: reader.decode_branch(b) },
            opcode::PUSH => {
                let value = reader.decode_push(b).ctx("decoding Push Instruction")?;
                Self::Push { value }
            }
            opcode::PUSHL => {
                let variable = reader.decode_push_var(b).ctx("decoding Push Local Instruction")?;
                Self::PushLocal { variable }
            }
            opcode::PUSHG => {
                let variable = reader.decode_push_var(b).ctx("decoding Push Global Instruction")?;
                Self::PushGlobal { variable }
            }
            opcode::PUSHV => Self::PushBuiltin { variable: reader.decode_push_var(b)? },
            opcode::PUSHI => Self::PushImmediate { integer: reader.decode_pushim(b)? },
            opcode::CALL => reader.decode_call(b).ctx("decoding Call Instruction")?,
            opcode::CALLV => {
                let arg_count =
                    reader.decode_callvar(b).ctx("decoding Call Variable Instruction")?;
                Self::CallVariable { arg_count }
            }
            opcode::BREAK => reader.decode_extended(b).ctx("decoding Extended Instruction")?,
            _ => bail!(
                "Invalid Instruction Opcode {opcode} (0x{opcode:02X}) for instruction bytes [{}]",
                hexdump(&word.to_le_bytes())
            ),
        })
    }

    fn serialize(&self, writer: &mut DataWriter) -> Result<()> {
        let mut opcode: u8 = self.opcode();
        if writer.version() < GMVersion::Wad15 {
            opcode = opcode::new_to_old(opcode);
        }

        match *self {
            Self::Negate { data_type }
            | Self::Not { data_type }
            | Self::PopDiscard { data_type } => encode_single_type(writer, opcode, data_type),
            Self::Convert { from, to } => encode_double_type(writer, opcode, from, to),
            Self::Binary { op: _, lhs, rhs } => encode_double_type(writer, opcode, rhs, lhs),
            Self::Compare { lhs, rhs, comparison_type } => {
                encode_comparison(writer, opcode, rhs, lhs, comparison_type);
            }
            Self::Pop { variable, type1, type2 } => {
                encode_pop(writer, opcode, variable, type1, type2)?;
            }
            Self::PopSwap { is_array } => encode_popswap(writer, opcode, is_array),
            Self::Duplicate { data_type, count } => {
                encode_duplicate(writer, opcode, data_type, count);
            }
            Self::DuplicateSwap { data_type, size1, size2 } => {
                encode_dupswap(writer, opcode, data_type, size1, size2);
            }
            Self::Return => encode_single_type(writer, opcode, DataType::Variable),
            Self::Exit => encode_single_type(writer, opcode, DataType::Int),
            Self::Branch { jump_offset }
            | Self::BranchIf { jump_offset }
            | Self::BranchUnless { jump_offset }
            | Self::PushWithContext { jump_offset }
            | Self::PopWithContext { jump_offset } => encode_branch(writer, opcode, jump_offset),
            Self::PopWithContextExit => encode_popenv_exit(writer, opcode),
            Self::Push { value } => encode_push(writer, opcode, value)?,
            Self::PushLocal { variable }
            | Self::PushGlobal { variable }
            | Self::PushBuiltin { variable } => encode_pushvar(writer, opcode, variable)?,
            Self::PushImmediate { integer } => encode_pushim(writer, opcode, integer),
            Self::Call { function, arg_count } => encode_call(writer, opcode, function, arg_count)?,
            Self::CallVariable { arg_count } => encode_callvar(writer, opcode, arg_count),
            Self::CheckArrayIndex => encode_extended16(writer, opcode::extended::CHKINDEX),
            Self::PushArrayFinal => encode_extended16(writer, opcode::extended::PUSHAF),
            Self::PopArrayFinal => encode_extended16(writer, opcode::extended::POPAF),
            Self::PushArrayContainer => encode_extended16(writer, opcode::extended::PUSHAC),
            Self::SetArrayOwner => encode_extended16(writer, opcode::extended::SETOWNER),
            Self::HasStaticInitialized => encode_extended16(writer, opcode::extended::ISSTATICOK),
            Self::SetStaticInitialized => encode_extended16(writer, opcode::extended::SETSTATIC),
            Self::SaveArrayReference => encode_extended16(writer, opcode::extended::SAVEAREF),
            Self::RestoreArrayReference => encode_extended16(writer, opcode::extended::RESTOREAREF),
            Self::IsNullishValue => encode_extended16(writer, opcode::extended::ISNULLISH),
            Self::PushReference { asset_reference } => encode_pushref(writer, asset_reference)?,
        }

        Ok(())
    }
}

fn get_type1(b: [u8; 3]) -> Result<DataType> {
    DataType::decode(b[2] & 0xF)
}

fn get_type2(b: [u8; 3]) -> Result<DataType> {
    DataType::decode(b[2] >> 4)
}

/// This will not work for big endian (probably)
fn get_u24(b: [u8; 3]) -> u32 {
    let b0 = u32::from(b[0]);
    let b1 = u32::from(b[1]);
    let b2 = u32::from(b[2]);
    b0 | (b1 << 8) | (b2 << 16)
}

/// This will not work for big endian (probably)
fn get_u16(b: [u8; 3]) -> u16 {
    let b0 = u16::from(b[0]);
    let b1 = u16::from(b[1]);
    b0 | (b1 << 8)
}

impl DataReader<'_> {
    fn assert_type(&self, actual: DataType, expected: DataType) -> Result<()> {
        self.assert_data_type(actual, expected, "Instruction")
    }

    fn assert_zero_b0(&self, b: [u8; 3]) -> Result<()> {
        self.assert_int(b[0], 0, "Instruction byte #0")
    }

    fn assert_zero_b1(&self, b: [u8; 3]) -> Result<()> {
        self.assert_int(b[1], 0, "Instruction byte #1")
    }

    fn assert_zero_type2(&self, b: [u8; 3]) -> Result<()> {
        self.assert_int(b[2] >> 4, 0, "Instruction data type 2 (in byte #2)")
    }

    fn decode_single_type(&self, b: [u8; 3]) -> Result<DataType> {
        const CTX: &str = "decoding single type instruction";
        self.assert_zero_b0(b).ctx(CTX)?;
        self.assert_zero_b1(b).ctx(CTX)?;
        let data_type = get_type1(b).ctx(CTX)?;
        self.assert_zero_type2(b).ctx(CTX)?;
        Ok(data_type)
    }

    fn decode_double_type(&self, b: [u8; 3]) -> Result<[DataType; 2]> {
        const CTX: &str = "decoding double type instruction";
        self.assert_zero_b0(b).ctx(CTX)?;
        self.assert_zero_b1(b).ctx(CTX)?;
        let right = get_type1(b).ctx(CTX)?;
        let left = get_type2(b).ctx(CTX)?;
        Ok([right, left])
    }

    fn decode_binary(&self, b: [u8; 3], op: BinaryOp) -> Result<Instruction> {
        let types = self.decode_double_type(b)?;
        Ok(Instruction::Binary { op, lhs: types[1], rhs: types[0] })
    }

    fn decode_comparison(&self, b: [u8; 3]) -> Result<Instruction> {
        self.assert_zero_b0(b)?;
        let comparison_type = ComparisonType::from_u8(b[1])?;
        let rhs = get_type1(b)?;
        let lhs = get_type2(b)?;
        Ok(Instruction::Compare { lhs, rhs, comparison_type })
    }

    fn decode_pop(&mut self, b: [u8; 3]) -> Result<Instruction> {
        let raw_instance_type = get_u16(b) as i16;
        let type1: DataType = get_type1(b)?;
        let type2: DataType = get_type2(b)?;

        if type1 == DataType::Short {
            // PopSwap instruction
            self.assert_type(DataType::Variable, type2)?;

            let is_array = match raw_instance_type {
                5 => false,
                6 => true,
                n => bail!(
                    "Expected 5 or 6 for \"instance type\" (aka SwapExtra) of PopSwap \
                     Instruction, got {n}"
                ),
            };
            return Ok(Instruction::PopSwap { is_array });
        }

        let variable: CodeVariable = read_variable(self, raw_instance_type)?;
        Ok(Instruction::Pop { variable, type1, type2 })
    }

    fn decode_duplicate(&self, b: [u8; 3]) -> Result<Instruction> {
        let count: u8 = b[0];
        let mut size2: u8 = b[1];
        let data_type = get_type1(b)?;
        self.assert_zero_type2(b)?;

        if size2 == 0 {
            return Ok(Instruction::Duplicate { data_type, count });
        }

        // Duplicate Swap Instruction
        size2 = (size2 & 0x7F) >> 3;
        Ok(Instruction::DuplicateSwap { data_type, size1: count, size2 })
    }

    fn decode_branch(&self, b: [u8; 3]) -> i32 {
        let mut value: u32 = get_u24(b);
        if self.version >= GMVersion::Wad15 && (value & 0x40_0000) != 0 {
            value |= 0x80_0000;
        }
        if value & 0x80_0000 != 0 { (value | 0xFF00_0000) as i32 } else { value as i32 }
    }

    fn decode_push(&mut self, b: [u8; 3]) -> Result<PushValue> {
        let int16 = get_u16(b) as i16;
        let data_type = get_type1(b)?;
        self.assert_zero_type2(b)?;

        match data_type {
            DataType::Short => Ok(PushValue::Short(int16)),
            DataType::Int => {
                if let Some(&function) = self.function_occurrences.get(&self.cur_pos) {
                    self.cur_pos += 4; // Skip next occurrence offset
                    return Ok(PushValue::Function(function));
                }

                if let Some(&(variable, _)) = self.variable_occurrences.get(&self.cur_pos) {
                    self.cur_pos += 4; // Skip next occurrence offset
                    return Ok(PushValue::Variable(CodeVariable {
                        variable,
                        ref_type: ReferenceType::Normal,
                        instance_type: InstanceType::Self_,
                        is_int32: true,
                    }));
                }

                self.read_i32().map(PushValue::Int)
            }
            DataType::Long => self.read_i64().map(PushValue::Long),
            DataType::Double => self.read_f64().map(PushValue::Double),
            DataType::Bool => self.read_bool32().map(PushValue::Bool),
            DataType::String => {
                // yes, strings in Push instructions are encoded as ID instead of pointer for some reason
                let string: GMRef<String> = self.read_resource_by_id()?;
                Ok(PushValue::String(string))
            }
            DataType::Variable => read_variable(self, int16).map(PushValue::Variable),
        }
    }

    fn decode_push_var(&mut self, b: [u8; 3]) -> Result<CodeVariable> {
        let raw_instance_type = get_u16(b) as i16;
        let data_type: DataType = get_type1(b)?;
        self.assert_zero_type2(b)?;
        self.assert_type(DataType::Variable, data_type)?;
        read_variable(self, raw_instance_type)
    }

    fn decode_pushim(&self, b: [u8; 3]) -> Result<i16> {
        let integer = get_u16(b) as i16;
        let data_type = get_type1(b)?;
        self.assert_zero_type2(b)?;
        self.assert_type(DataType::Short, data_type)?;
        Ok(integer)
    }

    fn decode_call(&mut self, b: [u8; 3]) -> Result<Instruction> {
        let arg_count: u16 = get_u16(b);
        let data_type: DataType = get_type1(b)?;
        self.assert_zero_type2(b)?;
        self.assert_type(DataType::Int, data_type)?;
        let Some(&function) = self.function_occurrences.get(&self.cur_pos) else {
            bail!(
                "Could not find any function with absolute occurrence position {} in map with \
                 length {} while decoding Call Instruction",
                self.cur_pos,
                self.function_occurrences.len(),
            )
        };
        self.cur_pos += 4; // Skip next occurrence offset
        Ok(Instruction::Call { function, arg_count })
    }

    fn decode_callvar(&self, b: [u8; 3]) -> Result<u16> {
        let argument_count: u16 = get_u16(b);
        let data_type: DataType = get_type1(b)?;
        self.assert_zero_type2(b)?;
        self.assert_type(DataType::Variable, data_type)?;
        Ok(argument_count)
    }

    fn decode_extended(&mut self, b: [u8; 3]) -> Result<Instruction> {
        use DataType::Int;
        use DataType::Short;
        #[allow(clippy::wildcard_imports)]
        use opcode::extended::*;

        let kind = get_u16(b) as i16;
        let data_type = DataType::decode(b[2] & 0xF)?;
        self.assert_zero_type2(b)?;

        let instruction = match (data_type, kind) {
            (Short, CHKINDEX) => Instruction::CheckArrayIndex,
            (Short, PUSHAF) => Instruction::PushArrayFinal,
            (Short, POPAF) => Instruction::PopArrayFinal,
            (Short, PUSHAC) => Instruction::PushArrayContainer,
            (Short, SETOWNER) => Instruction::SetArrayOwner,
            (Short, ISSTATICOK) => Instruction::HasStaticInitialized,
            (Short, SETSTATIC) => Instruction::SetStaticInitialized,
            (Short, SAVEAREF) => Instruction::SaveArrayReference,
            (Short, RESTOREAREF) => Instruction::RestoreArrayReference,
            (Short, ISNULLISH) => Instruction::IsNullishValue,
            (Int, PUSHREF) => {
                let asset_reference = AssetReference::deserialize(self)
                    .ctx("decoding PushReference Extended Instruction")?;
                Instruction::PushReference { asset_reference }
            }
            _ => bail!("Invalid Extended Instruction with data type {data_type:?} and kind {kind}"),
        };

        Ok(instruction)
    }
}

fn encode_single_type(writer: &mut DataWriter, opcode: u8, data_type: DataType) {
    writer.write_u16(0);
    writer.write_u8(data_type.encode());
    writer.write_u8(opcode);
}

fn encode_double_type(writer: &mut DataWriter, opcode: u8, type1: DataType, type2: DataType) {
    writer.write_u16(0);
    writer.write_u8(type1.encode() | type2.encode() << 4);
    writer.write_u8(opcode);
}

fn encode_comparison(
    writer: &mut DataWriter,
    mut opcode: u8,
    type1: DataType,
    type2: DataType,
    comparison_type: ComparisonType,
) {
    let mut comparison_type = comparison_type.as_u8();
    if writer.version() < GMVersion::Wad15 {
        opcode = 0x10 + comparison_type;
        comparison_type = 0;
    }
    writer.write_u8(0);
    writer.write_u8(comparison_type);
    writer.write_u8(type1.encode() | type2.encode() << 4);
    writer.write_u8(opcode);
}

fn encode_pop(
    writer: &mut DataWriter,
    opcode: u8,
    variable: CodeVariable,
    type1: DataType,
    type2: DataType,
) -> Result<()> {
    let instr_pos: u32 = writer.pos();
    writer.write_i16(variable.instance_type.encode(variable.ref_type));
    writer.write_u8(type1.encode() | type2.encode() << 4);
    writer.write_u8(opcode);
    write_variable_occurrence(writer, variable.variable, instr_pos, variable.ref_type)
        .ctx("writing variable occurrence for pop instruction")?;
    Ok(())
}

fn encode_popswap(writer: &mut DataWriter, opcode: u8, array: bool) {
    writer.write_i16(if array { 6 } else { 5 });
    writer.write_u8(DataType::Int.encode() | DataType::Variable.encode() << 4);
    writer.write_u8(opcode);
}

fn encode_duplicate(writer: &mut DataWriter, opcode: u8, data_type: DataType, size: u8) {
    writer.write_u8(size);
    writer.write_u8(0);
    writer.write_u8(data_type.encode());
    writer.write_u8(opcode);
}

fn encode_dupswap(writer: &mut DataWriter, opcode: u8, data_type: DataType, size1: u8, size2: u8) {
    writer.write_u8(size1);
    writer.write_u8((size2 << 3) | 0x80);
    writer.write_u8(data_type.encode());
    writer.write_u8(opcode);
}

fn encode_branch(writer: &mut DataWriter, opcode: u8, jump_offset: i32) {
    let mut value = (jump_offset as u32) & 0x00FF_FFFF;
    if writer.version() >= GMVersion::Wad15 && (value & 0x80_0000) != 0 {
        value &= !0x80_0000;
        value |= 0x40_0000;
    }
    writer.write_u8((value & 0xFF) as u8);
    writer.write_u8(((value >> 8) & 0xFF) as u8);
    writer.write_u8(((value >> 16) & 0xFF) as u8);
    writer.write_u8(opcode);
}

fn encode_popenv_exit(writer: &mut DataWriter, opcode: u8) {
    writer.write_u8(0x00);
    writer.write_u8(0x00);
    writer.write_u8(0xF0);
    writer.write_u8(opcode);
}

fn encode_push(writer: &mut DataWriter, opcode: u8, value: PushValue) -> Result<()> {
    let instr_pos: u32 = writer.pos();
    writer.write_i16(match value {
        PushValue::Short(int16) => int16,
        PushValue::Variable(variable) => variable.instance_type.encode(variable.ref_type),
        _ => 0,
    });

    writer.write_u8(value.data_type().encode());
    writer.write_u8(opcode);

    match value {
        PushValue::Short(_) => {} // Nothing because it was already written inside the instruction
        PushValue::Int(int) => writer.write_i32(int),
        PushValue::Long(long) => writer.write_i64(long),
        PushValue::Double(double) => writer.write_f64(double),
        PushValue::Bool(boolean) => writer.write_bool32(boolean),
        PushValue::String(string) => writer.write_resource_id(string),
        PushValue::Variable(code_variable) => write_variable_occurrence(
            writer,
            code_variable.variable,
            instr_pos,
            code_variable.ref_type,
        )
        .ctx("writing variable occurrence for push instruction")?,
        PushValue::Function(func_ref) => write_function_occurrence(writer, func_ref, instr_pos)
            .ctx("writing function occurrence for push instruction")?,
    }
    Ok(())
}

fn encode_pushvar(writer: &mut DataWriter, opcode: u8, variable: CodeVariable) -> Result<()> {
    let instr_pos = writer.pos();
    writer.write_i16(variable.instance_type.encode(variable.ref_type));
    writer.write_u8(DataType::Variable.encode());
    writer.write_u8(opcode);

    write_variable_occurrence(writer, variable.variable, instr_pos, variable.ref_type)
        .ctx("writing variable occurrence for a push variable instruction")?;
    Ok(())
}

fn encode_pushim(writer: &mut DataWriter, opcode: u8, integer: i16) {
    writer.write_i16(integer);
    writer.write_u8(DataType::Short.encode());
    writer.write_u8(opcode);
}

fn encode_call(
    writer: &mut DataWriter,
    opcode: u8,
    function: GMRef<Function>,
    argument_count: u16,
) -> Result<()> {
    let instr_pos: u32 = writer.pos();
    writer.write_u16(argument_count);
    writer.write_u8(DataType::Int.encode());
    writer.write_u8(opcode);

    write_function_occurrence(writer, function, instr_pos)
        .ctx("writing function occurrence for call instruction")?;
    Ok(())
}

fn encode_callvar(writer: &mut DataWriter, opcode: u8, argument_count: u16) {
    writer.write_u16(argument_count);
    writer.write_u8(DataType::Variable.encode());
    writer.write_u8(opcode);
}

fn encode_extended16(writer: &mut DataWriter, extended_kind: i16) {
    writer.write_i16(extended_kind);
    writer.write_u8(DataType::Short.encode());
    writer.write_u8(opcode::BREAK);
}

fn encode_pushref(writer: &mut DataWriter, asset_reference: AssetReference) -> Result<()> {
    writer.write_i16(opcode::extended::PUSHREF);
    writer.write_u8(DataType::Int.encode());
    writer.write_u8(opcode::BREAK);
    writer.write_elem(&asset_reference)
}

impl GMElement for AssetReference {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        if let Some(func) = reader.function_occurrences.get(&reader.cur_pos) {
            reader.cur_pos += 4; // Consume next occurrence offset
            return Ok(Self::Function(*func));
        }

        let raw = reader.read_u32()?;
        if reader.version >= GMVersion::GM2024_4 {
            Self::decode(raw)
        } else {
            Self::decode_old(raw)
        }
    }

    fn serialize(&self, writer: &mut DataWriter) -> Result<()> {
        if let Self::Function(func_ref) = *self {
            let pos = writer.pos() - 4;
            return write_function_occurrence(writer, func_ref, pos)
                .ctx("writing function occurrence for pushref instruction");
        }

        let raw =
            if writer.version() >= GMVersion::GM2024_4 { self.encode() } else { self.encode_old() };

        writer.write_u32(raw);
        Ok(())
    }
}

fn read_variable(reader: &mut DataReader, raw_instance_type: i16) -> Result<CodeVariable> {
    const CTX: &str = "decoding variable reference chain";
    let occurrence_position: u32 = reader.cur_pos;
    let raw_value = reader.read_u32()?;

    let (variable, variable_type): (GMRef<Variable>, VariableType) = *reader
        .variable_occurrences
        .get(&occurrence_position)
        .ok_or_else(|| {
            format!("Could not find variable with occurrence position {occurrence_position}")
        })
        .ctx(CTX)?;

    let ref_type = (raw_value >> 24) as u8;
    let ref_type = ReferenceType::decode(ref_type).ctx(CTX)?;

    let instance_type: InstanceType =
        if matches!(ref_type, ReferenceType::Normal | ReferenceType::Instance) {
            InstanceType::decode(raw_instance_type, ref_type).ctx(CTX)?
        } else if variable_type == VariableType::Builtin {
            InstanceType::Argument
        } else {
            variable_type.as_instance_type()
        };

    Ok(CodeVariable { variable, ref_type, instance_type, is_int32: false })
}

fn write_variable_occurrence(
    writer: &mut DataWriter,
    variable_ref: GMRef<Variable>,
    occurrence_pos: u32,
    ref_type: ReferenceType,
) -> Result<()> {
    if occurrence_pos & 0xF800_0000 != 0 {
        // (This will basically never happen.)
        let pos = occurrence_pos;
        bail!("Occurrence position {pos} (0x{pos:08X}) is too large (max is 0x07FFFFFF)");
    }

    let var = writer.gm_data.variables.by_ref(variable_ref)?;
    // Since the variable resolved successfully, we don't have to check bounds again.
    let occurrences = &mut writer.variable_occurrences[variable_ref.index as usize];
    let last: Option<u32> = occurrences.last().copied();

    let ref_type_raw = u32::from(ref_type.encode());
    occurrences.push(occurrence_pos | ref_type_raw << 24);

    if let Some(last_chain_value) = last {
        // Replace the last written value (name string id) of the occurrence chain
        // with the offset to its next occurrence (this one).

        // The `last_chain_value` also has the ref type encoded.
        // (This is an optimization to save space in `writer.variable_occurrences`)
        let last_occurrence_pos = last_chain_value & 0x07FF_FFFF;
        let offset: u32 = occurrence_pos - last_occurrence_pos;
        let value = offset | last_chain_value & 0xF800_0000;
        writer.patch_u32(value, last_occurrence_pos + 4)?;
    }

    // Write the Name String ID (the index of the string, not a pointer) together with the reference type.
    // This value will be overwritten by the above code, unless this is the last occurrence of that variable.
    // This is exactly what we want: the last value of the occurrence chain needs to store the name string id (since there is no next occurrence offset).
    let ref_type_raw = ref_type.encode() as u32;
    let name_string_id = var.name.index as u32;
    writer.write_u32(name_string_id | ref_type_raw << 24);

    Ok(())
}

fn write_function_occurrence(
    writer: &mut DataWriter,
    func_ref: GMRef<Function>,
    occurrence_pos: u32,
) -> Result<()> {
    // see write_variable_occurrence for comments

    let func = writer.gm_data.functions.by_ref(func_ref)?;
    let occurrences = &mut writer.function_occurrences[func_ref.index as usize];
    let last: Option<u32> = occurrences.last().copied();
    occurrences.push(occurrence_pos);

    if let Some(last_occurrence_pos) = last {
        let offset: u32 = occurrence_pos - last_occurrence_pos;
        if offset & 0xF800_0000 != 0 {
            bail!("Occurrence offset {offset} (0x{offset:08X}) is too large (max is 0x07FFFFFF)");
        }
        writer.patch_u32(offset, last_occurrence_pos + 4)?;
    }

    writer.write_u32(func.name.index as u32);
    Ok(())
}

/// Check whether this data file was generated with `YYC` (`YoYo Games Compiler`).
/// Should that be the case, the `CODE`, `VARI` and `FUNC` chunks will be empty
/// (or not exist, depending on the WAD version).
pub(crate) fn check_yyc(reader: &DataReader) -> Result<bool> {
    use crate::wad::chunk::ChunkName::CODE;
    use crate::wad::chunk::ChunkName::FUNC;
    use crate::wad::chunk::ChunkName::VARI;

    // If the CODE chunk doesn't exist; the data file was compiled with YYC.
    let Some(code) = reader.chunks.get(CODE) else {
        if reader.chunks.contains(VARI) {
            bail!("Chunk VARI exists but CODE doesn't");
        }

        if reader.chunks.contains(FUNC) {
            bail!("Chunk FUNC exists but CODE and VARI don't");
        }

        return Ok(true);
    };

    let vari = reader.chunks.get(VARI).ok_or("Chunk CODE exists but VARI doesn't")?;

    let func = reader.chunks.get(FUNC).ok_or("Chunk CODE and VARI exist but FUNC doesn't")?;

    // If the CODE chunk exists but is completely empty,
    // the data file was compiled with YYC before WAD 17.
    if !code.is_empty() {
        return Ok(false);
    }

    if reader.version > GMVersion::Wad16 {
        log::warn!("Empty, but existent CODE chunk after WAD 16");
    }

    if !vari.is_empty() {
        bail!("Chunk CODE is empty but VARI is not");
    }

    if !func.is_empty() {
        bail!("Chunk CODE and VARI are empty but FUNC is not");
    }

    Ok(true)
}