-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathROMUtils.cpp
1847 lines (1720 loc) · 77.5 KB
/
ROMUtils.cpp
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
#include "ROMUtils.h"
#include "Compress.h"
#include "Operation.h"
#include <QFile>
#include <QTranslator>
#include "WL4EditorWindow.h"
#include "PatchUtils.h"
#include "SettingsUtils.h"
#include <cmath>
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
#include <cassert>
#include <iostream>
#include <QtDebug>
extern WL4EditorWindow *singleton;
// Helper function to find the number of characters matched in ptr to a pattern
static inline int StrMatch(unsigned char *ptr, const char *pattern)
{
int matched = 0;
do
{
if (ptr[matched] != *pattern)
break;
++matched;
} while (*++pattern);
return matched;
}
// Helper function to validate RATS at an address
static inline bool ValidRATS(unsigned char *ptr)
{
if (strncmp(reinterpret_cast<const char *>(ptr), "STAR", 4))
return false;
short chunkLen = *reinterpret_cast<short *>(ptr + 4);
short chunkComp = *reinterpret_cast<short *>(ptr + 6);
return chunkLen == ~chunkComp;
}
namespace ROMUtils
{
unsigned char *CurrentFile;
unsigned int CurrentFileSize;
QString ROMFilePath;
unsigned char *tmpCurrentFile;
unsigned int tmpCurrentFileSize;
QString tmpROMFilePath;
struct ROMFileMetadata CurrentROMMetadata;
struct ROMFileMetadata TempROMMetadata;
struct ROMFileMetadata *ROMFileMetadata;
unsigned int SaveDataIndex;
LevelComponents::AnimatedTile8x8Group *animatedTileGroups[270];
LevelComponents::Tileset *singletonTilesets[92];
LevelComponents::EntitySet *entitiessets[90];
LevelComponents::Entity *entities[129];
const char *ChunkTypeString[CHUNK_TYPE_COUNT] = {
"InvalidationChunk",
"RoomHeaderChunkType",
"DoorChunkType",
"LayerChunkType",
"LevelNameChunkType",
"EntityListChunk",
"CameraPointerTableType",
"CameraBoundaryChunkType",
"PatchListChunk",
"PatchChunk",
"TilesetForegroundTile8x8DataChunkType",
"TilesetMap16EventTableChunkType",
"TilesetMap16TerrainChunkType",
"TilesetMap16DataChunkType",
"TilesetPaletteDataChunkType",
"EntityTile8x8DataChunkType",
"EntityPaletteDataChunkType",
"EntitySetLoadTableChunkType",
"AssortedGraphicListChunkType",
"AssortedGraphicTile8x8DataChunkType",
"AssortedGraphicmappingChunkType",
"AssortedGraphicPaletteChunkType",
"AnimatedTileGroupTile8x8DataChunkType",
};
bool ChunkTypeAlignment[CHUNK_TYPE_COUNT] = {
false, // InvalidationChunk
true, // RoomHeaderChunkType
true, // DoorChunkType
false, // LayerChunkType
false, // LevelNameChunkType
false, // EntityListChunk
true, // CameraPointerTableType
true, // CameraBoundaryChunkType
false, // PatchListChunk
true, // PatchChunk
true, // TilesetForegroundTile8x8DataChunkType
true, // TilesetMap16EventTableChunkType
true, // TilesetMap16TerrainChunkType
true, // TilesetMap16DataChunkType
true, // TilesetPaletteDataChunkType
true, // EntityTile8x8DataChunkType
true, // EntityPaletteDataChunkType
true, // EntitySetLoadTableChunkType
false, // AssortedGraphicListChunkType = '\x12',
true, // AssortedGraphicTile8x8DataChunkType = '\x13',
false, // AssortedGraphicmappingChunkType = '\x14',
true, // AssortedGraphicPaletteChunkType = '\x15',
true, // AnimatedTileGroupTile8x8DataChunkType = '\x16',
};
void StaticInitialization()
{
CurrentFile = tmpCurrentFile = nullptr;
CurrentROMMetadata = {CurrentFileSize, ROMFilePath, CurrentFile};
TempROMMetadata = {tmpCurrentFileSize, tmpROMFilePath, tmpCurrentFile};
ROMFileMetadata = &CurrentROMMetadata;
}
/// <summary>
/// Get a 4-byte, little-endian integer from ROM data.
/// </summary>
/// <param name="data">
/// The ROM data to read from.
/// </param>
/// <param name="address">
/// The address to get the integer from.
/// </param>
unsigned int IntFromData(int address)
{
return *reinterpret_cast<unsigned int *>(ROMFileMetadata->ROMDataPtr + address);
}
/// <summary>
/// Get a pointer value from ROM data.
/// </summary>
/// <remarks>
/// The pointer which is returned does not include the upper byte, which is only necessary for the GBA memory map.
/// The returned int value can be used to index the ROM data.
/// </remarks>
/// <param name="data">
/// The ROM data to read from.
/// </param>
/// <param name="address">
/// The address to get the pointer from.
/// </param>
/// <param name="loadFromTmpROM">
/// Ture when load from a temp ROM.
/// </param>
unsigned int PointerFromData(int address)
{
unsigned int ret = IntFromData(address) & 0x7FFFFFF;
if (ret > WL4Constants::AvailableSpaceBeginningInROM && !ValidRATS(ROMFileMetadata->ROMDataPtr + ret - 12))
{
singleton->GetOutputWidgetPtr()->PrintString(QT_TR_NOOP("Internal or corruption error: Load data from a broken chunk!\n "
"Data Address:" + QString::number(ret, 16) + "\n"
"Chunk Address:" + QString::number(ret - 12, 16) + "\n"));
// we can provide no more information of the chunk here since the chunk header is broken
}
if(ret >= ROMFileMetadata->Length)
{
singleton->GetOutputWidgetPtr()->PrintString(QT_TR_NOOP("Internal or corruption error: Attempted to read a pointer which is larger than the ROM's file size"));
}
return ret;
}
/// <summary>
/// Get an 32 bytes uchar array of Tile8x8 graphic data, then X flip the data of its graphic.
/// </summary>
/// <param name="source">
/// The pointer to read uchar array Tile8x8 data.
/// </param>
/// <param name="destination">
/// The pointer to save changed Tile8x8 data to.
/// </param>
void Tile8x8DataXFlip(unsigned char *source, unsigned char *destination)
{
for (int col = 0; col < 8; col++)
{
for (int row = 0; row < 4; row++)
{
unsigned char curByte = source[col * 4 + row];
curByte = ((curByte & 0xF) << 4) | ((curByte & 0xF0) >> 4);
destination[col * 4 + (3 - row)] = curByte;
}
}
}
/// <summary>
/// Get an 32 bytes uchar array of Tile8x8 graphic data, then Y flip the data of its graphic.
/// </summary>
/// <param name="source">
/// The pointer to read uchar array Tile8x8 data.
/// </param>
/// <param name="destination">
/// The pointer to save changed Tile8x8 data to.
/// </param>
void Tile8x8DataYFlip(unsigned char *source, unsigned char *destination)
{
for (int col = 0; col < 8; col++)
{
memcpy(&destination[col * 4], &source[(7 - col) * 4], 4 * sizeof(unsigned char));
}
}
/// <summary>
/// Reverse the endianness of an integer.
/// </summary>
/// <param name="n">
/// The integer to reverse.
/// </param>
/// <return>
/// 08 FF A1 C9 -> C9 A1 FF 08
/// </return>
uint32_t EndianReverse(uint32_t n)
{
return (n << 24) | ((n & 0xFF00) << 8) | ((n & 0xFF0000) >> 8) | ((n >> 24) & 0xFF);
}
/// <summary>
/// Compress a whole screen of character data.
/// </summary>
/// <param name="screenCharData">
/// A pointer to a whole screen of character data.
/// </param>
/// <param name="outputCompressedData">
/// A pointer to the output compressed character data.
/// </param>
/// <return>The length of output data (number of unsigned short).</return>
unsigned int PackScreen(unsigned short *screenCharData, unsigned short *&outputCompressedData, bool skipzeros)
{
/*** compressed data format:
* Compressed data format:
* 1st ushort: t | o o o o o o o o o o | n n n n n
* 2nd ushort: the unsigned short value of the current character
************************************************
* number(n): the loop counter
* offset(o): the offset of the current character in the non-compressed char data array
* type(t): there are 2 cases:
* if t = 0, then the decompressed data will be:
* o, o + 1, o + 2, ... , o + n - 1. (n continuous numbers in total)
* if t = 1, then the decompressed data will be:
* o, o, o, o, ... , o. (duplicate o by n times)
************************************************
* The compressed data array should end with an additional 0x0000,
* the decompression function ingame need it to stop decompression
*/
int offset = 0; // should be in range of [0, 0x3FF]
QVector<unsigned short> output;
while (offset < 0x3FF)
{
unsigned short curChar = screenCharData[offset];
int num_dup = 0;
int num_AddByOne = 0;
for (int i = 1; i < 32; ++i) // type = 1
{
if ((curChar != screenCharData[offset + i]) || ((offset + i) == 0x3FF))
{
break;
}
num_dup++;
}
for (int i = 1; i < 32; ++i) // type = 0
{
if (((curChar + i) != screenCharData[offset + i]) || ((offset + i) == 0x3FF))
{
break;
}
num_AddByOne++;
}
if (num_dup >= num_AddByOne)
{
if (skipzeros && !curChar)
{
goto skip_append_output_1;
}
output << ((0x8000 | ((offset & 0x3FF) << 5) | num_dup) & 0xFFFF);
output << curChar;
skip_append_output_1:
offset += num_dup + 1;
}
else // num_dup < num_AddByOne, type = 1
{
if (skipzeros && !curChar)
{
goto skip_append_output_2;
}
output << ((((offset & 0x3FF) << 5) | num_AddByOne) & 0x7FFF);
output << curChar;
skip_append_output_2:
offset += num_AddByOne + 1;
}
}
output << 0x0000;
int output_size = output.size();
outputCompressedData = new unsigned short[output_size];
unsigned short *operationPtr = outputCompressedData;
memset((unsigned char *)operationPtr, 0, sizeof(unsigned short) * output_size);
for (int i = 0; i < output_size; ++i)
{
*operationPtr = output[i];
operationPtr++;
}
return output_size;
}
/// <summary>
/// Decompress a whole screen of character data.
/// </summary>
/// <param name="address">
/// A pointer into the ROM data to start reading from.
/// </param>
/// <return>A pointer to decompressed data.</return>
unsigned short *UnPackScreen(uint32_t address)
{
// directly modified from disassembled rom's code, C code generated by IDA pro
unsigned short *v2, *src;
unsigned short i;
unsigned short *dst = new unsigned short[32 * 32];
unsigned short *v5;
unsigned short *v6;
unsigned short v7;
unsigned short j;
unsigned short v9;
unsigned short k;
unsigned short v11;
memset(dst, 0, 32 * 32 * sizeof(unsigned short));
// check if address is an odd number
if (address & 1)
{
singleton->GetOutputWidgetPtr()->PrintString(QT_TR_NOOP("Error in ROMUtils::UnPackScreen(int address): input parameter 'address' should be an odd number."));
return dst;
}
v2 = src = (unsigned short *)(ROMFileMetadata->ROMDataPtr + address);
for (i = *src; *v2; i = *v2)
{
v5 = (dst + ((i >> 5) & 0x3FF));
v6 = v2 + 1;
if ((i & 0x8000) != 0)
{
v7 = *v6;
v2 = v6 + 1;
for (j = i & 0x1F; j != 0xFFFF; --j)
{
// don't write memory if memory leak
if (v5 > (dst + 32 * 32 - 1))
{
v5++;
continue;
}
*v5++ = v7;
}
}
else
{
v9 = *v6;
v2 = v6 + 1;
for (k = i & 0x1F; k != 0xFFFF; --k)
{
v11 = v9++;
// don't write memory if memory leak
if (v5 > (dst + 32 * 32 - 1))
{
v5++;
continue;
}
*v5++ = v11;
}
}
}
return dst;
}
/// <summary>
/// Decompress ROM data that was compressed with run-length encoding.
/// </summary>
/// <remarks>
/// The <paramref name="outputSize"/> parameter specifies the predicted output size in bytes.
/// The return unsigned char * is on the heap, delete it after using.
/// </remarks>
/// <param name="address">
/// A pointer into the ROM data to start reading from.
/// </param>
/// <param name="outputSize">
/// The predicted size of the output data.(unit: Byte)
/// </param>
/// <return>A pointer to decompressed data.</return>
unsigned char *LayerRLEDecompress(int address, size_t outputSize)
{
unsigned char *OutputLayerData = new unsigned char[outputSize];
int runData;
for (int i = 0; i < 2; i++)
{
unsigned char *dst = OutputLayerData + i;
if (ROMFileMetadata->ROMDataPtr[address++] == 1)
{
while (1)
{
int ctrl = ROMFileMetadata->ROMDataPtr[address++];
if (!ctrl)
{
break;
}
size_t temp = dst - OutputLayerData;
if (temp > outputSize)
{
delete[] OutputLayerData;
return nullptr;
}
else if (ctrl & 0x80)
{
runData = ctrl & 0x7F;
for (int j = 0; j < runData; j++)
{
dst[2 * j] = ROMFileMetadata->ROMDataPtr[address];
}
address++;
}
else
{
runData = ctrl;
for (int j = 0; j < runData; j++)
{
dst[2 * j] = ROMFileMetadata->ROMDataPtr[address + j];
}
address += runData;
}
dst += 2 * runData;
}
}
else // RLE16
{
while (1)
{
int ctrl = (static_cast<int>(ROMFileMetadata->ROMDataPtr[address]) << 8) | ROMFileMetadata->ROMDataPtr[address + 1];
address += 2; // offset + 2
if (!ctrl)
{
break;
}
size_t temp = dst - OutputLayerData;
if (temp > outputSize)
{
delete[] OutputLayerData;
return nullptr;
}
if (ctrl & 0x8000)
{
runData = ctrl & 0x7FFF;
for (int j = 0; j < runData; j++)
{
dst[2 * j] = ROMFileMetadata->ROMDataPtr[address];
}
address++;
}
else
{
runData = ctrl;
for (int j = 0; j < runData; j++)
{
dst[2 * j] = ROMFileMetadata->ROMDataPtr[address + j];
}
address += runData;
}
dst += 2 * runData;
}
}
}
return OutputLayerData;
}
/// <summary>
/// compress Layer data by run-length encoding.
/// </summary>
/// <remarks>
/// the first and second byte as the layer width and height information will not be generated in the function
/// you have to add them by yourself when saving compressed data.
/// </remarks>
/// <param name="_layersize">
/// the size of the layer, the value equal to (layerwidth * layerheight).
/// </param>
/// <param name="LayerData">
/// unsigned char pointer to the uncompressed layer data.
/// </param>
/// <param name="OutputCompressedData">
/// unsigned char pointer to the compressed layer data.
/// </param>
/// <return>the length of compressed data.</return>
unsigned int LayerRLECompress(unsigned int _layersize, unsigned short *LayerData,
unsigned char **OutputCompressedData)
{
// Separate short data into char arrays
unsigned char *separatedBytes = new unsigned char[_layersize * 2];
for (unsigned int i = 0; i < _layersize; ++i)
{
unsigned short s = LayerData[i];
separatedBytes[i] = static_cast<unsigned char>(s);
separatedBytes[i + _layersize] = static_cast<unsigned char>(s >> 8);
}
// Decide on 8 or 16 bit compression for the arrays
RLEMetadata8Bit Lower8Bit(separatedBytes, _layersize);
RLEMetadata16Bit Lower16Bit(separatedBytes, _layersize);
RLEMetadata8Bit Upper8Bit(separatedBytes + _layersize, _layersize);
RLEMetadata16Bit Upper16Bit(separatedBytes + _layersize, _layersize);
RLEMetadata *Lower = Lower8Bit.GetCompressedLength() < Lower16Bit.GetCompressedLength()
? (RLEMetadata *) &Lower8Bit
: (RLEMetadata *) &Lower16Bit;
RLEMetadata *Upper = Upper8Bit.GetCompressedLength() < Upper16Bit.GetCompressedLength()
? (RLEMetadata *) &Upper8Bit
: (RLEMetadata *) &Upper16Bit;
// Create the data to return
unsigned int lowerLength = Lower->GetCompressedLength(), upperLength = Upper->GetCompressedLength();
unsigned int size = lowerLength + upperLength + 1;
*OutputCompressedData = new unsigned char[size];
void *lowerData = Lower->GetCompressedData();
void *upperData = Upper->GetCompressedData();
memcpy(*OutputCompressedData, lowerData, lowerLength);
memcpy(*OutputCompressedData + lowerLength, upperData, upperLength);
(*OutputCompressedData)[lowerLength + upperLength] = '\0';
// Clean up
delete[] separatedBytes;
return size;
}
/// <summary>
/// Get the savedata chunks from a Tileset.
/// </summary>
/// <param name="TilesetId">
/// Select a Tileset by its Id.
/// </param>
/// <param name="chunks">
/// Push new chunks to it.
/// </param>
void GenerateTilesetSaveChunks(int TilesetId, QVector<SaveData> &chunks)
{
int tilesetPtr = singletonTilesets[TilesetId]->getTilesetPtr();
// Create Map16EventTable chunk
struct ROMUtils::SaveData Map16EventTablechunk = { static_cast<unsigned int>(tilesetPtr + 28),
0x600,
(unsigned char *) malloc(0x600),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr + 28),
ROMUtils::SaveDataChunkType::TilesetMap16EventTableChunkType };
memcpy(Map16EventTablechunk.data, singletonTilesets[TilesetId]->GetEventTablePtr(), 0x600);
chunks.append(Map16EventTablechunk);
// Create FGTile8x8GraphicData chunk
int FGTileGfxDataLen = singletonTilesets[TilesetId]->GetfgGFXlen();
unsigned char FGmap8x8tiledata[(1024 - 65) * 32];
QVector<LevelComponents::Tile8x8 *> tile8x8array = singletonTilesets[TilesetId]->GetTile8x8arrayPtr();
for (int j = 0; j < (FGTileGfxDataLen / 32); ++j)
{
memcpy(&FGmap8x8tiledata[32 * j], tile8x8array[j + 0x41]->CreateGraphicsData().data(), 32);
}
struct ROMUtils::SaveData FGTile8x8GraphicDataChunk = { static_cast<unsigned int>(tilesetPtr),
static_cast<unsigned int>(FGTileGfxDataLen),
(unsigned char *) malloc(FGTileGfxDataLen),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr),
ROMUtils::SaveDataChunkType::TilesetForegroundTile8x8DataChunkType };
memcpy(FGTile8x8GraphicDataChunk.data, FGmap8x8tiledata, FGTileGfxDataLen);
chunks.append(FGTile8x8GraphicDataChunk);
// Create Map16TerrainType chunk
struct ROMUtils::SaveData Map16TerrainTypechunk = { static_cast<unsigned int>(tilesetPtr + 24),
0x300,
(unsigned char *) malloc(0x300),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr + 24),
ROMUtils::SaveDataChunkType::TilesetMap16TerrainChunkType };
memcpy(Map16TerrainTypechunk.data, singletonTilesets[TilesetId]->GetTerrainTypeIDTablePtr(), 0x300);
chunks.append(Map16TerrainTypechunk);
// Save palettes
singletonTilesets[TilesetId]->ReGeneratePaletteData();
struct ROMUtils::SaveData TilesetPalettechunk = { static_cast<unsigned int>(tilesetPtr + 8),
16 * 16 * 2,
(unsigned char *) malloc(16 * 16 * 2),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr + 8),
ROMUtils::SaveDataChunkType::TilesetPaletteDataChunkType };
memcpy(TilesetPalettechunk.data, singletonTilesets[TilesetId]->GetTilesetPaletteDataPtr(), 16 * 16 * 2);
chunks.append(TilesetPalettechunk);
// Create Map16Data chunk
QVector<LevelComponents::TileMap16 *> map16data = singletonTilesets[TilesetId]->GetMap16arrayPtr();
struct ROMUtils::SaveData Map16Datachunk = { static_cast<unsigned int>(tilesetPtr + 20),
0x300 * 8,
(unsigned char *) malloc(0x300 * 8),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr + 20),
ROMUtils::SaveDataChunkType::TilesetMap16DataChunkType };
unsigned short map16tilePtr[0x300 * 4];
for (int j = 0; j < 0x300; ++j)
{
map16tilePtr[j * 4] = map16data[j]->GetTile8X8(LevelComponents::TileMap16::TILE8_TOPLEFT)->GetValue();
map16tilePtr[j * 4 + 1] = map16data[j]->GetTile8X8(LevelComponents::TileMap16::TILE8_TOPRIGHT)->GetValue();
map16tilePtr[j * 4 + 2] = map16data[j]->GetTile8X8(LevelComponents::TileMap16::TILE8_BOTTOMLEFT)->GetValue();
map16tilePtr[j * 4 + 3] = map16data[j]->GetTile8X8(LevelComponents::TileMap16::TILE8_BOTTOMRIGHT)->GetValue();
}
memcpy(Map16Datachunk.data, (unsigned char*)map16tilePtr, 0x300 * 8);
chunks.append(Map16Datachunk);
}
/// <summary>
/// Find the next chunk of a specific type.
/// </summary>
/// <param name="ROMData">
/// The pointer to the ROM data being processed.
/// </param>
/// <param name="ROMLength">
/// The length of the ROM data.
/// </param>
/// <param name="startAddr">
/// The start address to search from.
/// </param>
/// <param name="chunkType">
/// The chunk type to search for in the ROM.
/// </param>
/// <param name="anyChunk">
/// If true, then return any chunk instead of specific types specified by <paramref name="chunkType"/>.
/// </param>
/// <returns>
/// The next chunk of a specific type, or 0 if none exists.
/// </returns>
unsigned int FindChunkInROM(unsigned char *ROMData, unsigned int ROMLength, unsigned int startAddr, enum SaveDataChunkType chunkType, bool anyChunk)
{
if(startAddr >= ROMLength) return 0; // fail if not enough room in ROM
while(startAddr < ROMLength)
{
// Optimize search by incrementing more with partial matches
int STARmatch = StrMatch(ROMData + startAddr, "STAR");
if(STARmatch < 4)
{
// STAR not found at current address
startAddr += qMax(STARmatch, 1);
}
else
{
// STAR found at current address: validate the RATS checksum and chunk type
if(ValidRATS(ROMData + startAddr) && (anyChunk || ROMData[startAddr + 8] == chunkType))
{
return startAddr;
}
else
{
// Invalid RATS or chunk type not found: advance
startAddr += 4;
}
}
}
return 0;
}
/// <summary>
/// Find all chunks of a specific type.
/// </summary>
/// <param name="ROMData">
/// The pointer to the ROM data being processed.
/// </param>
/// <param name="ROMLength">
/// The length of the ROM data.
/// </param>
/// <param name="startAddr">
/// The start address to search from.
/// </param>
/// <param name="chunkType">
/// The chunk type to search for in the ROM.
/// </param>
/// <param name="anyChunk">
/// If true, then return any chunk instead of specific types specified by <paramref name="chunkType"/>.
/// </param>
/// <returns>
/// A list of all chunks of a specific type.
/// </returns>
QVector<unsigned int> FindAllChunksInROM(unsigned char *ROMData, unsigned int ROMLength, unsigned int startAddr, enum SaveDataChunkType chunkType, bool anyChunk)
{
QVector<unsigned int> chunks;
while(startAddr < ROMLength)
{
unsigned int chunkAddr = FindChunkInROM(ROMData, ROMLength, startAddr, chunkType, anyChunk);
if(chunkAddr)
{
chunks.append(chunkAddr);
unsigned int chunkLen = *reinterpret_cast<unsigned short*>(ROMData + chunkAddr + 4);
unsigned int extLen = (unsigned int) *reinterpret_cast<unsigned char*>(ROMData + chunkAddr + 9) << 16;
startAddr = chunkAddr + chunkLen + extLen + 12;
}
else break;
}
return chunks;
}
/// <summary>
/// Find all free space regions in the ROM.
/// </summary>
/// <param name="ROMData">
/// The pointer to the ROM data being processed.
/// </param>
/// <param name="ROMLength">
/// The length of the ROM data.
/// </param>
/// <returns>
/// A list of all free space regions.
/// </returns>
QVector<struct FreeSpaceRegion> FindAllFreeSpaceInROM(unsigned char *ROMData, unsigned int ROMLength)
{
QVector<struct FreeSpaceRegion> freeSpace;
unsigned int startAddr = WL4Constants::AvailableSpaceBeginningInROM;
unsigned int freeSpaceStart = startAddr;
// Search through ROM for chunks. The space between them is free space
while(startAddr < ROMLength)
{
// Optimize search by incrementing more with partial matches
int STARmatch = StrMatch(ROMData + startAddr, "STAR");
if(STARmatch < 4)
{
// STAR not found at current address
startAddr += qMax(STARmatch, 1);
}
else
{
// STAR found at current address: validate the RATS checksum and chunk type
if(ValidRATS(ROMData + startAddr))
{
// Chunk found. The space up to this point is free space
if(startAddr > freeSpaceStart)
{
freeSpace.append({freeSpaceStart, startAddr - freeSpaceStart});
}
// Continue search after this chunk
unsigned int chunkLen = *reinterpret_cast<unsigned short*>(ROMData + startAddr + 4);
unsigned int extLen = (unsigned int) *reinterpret_cast<unsigned char*>(ROMData + startAddr + 9) << 16;
startAddr += chunkLen + extLen + 12;
freeSpaceStart = startAddr;
}
else
{
// Invalid RATS or chunk type not found: advance
startAddr += 4;
}
}
}
// The last space in the ROM is a free space region
if(startAddr > freeSpaceStart)
{
freeSpace.append({freeSpaceStart, startAddr - freeSpaceStart});
}
return freeSpace;
}
/// <summary>
/// Callback used for allocating chunks from a list.
/// Must call init before using this function as a callback.
/// </summary>
static int CHUNK_INDEX;
static QVector<struct SaveData> CHUNK_ALLOC;
static ChunkAllocationStatus AllocateChunksFromList(unsigned char *TempFile,
struct FreeSpaceRegion freeSpace,
struct SaveData *sd,
bool resetchunkIndex,
int *require_size)
{
(void) TempFile;
// This part of code will be triggered when rom size needs to be expanded
// So all the chunks will be reallocated
if(resetchunkIndex)
{
CHUNK_INDEX = 0;
}
if(CHUNK_INDEX >= CHUNK_ALLOC.size())
{
return ChunkAllocationStatus::NoMoreChunks;
}
// Get the size of the space that would be needed at this address depending on alignment
unsigned int alignOffset = 0;
if(CHUNK_ALLOC[CHUNK_INDEX].alignment)
{
unsigned int startAddr = (freeSpace.addr + 3) & ~3;
alignOffset = startAddr - freeSpace.addr;
}
// Check if there is space for the chunk in the offered area
// required_size > (freespace.size - alignment - 12 bytes (for header))
if(CHUNK_ALLOC[CHUNK_INDEX].size > freeSpace.size - alignOffset - 12)
{
// This will request a larger free area
*require_size = CHUNK_ALLOC[CHUNK_INDEX].size;
return ChunkAllocationStatus::InsufficientSpace;
}
else
{
// Accept the offered free area for this save chunk
*sd = CHUNK_ALLOC[CHUNK_INDEX++];
return ChunkAllocationStatus::Success;
}
}
static ChunkAllocationStatus AllocateChunksFromListInit(QVector<struct SaveData> chunksToAllocate)
{
CHUNK_INDEX = 0;
CHUNK_ALLOC = chunksToAllocate;
return ChunkAllocationStatus::Success;
}
/// <summary>
/// Save a list of chunks to the ROM file.
/// </summary>
/// <param name="filePath">
/// The file name to use when saving the ROM.
/// </param>
/// <param name="invalidationChunks">
/// Addresses of chunks to invalidate.
/// </param>
/// <param name="ChunkAllocator">
/// Callback function that allocates chunks.
/// The SaveFile function will offer potential free areas to the allocator, which will then
/// accept or reject the free area depending on how much space is actually needed.
/// </param>
/// <param name="PostProcessingCallback">
/// Post-processing to perform after writing the save chunks, but before saving the file itself.
/// This function returns an error string if unsuccessful, or an empty string if successful.
/// </param>
/// <returns>
/// True if the save was successful.
/// </returns>
bool SaveFile(QString filePath, QVector<unsigned int> invalidationChunks,
std::function<ChunkAllocationStatus (unsigned char *, FreeSpaceRegion, SaveData*, bool, int*)> ChunkAllocator,
std::function<QString (unsigned char*, std::map<int, int>)> PostProcessingCallback)
{
// Finding space for the chunks can be done faster if the chunks are ordered by size
unsigned char *TempFile = (unsigned char *) malloc(ROMFileMetadata->Length);
unsigned int TempLength = ROMFileMetadata->Length;
memcpy(TempFile, ROMFileMetadata->ROMDataPtr, ROMFileMetadata->Length);
std::map<int, int> chunkIDtoIndex;
// Invalidate old chunk data
for(unsigned int invalidationChunk : invalidationChunks)
{
// Sanity check
if(invalidationChunk > ROMFileMetadata->Length)
{
singleton->GetOutputWidgetPtr()->PrintString(QString(QT_TR_NOOP("Internal error while saving changes to ROM: Invalidation chunk out of range of entire ROM. Address: %1"))
.arg("0x" + QString::number(invalidationChunk - 12, 16).toUpper()));
}
// Chunks can only be invalidated within valid chunk area
if (invalidationChunk > WL4Constants::AvailableSpaceBeginningInROM)
{
unsigned char *RATSaddr = TempFile + invalidationChunk - 12;
if (ValidRATS(RATSaddr)) // old_chunk_addr should point to the start of the chunk data, not the RATS tag
{
strncpy((char *) RATSaddr, "STAR_INV", 8);
}
else
{
singleton->GetOutputWidgetPtr()->PrintString(QString(QT_TR_NOOP("Internal error while saving changes to ROM: Invalidation chunk references an invalid RATS identifier for existing chunk. Address: %1. Changes not saved."))
.arg("0x" + QString::number(invalidationChunk - 12, 16).toUpper()));
return false;
}
}
}
// Find free space in the ROM and attempt to offer the free regions to the chunk allocator
QVector<struct FreeSpaceRegion> freeSpaceRegions;
QVector<struct SaveData> chunksToAdd;
std::map<int, int> indexToChunkPtr;
bool success = false;
bool resizerom = false; // act as a trigger to reset index in ChunkAllocator
resized:freeSpaceRegions.clear();
chunksToAdd.clear();
indexToChunkPtr.clear();
freeSpaceRegions = FindAllFreeSpaceInROM(TempFile, TempLength);
do
{
// Order free space regions by increasing size
std::sort(freeSpaceRegions.begin(), freeSpaceRegions.end(),
[](const struct FreeSpaceRegion &a, const struct FreeSpaceRegion &b)
{return a.size < b.size;});
// Offer free space to chunk allocator (starting with size of 12)
unsigned int lastSize = 11, newSize;
struct SaveData sd;
int i;
for(i = 0; i < freeSpaceRegions.size(); ++i)
{
if(freeSpaceRegions[i].size <= lastSize) continue;
int required_min_size = lastSize;
ChunkAllocationStatus status = ChunkAllocator(TempFile, freeSpaceRegions[i], &sd, resizerom, &required_min_size);
resizerom = false;
switch(status)
{
case Success:
goto spaceFound;
case NoMoreChunks:
goto allocationComplete;
case ProcessingError:
goto error;
case InsufficientSpace:
lastSize = freeSpaceRegions[i].size;
if (required_min_size > lastSize) lastSize = required_min_size;
continue;
}
}
// No free space regions capable of accommodating chunk. Expand ROM
newSize = (TempLength << 1) & ~0x7FFFFF;
if(newSize <= 0x2000000)
{
unsigned char *newTempFile = (unsigned char*) realloc(TempFile, newSize);
if(!newTempFile)
{
// Realloc failed due to system memory constraints
QMessageBox::warning(
singleton,
QT_TR_NOOP("Out of memory"),
QT_TR_NOOP("Unable to save changes because your computer is out of memory."),
QMessageBox::Ok,
QMessageBox::Ok
);
goto error;
}
TempFile = newTempFile;
memset(TempFile + TempLength, 0xFF, newSize - TempLength);
TempLength = newSize;
resizerom = true;
goto resized;
}
else
{
// ROM size cannot exceed 32MB
QMessageBox::warning(
singleton,
QT_TR_NOOP("ROM too large"),
QString(QT_TR_NOOP("Unable to save changes because there is not enough free space, and the ROM file cannot be expanded larger than 32MB.")),
QMessageBox::Ok,
QMessageBox::Ok
);
goto error;
}
spaceFound:
// Split the free space region
struct FreeSpaceRegion freeSpace = freeSpaceRegions[i];
freeSpaceRegions.remove(i);
// Determine where the chunk starts if alignment would modify it
unsigned int alignedAddr = freeSpace.addr;
if(sd.alignment)
{
alignedAddr = (alignedAddr + 3) & ~3;
}
unsigned int alignmentOffset = alignedAddr - freeSpace.addr;
// If chunk data starts at an offset due to alignment, split on left side of data
if(alignmentOffset)
{
freeSpaceRegions.append({freeSpace.addr, alignmentOffset});
}
// If chunk data is smaller than free space, split on right side of data
if(alignmentOffset + sd.size < freeSpace.size)
{
freeSpaceRegions.append({
freeSpace.addr + alignmentOffset + sd.size + 12,
freeSpace.size - (alignmentOffset + sd.size) - 12
});
}