-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathUndertaleChunks.cs
More file actions
2868 lines (2407 loc) · 107 KB
/
UndertaleChunks.cs
File metadata and controls
2868 lines (2407 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using UndertaleModLib.Models;
using UndertaleModLib.Util;
using static UndertaleModLib.Models.UndertaleRoom;
namespace UndertaleModLib
{
public class UndertaleChunkFORM : UndertaleChunk
{
public override string Name => "FORM";
/// <summary>
/// Lookup from a chunk name to its loaded instance.
/// </summary>
public Dictionary<string, UndertaleChunk> Chunks = new();
/// <summary>
/// Lookup from a chunk type to its loaded instance.
/// </summary>
public Dictionary<Type, UndertaleChunk> ChunksTypeDict = new();
/// <summary>
/// Constructors for all chunk types.
/// </summary>
public static readonly IReadOnlyDictionary<string, Func<UndertaleChunk>> ChunkConstructors = new Dictionary<string, Func<UndertaleChunk>>()
{
{ "GEN8", () => new UndertaleChunkGEN8() },
{ "OPTN", () => new UndertaleChunkOPTN() },
{ "LANG", () => new UndertaleChunkLANG() },
{ "EXTN", () => new UndertaleChunkEXTN() },
{ "SOND", () => new UndertaleChunkSOND() },
{ "AGRP", () => new UndertaleChunkAGRP() },
{ "SPRT", () => new UndertaleChunkSPRT() },
{ "BGND", () => new UndertaleChunkBGND() },
{ "PATH", () => new UndertaleChunkPATH() },
{ "SCPT", () => new UndertaleChunkSCPT() },
{ "GLOB", () => new UndertaleChunkGLOB() },
{ "GMEN", () => new UndertaleChunkGMEN() },
{ "SHDR", () => new UndertaleChunkSHDR() },
{ "FONT", () => new UndertaleChunkFONT() },
{ "TMLN", () => new UndertaleChunkTMLN() },
{ "OBJT", () => new UndertaleChunkOBJT() },
{ "ROOM", () => new UndertaleChunkROOM() },
{ "UILR", () => new UndertaleChunkUILR() },
{ "DAFL", () => new UndertaleChunkDAFL() },
{ "EMBI", () => new UndertaleChunkEMBI() },
{ "TPAG", () => new UndertaleChunkTPAG() },
{ "TGIN", () => new UndertaleChunkTGIN() },
{ "CODE", () => new UndertaleChunkCODE() },
{ "VARI", () => new UndertaleChunkVARI() },
{ "FUNC", () => new UndertaleChunkFUNC() },
{ "STRG", () => new UndertaleChunkSTRG() },
{ "TXTR", () => new UndertaleChunkTXTR() },
{ "AUDO", () => new UndertaleChunkAUDO() },
{ "ACRV", () => new UndertaleChunkACRV() },
{ "SEQN", () => new UndertaleChunkSEQN() },
{ "TAGS", () => new UndertaleChunkTAGS() },
{ "FEAT", () => new UndertaleChunkFEAT() },
{ "FEDS", () => new UndertaleChunkFEDS() },
{ "PSEM", () => new UndertaleChunkPSEM() },
{ "PSYS", () => new UndertaleChunkPSYS() },
};
public UndertaleChunkGEN8 GEN8 => Chunks.GetValueOrDefault("GEN8") as UndertaleChunkGEN8;
public UndertaleChunkOPTN OPTN => Chunks.GetValueOrDefault("OPTN") as UndertaleChunkOPTN;
public UndertaleChunkLANG LANG => Chunks.GetValueOrDefault("LANG") as UndertaleChunkLANG;
public UndertaleChunkEXTN EXTN => Chunks.GetValueOrDefault("EXTN") as UndertaleChunkEXTN;
public UndertaleChunkSOND SOND => Chunks.GetValueOrDefault("SOND") as UndertaleChunkSOND;
public UndertaleChunkAGRP AGRP => Chunks.GetValueOrDefault("AGRP") as UndertaleChunkAGRP;
public UndertaleChunkSPRT SPRT => Chunks.GetValueOrDefault("SPRT") as UndertaleChunkSPRT;
public UndertaleChunkBGND BGND => Chunks.GetValueOrDefault("BGND") as UndertaleChunkBGND;
public UndertaleChunkPATH PATH => Chunks.GetValueOrDefault("PATH") as UndertaleChunkPATH;
public UndertaleChunkSCPT SCPT => Chunks.GetValueOrDefault("SCPT") as UndertaleChunkSCPT;
public UndertaleChunkGLOB GLOB => Chunks.GetValueOrDefault("GLOB") as UndertaleChunkGLOB;
public UndertaleChunkGMEN GMEN => Chunks.GetValueOrDefault("GMEN") as UndertaleChunkGMEN;
public UndertaleChunkSHDR SHDR => Chunks.GetValueOrDefault("SHDR") as UndertaleChunkSHDR;
public UndertaleChunkFONT FONT => Chunks.GetValueOrDefault("FONT") as UndertaleChunkFONT;
public UndertaleChunkTMLN TMLN => Chunks.GetValueOrDefault("TMLN") as UndertaleChunkTMLN;
public UndertaleChunkOBJT OBJT => Chunks.GetValueOrDefault("OBJT") as UndertaleChunkOBJT;
public UndertaleChunkROOM ROOM => Chunks.GetValueOrDefault("ROOM") as UndertaleChunkROOM;
public UndertaleChunkUILR UILR => Chunks.GetValueOrDefault("UILR") as UndertaleChunkUILR;
public UndertaleChunkDAFL DAFL => Chunks.GetValueOrDefault("DAFL") as UndertaleChunkDAFL;
public UndertaleChunkEMBI EMBI => Chunks.GetValueOrDefault("EMBI") as UndertaleChunkEMBI;
public UndertaleChunkTPAG TPAG => Chunks.GetValueOrDefault("TPAG") as UndertaleChunkTPAG;
public UndertaleChunkTGIN TGIN => Chunks.GetValueOrDefault("TGIN") as UndertaleChunkTGIN;
public UndertaleChunkCODE CODE => Chunks.GetValueOrDefault("CODE") as UndertaleChunkCODE;
public UndertaleChunkVARI VARI => Chunks.GetValueOrDefault("VARI") as UndertaleChunkVARI;
public UndertaleChunkFUNC FUNC => Chunks.GetValueOrDefault("FUNC") as UndertaleChunkFUNC;
public UndertaleChunkSTRG STRG => Chunks.GetValueOrDefault("STRG") as UndertaleChunkSTRG;
public UndertaleChunkTXTR TXTR => Chunks.GetValueOrDefault("TXTR") as UndertaleChunkTXTR;
public UndertaleChunkAUDO AUDO => Chunks.GetValueOrDefault("AUDO") as UndertaleChunkAUDO;
// GMS 2.3+ for the below chunks
public UndertaleChunkACRV ACRV => Chunks.GetValueOrDefault("ACRV") as UndertaleChunkACRV;
public UndertaleChunkSEQN SEQN => Chunks.GetValueOrDefault("SEQN") as UndertaleChunkSEQN;
public UndertaleChunkTAGS TAGS => Chunks.GetValueOrDefault("TAGS") as UndertaleChunkTAGS;
public UndertaleChunkFEAT FEAT => Chunks.GetValueOrDefault("FEAT") as UndertaleChunkFEAT;
// GMS 2.3.6+
public UndertaleChunkFEDS FEDS => Chunks.GetValueOrDefault("FEDS") as UndertaleChunkFEDS;
// GM 2023.2+
public UndertaleChunkPSEM PSEM => Chunks.GetValueOrDefault("PSEM") as UndertaleChunkPSEM;
public UndertaleChunkPSYS PSYS => Chunks.GetValueOrDefault("PSYS") as UndertaleChunkPSYS;
internal override void SerializeChunk(UndertaleWriter writer)
{
foreach (var chunk in Chunks)
{
writer.Write(chunk.Value);
}
}
internal override void UnserializeChunk(UndertaleReader reader)
{
long startPos = reader.Position;
// First, find the last chunk in the file because of padding changes
// (also, calculate all present chunks while we're at it)
reader.AllChunkNames = new List<string>();
string lastChunk = "";
while (reader.Position < reader.Length)
{
lastChunk = reader.ReadChars(4);
reader.AllChunkNames.Add(lastChunk);
uint length = reader.ReadUInt32();
reader.Position += length;
}
reader.LastChunkName = lastChunk;
reader.Position = startPos;
// Now, parse the chunks
while (reader.Position < startPos + Length)
{
UndertaleChunk chunk = reader.ReadUndertaleChunk();
if (chunk is not null)
{
if (!Chunks.ContainsKey(chunk.Name))
{
throw new IOException($"Missed chunk on object count pass \"{chunk.Name}\"");
}
if (reader.ReadOnlyGEN8 && chunk.Name == "GEN8")
{
return;
}
}
}
if (reader.undertaleData.IsVersionAtLeast(2023, 1) &&
reader.undertaleData.GeneralInfo.Branch == UndertaleGeneralInfo.BranchType.Pre2022_0)
{
reader.undertaleData.SetLTS(true);
}
}
internal override uint UnserializeObjectCount(UndertaleReader reader)
{
uint totalCount = 0;
long startPos = reader.Position;
reader.AllChunkNames = new List<string>();
while (reader.Position < reader.Length)
{
string chunkName = reader.ReadChars(4);
reader.AllChunkNames.Add(chunkName);
uint length = reader.ReadUInt32();
reader.Position += length;
}
reader.Position = startPos;
// Read some basic data from GEN8 for version info, etc.
if (reader.AllChunkNames[0] == "GEN8")
{
UndertaleChunkGEN8 gen8Chunk = new();
gen8Chunk.UnserializeGeneralData(reader);
Chunks.Add(gen8Chunk.Name, gen8Chunk);
ChunksTypeDict.Add(gen8Chunk.GetType(), gen8Chunk);
reader.Position = startPos;
}
// Read object counts for all chunks
while (reader.Position < startPos + Length)
{
(uint count, UndertaleChunk chunk) = reader.CountChunkChildObjects();
totalCount += count;
// Don't register a new chunk for GEN8 specifically
if (chunk.Name != "GEN8")
{
Chunks.Add(chunk.Name, chunk);
ChunksTypeDict.Add(chunk.GetType(), chunk);
}
}
return totalCount;
}
}
public class UndertaleChunkGEN8 : UndertaleSingleChunk<UndertaleGeneralInfo>
{
public override string Name => "GEN8";
public void UnserializeGeneralData(UndertaleReader reader)
{
Object = new UndertaleGeneralInfo();
reader.Position += 8; // Chunk name + length
reader.Position++; // "IsDebuggerDisabled"
Object.BytecodeVersion = reader.ReadByte();
reader.undertaleData.UnsupportedBytecodeVersion
= Object.BytecodeVersion < 13 || Object.BytecodeVersion > 17;
reader.Bytecode14OrLower = Object.BytecodeVersion <= 14;
reader.Position += 42;
Object.Major = reader.ReadUInt32();
Object.Minor = reader.ReadUInt32();
Object.Release = reader.ReadUInt32();
Object.Build = reader.ReadUInt32();
var readVer = (Object.Major, Object.Minor, Object.Release, Object.Build, Object.Branch);
var detectedVer = UndertaleGeneralInfo.TestForCommonGMSVersions(reader, readVer);
(Object.Major, Object.Minor, Object.Release, Object.Build, Object.Branch) = detectedVer;
}
}
public class UndertaleChunkOPTN : UndertaleSingleChunk<UndertaleOptions>
{
public override string Name => "OPTN";
}
public class UndertaleChunkLANG : UndertaleSingleChunk<UndertaleLanguage>
{
public override string Name => "LANG";
internal override uint UnserializeObjectCount(UndertaleReader reader)
{
return 1;
}
}
public class UndertaleChunkEXTN : UndertaleListChunk<UndertaleExtension>
{
public override string Name => "EXTN";
public List<byte[]> productIdData = new List<byte[]>();
private bool checkedFor2022_6 = false;
private bool checkedFor2023_4 = false;
private void CheckFor2022_6(UndertaleReader reader)
{
if (!reader.undertaleData.IsVersionAtLeast(2, 3) || reader.undertaleData.IsVersionAtLeast(2022, 6))
{
checkedFor2022_6 = true;
return;
}
bool definitely2022_6 = true;
long returnPosition = reader.AbsPosition;
int extCount = reader.ReadInt32();
if (extCount > 0)
{
uint firstExtPtr = reader.ReadUInt32();
uint firstExtEndPtr = (extCount >= 2) ? reader.ReadUInt32() /* second ptr */ : (uint)(returnPosition + this.Length);
reader.AbsPosition = firstExtPtr + 12;
uint newPointer1 = reader.ReadUInt32();
uint newPointer2 = reader.ReadUInt32();
if (newPointer1 != reader.AbsPosition)
definitely2022_6 = false; // first pointer mismatch
else if (newPointer2 <= reader.AbsPosition || newPointer2 >= (returnPosition + this.Length))
definitely2022_6 = false; // second pointer out of bounds
else
{
// Check ending position
reader.AbsPosition = newPointer2;
uint optionCount = reader.ReadUInt32();
if (optionCount > 0)
{
long newOffsetCheck = reader.AbsPosition + (4 * (optionCount - 1));
if (newOffsetCheck >= (returnPosition + this.Length))
{
// Option count would place us out of bounds
definitely2022_6 = false;
}
else
{
reader.Position += (4 * (optionCount - 1));
newOffsetCheck = reader.ReadUInt32() + 12; // jump past last option
if (newOffsetCheck >= (returnPosition + this.Length))
{
// Pointer list element would place us out of bounds
definitely2022_6 = false;
}
else
{
reader.AbsPosition = (uint)newOffsetCheck;
}
}
}
if (definitely2022_6)
{
if (extCount == 1)
{
reader.Position += 16; // skip GUID data (only one of them)
if (reader.AbsPosition % 16 != 0)
reader.Position += 16 - (reader.AbsPosition % 16); // align to chunk end
}
if (reader.AbsPosition != firstExtEndPtr)
definitely2022_6 = false;
}
}
}
else
definitely2022_6 = false;
reader.AbsPosition = returnPosition;
if (definitely2022_6)
reader.undertaleData.SetGMS2Version(2022, 6);
checkedFor2022_6 = true;
}
private void CheckFor2023_4(UndertaleReader reader)
{
if (!reader.undertaleData.IsVersionAtLeast(2022, 6) || reader.undertaleData.IsVersionAtLeast(2023, 4))
{
checkedFor2023_4 = true;
return;
}
long returnPosition = reader.Position;
int extCount = reader.ReadInt32();
if (extCount > 0)
{
// Go to the first extension
reader.AbsPosition = reader.ReadUInt32();
// Skip the minimal amount of strings
reader.Position += 4 * 3;
uint filesPtr = reader.ReadUInt32();
uint optionsPtr = reader.ReadUInt32();
// The file list pointer should be less than the option list pointer.
// If it's not true, then "filesPtr" is actually a string pointer, so it's GM 2023.4+.
if (filesPtr > optionsPtr)
reader.undertaleData.SetGMS2Version(2023, 4);
}
reader.Position = returnPosition;
checkedFor2023_4 = true;
}
internal override void UnserializeChunk(UndertaleReader reader)
{
if (!checkedFor2022_6)
CheckFor2022_6(reader);
if (!checkedFor2023_4)
CheckFor2023_4(reader);
base.UnserializeChunk(reader);
// Strange data for each extension, some kind of unique identifier based on
// the product ID for each of them
productIdData = new List<byte[]>();
if (UndertaleExtension.ProductDataEligible(reader.undertaleData))
{
for (int i = 0; i < List.Count; i++)
{
productIdData.Add(reader.ReadBytes(16));
}
}
}
internal override void SerializeChunk(UndertaleWriter writer)
{
base.SerializeChunk(writer);
// (read above comment)
foreach (byte[] data in productIdData)
{
int Len = data.Length;
if (Len != 16)
{
throw new IOException("Can't write EXTN product id data of invalid length, expected 16, got " + Len);
}
writer.Write(data);
}
}
internal override uint UnserializeObjectCount(UndertaleReader reader)
{
checkedFor2022_6 = false;
CheckFor2022_6(reader);
CheckFor2023_4(reader);
return base.UnserializeObjectCount(reader);
}
}
public class UndertaleChunkSOND : UndertaleListChunk<UndertaleSound>
{
public override string Name => "SOND";
private bool checkedFor2024_6 = false;
private void CheckForGM2024_6(UndertaleReader reader)
{
if (!reader.undertaleData.IsNonLTSVersionAtLeast(2023, 2) || reader.undertaleData.IsVersionAtLeast(2024, 6))
{
checkedFor2024_6 = true;
return;
}
long returnTo = reader.Position;
uint possibleSoundCount = reader.ReadUInt32();
List<uint> soundPtrs = new();
if (possibleSoundCount > 0)
{
soundPtrs.Capacity = (int)possibleSoundCount;
for (int i = 0; i < possibleSoundCount; i++)
{
uint soundPtr = reader.ReadUInt32();
if (soundPtr == 0)
continue;
soundPtrs.Add(soundPtr);
}
}
if (soundPtrs.Count >= 2)
{
// If first sound's theoretical (old) end offset is below the start offset of
// the next sound by exactly 4 bytes, then this is 2024.6.
if ((soundPtrs[0] + (4 * 9)) == (soundPtrs[1] - 4))
{
reader.undertaleData.SetGMS2Version(2024, 6);
}
}
else if (soundPtrs.Count == 1)
{
// If there's a nonzero value where padding should be at the
// end of the sound, then this is 2024.6.
reader.AbsPosition = soundPtrs[0] + (4 * 9);
if ((reader.AbsPosition % 16) != 4)
{
// If this occurs, then something weird has happened at the start of the chunk?
throw new IOException("Expected to be on specific alignment at this point");
}
if (reader.ReadUInt32() != 0)
{
reader.undertaleData.SetGMS2Version(2024, 6);
}
}
reader.Position = returnTo;
checkedFor2024_6 = true;
}
internal override void UnserializeChunk(UndertaleReader reader)
{
if (!checkedFor2024_6)
CheckForGM2024_6(reader);
base.UnserializeChunk(reader);
}
internal override uint UnserializeObjectCount(UndertaleReader reader)
{
checkedFor2024_6 = false;
CheckForGM2024_6(reader);
return base.UnserializeObjectCount(reader);
}
}
public class UndertaleChunkAGRP : UndertaleListChunk<UndertaleAudioGroup>
{
public override string Name => "AGRP";
private bool checkedFor2024_14 = false;
private void CheckForGM2024_14(UndertaleReader reader)
{
checkedFor2024_14 = true;
// Only perform check if at least 2024.13 (trivially detected by now), and if not already detected
if (!reader.undertaleData.IsVersionAtLeast(2024, 13) || reader.undertaleData.IsVersionAtLeast(2024, 14))
{
return;
}
// Check for new field added in 2024.14
long returnTo = reader.Position;
long chunkEndPos = reader.AbsPosition + Length;
uint agrpCount = reader.ReadUInt32();
if (agrpCount == 0)
{
// No way to check when there's no audio groups... abort
reader.Position = returnTo;
return;
}
// Scan for up to two valid audio group pointers
uint firstGroupPosition = 0, secondGroupPosition = 0;
// Scan until we find a non-null first pointer...
uint i = 0;
while (i < agrpCount)
{
firstGroupPosition = reader.ReadUInt32();
i++;
if (firstGroupPosition != 0)
{
break;
}
}
// Scan until we find a non-null second pointer...
while (i < agrpCount)
{
secondGroupPosition = reader.ReadUInt32();
i++;
if (secondGroupPosition != 0)
{
break;
}
}
// Handle 0 audio groups (can't check anything)
if (firstGroupPosition == 0)
{
reader.Position = returnTo;
return;
}
// Separately handle the case with 1 audio group only, and cases with at least 2
if (secondGroupPosition == 0)
{
// Look for non-null bytes in the 4 bytes after the audio group name (and within bounds of the chunk)
reader.AbsPosition = firstGroupPosition + 4;
// Make sure the new field can fit in the remaining chunk space
if ((reader.AbsPosition + 4) > chunkEndPos)
{
reader.Position = returnTo;
return;
}
// If the field data is zero, it's not 2024.14
uint pathPtr = reader.ReadUInt32();
if (pathPtr == 0)
{
reader.Position = returnTo;
return;
}
}
else
{
// Compare offsets of two audio groups. If the difference is 4, then it's not 2024.14.
// Otherwise, it is at least 2024.14.
if ((secondGroupPosition - firstGroupPosition) == 4)
{
reader.Position = returnTo;
return;
}
}
// 2024.14 detected
reader.Position = returnTo;
reader.undertaleData.SetGMS2Version(2024, 14);
uint newSize = UndertaleAudioGroup.ChildObjectsSize + 4;
reader.SetStaticChildObjectsSize(typeof(UndertaleAudioGroup), newSize);
}
internal override void UnserializeChunk(UndertaleReader reader)
{
if (!checkedFor2024_14)
CheckForGM2024_14(reader);
base.UnserializeChunk(reader);
}
internal override uint UnserializeObjectCount(UndertaleReader reader)
{
checkedFor2024_14 = false;
CheckForGM2024_14(reader);
return base.UnserializeObjectCount(reader);
}
}
public class UndertaleChunkSPRT : UndertaleListChunk<UndertaleSprite>
{
public override string Name => "SPRT";
private bool checkedFor2024_6 = false;
private void CheckForGM2024_6(UndertaleReader reader)
{
if (!reader.undertaleData.IsNonLTSVersionAtLeast(2023, 2) || reader.undertaleData.IsVersionAtLeast(2024, 6))
{
checkedFor2024_6 = true;
return;
}
long returnTo = reader.Position;
long chunkStartPos = reader.AbsPosition;
// Calculate the expected end position of the first sprite where the bbox size differs from width/height
uint spriteCount = reader.ReadUInt32();
for (int i = 0; i < spriteCount; i++)
{
// Go to sprite's start position
reader.Position = returnTo + 4 + (4 * i);
uint spritePtr = reader.ReadUInt32();
if (spritePtr == 0)
continue;
uint nextSpritePtr = 0;
int j = i;
while (nextSpritePtr == 0 && (++j) < spriteCount)
nextSpritePtr = reader.ReadUInt32();
reader.AbsPosition = spritePtr + 4; // Skip past "Name"
// Check if bbox size differs from width/height
uint width = reader.ReadUInt32();
uint height = reader.ReadUInt32();
int marginLeft = reader.ReadInt32();
int marginRight = reader.ReadInt32();
int marginBottom = reader.ReadInt32();
int marginTop = reader.ReadInt32();
(int bboxWidth, int bboxHeight) = UndertaleSprite.CalculateBboxMaskDimensions(marginRight, marginLeft, marginBottom, marginTop);
(int normalWidth, int normalHeight) = UndertaleSprite.CalculateFullMaskDimensions((int)width, (int)height);
if (bboxWidth == normalWidth && bboxHeight == normalHeight)
{
// We can't determine anything from this sprite
continue;
}
reader.Position += 28;
if (reader.ReadInt32() != -1)
{
throw new IOException("Expected special sprite type");
}
uint sVersion = reader.ReadUInt32();
UndertaleSprite.SpriteType sSpriteType = (UndertaleSprite.SpriteType)reader.ReadUInt32();
if (sSpriteType != UndertaleSprite.SpriteType.Normal)
{
// We can't determine anything from this sprite
continue;
}
reader.Position += 8; // Playback speed values
if (sVersion != 3)
{
throw new IOException("Expected sprite version 3");
}
uint sequenceOffset = reader.ReadUInt32();
uint nineSliceOffset = reader.ReadUInt32();
// Skip past texture pointers
uint textureCount = reader.ReadUInt32();
reader.Position += textureCount * 4;
// Calculate how much space the "full" and "bbox" mask data take up
uint maskCount = reader.ReadUInt32();
if (maskCount == 0)
{
// We can't determine anything from this sprite
continue;
}
uint fullLength = (uint)((normalWidth + 7) / 8 * normalHeight);
fullLength *= maskCount;
if ((fullLength % 4) != 0)
fullLength += (4 - (fullLength % 4));
uint bboxLength = (uint)((bboxWidth + 7) / 8 * bboxHeight);
bboxLength *= maskCount;
if ((bboxLength % 4) != 0)
bboxLength += (4 - (bboxLength % 4));
// Calculate expected end offset
long expectedEndOffset;
bool endOffsetLenient = false;
if (sequenceOffset != 0)
{
expectedEndOffset = sequenceOffset;
}
else if (nineSliceOffset != 0)
{
expectedEndOffset = nineSliceOffset;
}
else if (nextSpritePtr != 0)
{
expectedEndOffset = nextSpritePtr;
}
else
{
// Use chunk length, and be lenient with it (due to chunk padding)
endOffsetLenient = true;
expectedEndOffset = chunkStartPos + Length;
}
// If the "full" mask data runs past the expected end offset, and the "bbox" mask data does not, then this is 2024.6.
// Otherwise, stop processing and assume this is not 2024.6.
long fullEndPos = (reader.AbsPosition + fullLength);
if (fullEndPos == expectedEndOffset)
{
// "Full" mask data is valid
break;
}
if (endOffsetLenient && (fullEndPos % 16) != 0 && fullEndPos + (16 - (fullEndPos % 16)) == expectedEndOffset)
{
// "Full" mask data doesn't exactly line up, but works if rounded up to the next chunk padding
break;
}
long bboxEndPos = (reader.AbsPosition + bboxLength);
if (bboxEndPos == expectedEndOffset)
{
// "Bbox" mask data is valid
reader.undertaleData.SetGMS2Version(2024, 6);
break;
}
if (endOffsetLenient && (bboxEndPos % 16) != 0 && bboxEndPos + (16 - (bboxEndPos % 16)) == expectedEndOffset)
{
// "Bbox" mask data doesn't exactly line up, but works if rounded up to the next chunk padding
reader.undertaleData.SetGMS2Version(2024, 6);
break;
}
// Neither option seems to have worked...
throw new IOException("Failed to detect mask type in 2024.6 detection");
}
reader.Position = returnTo;
checkedFor2024_6 = true;
}
internal override void UnserializeChunk(UndertaleReader reader)
{
if (!checkedFor2024_6)
CheckForGM2024_6(reader);
base.UnserializeChunk(reader);
}
internal override uint UnserializeObjectCount(UndertaleReader reader)
{
checkedFor2024_6 = false;
CheckForGM2024_6(reader);
return base.UnserializeObjectCount(reader);
}
}
public class UndertaleChunkBGND : UndertaleAlignUpdatedListChunk<UndertaleBackground>
{
public override string Name => "BGND";
private bool checkedFor2024_14_1 = false;
private void CheckForGM2024_14_1(UndertaleReader reader)
{
checkedFor2024_14_1 = true;
if (!reader.undertaleData.IsVersionAtLeast(2024, 13) || reader.undertaleData.IsVersionAtLeast(2024, 14, 1))
{
return;
}
long returnTo = reader.Position;
long chunkStartPos = reader.AbsPosition;
// Go through each background, and check to see if it ends at the expected position. If not, this is probably 2024.14.1.
uint bgCount = reader.ReadUInt32();
for (int i = 0; i < bgCount; i++)
{
// Find background's start position, and calculate next background position (if available).
reader.Position = returnTo + 4 + (4 * i);
uint bgPtr = reader.ReadUInt32();
if (bgPtr == 0)
{
// Removed asset
continue;
}
uint nextBgPtr = 0;
int j = i;
while (nextBgPtr == 0 && (++j) < bgCount)
{
// Try next pointer in list
nextBgPtr = reader.ReadUInt32();
}
// Skip all the way to "GMS2ItemsPerTileCount" (at its pre-2024.14.1 location), which is what we actually care about.
reader.AbsPosition = bgPtr + (11 * 4);
uint itemsPerTileCount = reader.ReadUInt32();
uint tileCount = reader.ReadUInt32();
// Calculate the theoretical end position given the above info, and compare to the actual end position (with padding).
uint theoreticalEndPos = bgPtr + (16 * 4) + (itemsPerTileCount * tileCount * 4);
if (nextBgPtr == 0)
{
// Align to 16 bytes, and compare against chunk end position
if ((theoreticalEndPos % 16) != 0)
{
theoreticalEndPos += 16 - (theoreticalEndPos % 16);
}
uint chunkEndPos = (uint)chunkStartPos + Length;
if (theoreticalEndPos != chunkEndPos)
{
// Probably 2024.14.1!
reader.undertaleData.SetGMS2Version(2024, 14, 1);
break;
}
}
else
{
// Align to 8 bytes, and compare against next background start position
if ((theoreticalEndPos % 8) != 0)
{
theoreticalEndPos += 8 - (theoreticalEndPos % 8);
}
if (theoreticalEndPos != nextBgPtr)
{
// Probably 2024.14.1!
reader.undertaleData.SetGMS2Version(2024, 14, 1);
break;
}
}
}
reader.Position = returnTo;
}
internal override void SerializeChunk(UndertaleWriter writer)
{
Alignment = 8;
base.SerializeChunk(writer);
}
internal override void UnserializeChunk(UndertaleReader reader)
{
Alignment = 8;
if (!checkedFor2024_14_1)
{
CheckForGM2024_14_1(reader);
}
base.UnserializeChunk(reader);
}
internal override uint UnserializeObjectCount(UndertaleReader reader)
{
checkedFor2024_14_1 = false;
CheckForGM2024_14_1(reader);
return base.UnserializeObjectCount(reader);
}
}
public class UndertaleChunkPATH : UndertaleListChunk<UndertalePath>
{
public override string Name => "PATH";
}
public class UndertaleChunkSCPT : UndertaleListChunk<UndertaleScript>
{
public override string Name => "SCPT";
}
public class UndertaleChunkGLOB : UndertaleSimpleListChunk<UndertaleGlobalInit>
{
public override string Name => "GLOB";
}
public class UndertaleChunkGMEN : UndertaleSimpleListChunk<UndertaleGlobalInit>
{
public override string Name => "GMEN";
}
public class UndertaleChunkSHDR : UndertaleListChunk<UndertaleShader>
{
public override string Name => "SHDR";
internal override void UnserializeChunk(UndertaleReader reader)
{
long chunkEnd = reader.AbsPosition + Length;
long beginPosition = reader.Position;
// Figure out where the starts/ends of each shader object are
int count = reader.ReadInt32();
uint[] objectLocations = new uint[count + 1];
for (int i = 0; i < count; i++)
{
uint objectLocation = reader.ReadUInt32();
if (objectLocation == 0)
{
i--;
count--;
continue;
}
objectLocations[i] = objectLocation;
}
objectLocations[count] = (uint)chunkEnd;
Dictionary<uint, UndertaleObject> objPool = reader.GetOffsetMap();
Dictionary<UndertaleObject, uint> objPoolRev = reader.GetOffsetMapRev();
// Setup base shader objects with boundaries set. Load into object pool
// so that they don't immediately discard.
for (int i = 0; i < count; i++)
{
UndertaleShader s = new UndertaleShader { EntryEnd = objectLocations[i + 1] };
objPool.Add(objectLocations[i], s);
objPoolRev.Add(s, objectLocations[i]);
}
reader.Position = beginPosition;
base.UnserializeChunk(reader);
}
}
public class UndertaleChunkFONT : UndertaleListChunk<UndertaleFont>
{
public override string Name => "FONT";
public byte[] Padding;
private bool checkedFor2022_2 = false;
private bool checkedFor2023_6And2024_11 = false;
private bool checkedFor2024_14 = false;
private void CheckForGM2022_2(UndertaleReader reader)
{
/* This code performs four checks to identify GM2022.2.
* First, as you've seen, is the bytecode version.
* Second, we assume it is. If there are no Glyphs, we are vindicated by the impossibility of null values there.
* Third, we check that the Glyph Length is less than the chunk length. If it's going outside the chunk, that means
* that the length was misinterpreted.
* Fourth, in case of a terrible fluke causing this to appear valid erroneously, we verify that each pointer leads into the next.
* And if someone builds their game so the first pointer is absolutely valid length data and the next font is valid glyph data-
* screw it, call Jacky720 when someone constructs that and you want to mod it.
* Maybe try..catch on the whole shebang?
*/
if (reader.undertaleData.GeneralInfo?.BytecodeVersion < 17 || reader.undertaleData.IsVersionAtLeast(2022, 2))
{
checkedFor2022_2 = true;
return;
}
long positionToReturn = reader.Position;
bool GMS2022_2 = false;
uint possibleFontCount = reader.ReadUInt32();
if (possibleFontCount > 0)
{
uint firstFontPointer = 0;
for (int i = 0; i < possibleFontCount; i++)
{
uint fontPointer = reader.ReadUInt32();
if (fontPointer != 0)
{
firstFontPointer = fontPointer;
break;
}
}
if (firstFontPointer != 0)
{
reader.AbsPosition = firstFontPointer + 48; // There are 48 bytes of existing metadata.
uint glyphsLength = reader.ReadUInt32();
GMS2022_2 = true;
if ((glyphsLength * 4) > this.Length)
{
GMS2022_2 = false;
}
else if (glyphsLength != 0)
{
List<uint> glyphPointers = new List<uint>((int)glyphsLength);
for (uint i = 0; i < glyphsLength; i++)
{
uint glyphPointer = reader.ReadUInt32();
if (glyphPointer == 0)
throw new IOException("One of the glyph pointers is null?");
glyphPointers.Add(glyphPointer);