/
GameSave.cpp
2715 lines (2535 loc) · 82.7 KB
/
GameSave.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 "common/tpt-minmax.h"
#include <iostream>
#include <cmath>
#include <climits>
#include <memory>
#include <vector>
#include <set>
#include <bzlib.h>
#include "Config.h"
#include "Format.h"
#include "GameSave.h"
#include "simulation/SimulationData.h"
#include "ElementClasses.h"
#include "hmap.h"
GameSave::GameSave(GameSave & save):
majorVersion(save.majorVersion),
waterEEnabled(save.waterEEnabled),
legacyEnable(save.legacyEnable),
gravityEnable(save.gravityEnable),
aheatEnable(save.aheatEnable),
paused(save.paused),
gravityMode(save.gravityMode),
airMode(save.airMode),
edgeMode(save.edgeMode),
signs(save.signs),
stkm(save.stkm),
palette(save.palette),
pmapbits(save.pmapbits),
expanded(save.expanded),
hasOriginalData(save.hasOriginalData),
originalData(save.originalData)
{
InitData();
hasPressure = save.hasPressure;
hasAmbientHeat = save.hasAmbientHeat;
if (save.expanded)
{
setSize(save.blockWidth, save.blockHeight);
std::copy(save.particles, save.particles+NPART, particles);
for (int j = 0; j < blockHeight; j++)
{
std::copy(save.blockMap[j], save.blockMap[j]+blockWidth, blockMap[j]);
std::copy(save.fanVelX[j], save.fanVelX[j]+blockWidth, fanVelX[j]);
std::copy(save.fanVelY[j], save.fanVelY[j]+blockWidth, fanVelY[j]);
std::copy(save.pressure[j], save.pressure[j]+blockWidth, pressure[j]);
std::copy(save.velocityX[j], save.velocityX[j]+blockWidth, velocityX[j]);
std::copy(save.velocityY[j], save.velocityY[j]+blockWidth, velocityY[j]);
std::copy(save.ambientHeat[j], save.ambientHeat[j]+blockWidth, ambientHeat[j]);
}
}
else
{
blockWidth = save.blockWidth;
blockHeight = save.blockHeight;
}
particlesCount = save.particlesCount;
authors = save.authors;
}
GameSave::GameSave(int width, int height)
{
InitData();
InitVars();
hasOriginalData = false;
expanded = true;
setSize(width, height);
}
GameSave::GameSave(std::vector<char> data)
{
blockWidth = 0;
blockHeight = 0;
InitData();
InitVars();
expanded = false;
hasOriginalData = true;
originalData = data;
try
{
Expand();
}
catch(ParseException & e)
{
std::cout << e.what() << std::endl;
dealloc(); //Free any allocated memory
throw;
}
Collapse();
}
GameSave::GameSave(std::vector<unsigned char> data)
{
blockWidth = 0;
blockHeight = 0;
InitData();
InitVars();
expanded = false;
hasOriginalData = true;
originalData = std::vector<char>(data.begin(), data.end());
try
{
Expand();
}
catch(ParseException & e)
{
std::cout << e.what() << std::endl;
dealloc(); //Free any allocated memory
throw;
}
Collapse();
}
GameSave::GameSave(char * data, int dataSize)
{
blockWidth = 0;
blockHeight = 0;
InitData();
InitVars();
expanded = false;
hasOriginalData = true;
originalData = std::vector<char>(data, data+dataSize);
#ifdef DEBUG
std::cout << "Creating Expanded save from data" << std::endl;
#endif
try
{
Expand();
}
catch(ParseException & e)
{
std::cout << e.what() << std::endl;
dealloc(); //Free any allocated memory
throw;
}
//Collapse();
}
// Called on every new GameSave, including the copy constructor
void GameSave::InitData()
{
blockMap = NULL;
fanVelX = NULL;
fanVelY = NULL;
particles = NULL;
pressure = NULL;
velocityX = NULL;
velocityY = NULL;
ambientHeat = NULL;
fromNewerVersion = false;
hasPressure = false;
hasAmbientHeat = false;
authors.clear();
}
// Called on every new GameSave, except the copy constructor
void GameSave::InitVars()
{
majorVersion = 0;
waterEEnabled = false;
legacyEnable = false;
gravityEnable = false;
aheatEnable = false;
paused = false;
gravityMode = 0;
airMode = 0;
edgeMode = 0;
translated.x = translated.y = 0;
pmapbits = 8; // default to 8 bits for older saves
}
bool GameSave::Collapsed()
{
return !expanded;
}
void GameSave::Expand()
{
if(hasOriginalData && !expanded)
{
InitVars();
expanded = true;
read(&originalData[0], originalData.size());
}
}
void GameSave::Collapse()
{
if(expanded && hasOriginalData)
{
expanded = false;
dealloc();
signs.clear();
}
}
void GameSave::read(char * data, int dataSize)
{
if(dataSize > 15)
{
if ((data[0]==0x66 && data[1]==0x75 && data[2]==0x43) || (data[0]==0x50 && data[1]==0x53 && data[2]==0x76))
{
readPSv(data, dataSize);
}
else if(data[0] == 'O' && data[1] == 'P' && data[2] == 'S')
{
if (data[3] != '1')
throw ParseException(ParseException::WrongVersion, "Save format from newer version");
readOPS(data, dataSize);
}
else
{
std::cerr << "Got Magic number '" << data[0] << data[1] << data[2] << "'" << std::endl;
throw ParseException(ParseException::Corrupt, "Invalid save format");
}
}
else
{
throw ParseException(ParseException::Corrupt, "No data");
}
}
template <typename T>
T ** GameSave::Allocate2DArray(int blockWidth, int blockHeight, T defaultVal)
{
T ** temp = new T*[blockHeight];
for (int y = 0; y < blockHeight; y++)
{
temp[y] = new T[blockWidth];
std::fill(&temp[y][0], &temp[y][0]+blockWidth, defaultVal);
}
return temp;
}
void GameSave::setSize(int newWidth, int newHeight)
{
this->blockWidth = newWidth;
this->blockHeight = newHeight;
particlesCount = 0;
particles = new Particle[NPART];
blockMap = Allocate2DArray<unsigned char>(blockWidth, blockHeight, 0);
fanVelX = Allocate2DArray<float>(blockWidth, blockHeight, 0.0f);
fanVelY = Allocate2DArray<float>(blockWidth, blockHeight, 0.0f);
pressure = Allocate2DArray<float>(blockWidth, blockHeight, 0.0f);
velocityX = Allocate2DArray<float>(blockWidth, blockHeight, 0.0f);
velocityY = Allocate2DArray<float>(blockWidth, blockHeight, 0.0f);
ambientHeat = Allocate2DArray<float>(blockWidth, blockHeight, 0.0f);
}
std::vector<char> GameSave::Serialise()
{
unsigned int dataSize;
char * data = Serialise(dataSize);
if (data == NULL)
return std::vector<char>();
std::vector<char> dataVect(data, data+dataSize);
delete[] data;
return dataVect;
}
char * GameSave::Serialise(unsigned int & dataSize)
{
try
{
return serialiseOPS(dataSize);
}
catch (BuildException e)
{
std::cout << e.what() << std::endl;
return NULL;
}
}
vector2d GameSave::Translate(vector2d translate)
{
if (Collapsed())
Expand();
int nx, ny;
vector2d pos;
vector2d translateReal = translate;
float minx = 0, miny = 0, maxx = 0, maxy = 0;
// determine minimum and maximum position of all particles / signs
for (size_t i = 0; i < signs.size(); i++)
{
pos = v2d_new(signs[i].x, signs[i].y);
pos = v2d_add(pos,translate);
nx = floor(pos.x+0.5f);
ny = floor(pos.y+0.5f);
if (nx < minx)
minx = nx;
if (ny < miny)
miny = ny;
if (nx > maxx)
maxx = nx;
if (ny > maxy)
maxy = ny;
}
for (int i = 0; i < particlesCount; i++)
{
if (!particles[i].type) continue;
pos = v2d_new(particles[i].x, particles[i].y);
pos = v2d_add(pos,translate);
nx = floor(pos.x+0.5f);
ny = floor(pos.y+0.5f);
if (nx < minx)
minx = nx;
if (ny < miny)
miny = ny;
if (nx > maxx)
maxx = nx;
if (ny > maxy)
maxy = ny;
}
// determine whether corrections are needed. If moving in this direction would delete stuff, expand the save
vector2d backCorrection = v2d_new(
(minx < 0) ? (-floor(minx / CELL)) : 0,
(miny < 0) ? (-floor(miny / CELL)) : 0
);
int blockBoundsX = int(maxx / CELL) + 1, blockBoundsY = int(maxy / CELL) + 1;
vector2d frontCorrection = v2d_new(
(blockBoundsX > blockWidth) ? (blockBoundsX - blockWidth) : 0,
(blockBoundsY > blockHeight) ? (blockBoundsY - blockHeight) : 0
);
// get new width based on corrections
int newWidth = (blockWidth + backCorrection.x + frontCorrection.x) * CELL;
int newHeight = (blockHeight + backCorrection.y + frontCorrection.y) * CELL;
if (newWidth > XRES)
frontCorrection.x = backCorrection.x = 0;
if (newHeight > YRES)
frontCorrection.y = backCorrection.y = 0;
// call Transform to do the transformation we wanted when calling this function
translate = v2d_add(translate, v2d_multiply_float(backCorrection, CELL));
Transform(m2d_identity, translate, translateReal,
(blockWidth + backCorrection.x + frontCorrection.x) * CELL,
(blockHeight + backCorrection.y + frontCorrection.y) * CELL
);
// return how much we corrected. This is used to offset the position of the current stamp
// otherwise it would attempt to recenter it with the current size
return v2d_add(v2d_multiply_float(backCorrection, -CELL), v2d_multiply_float(frontCorrection, CELL));
}
void GameSave::Transform(matrix2d transform, vector2d translate)
{
if (Collapsed())
Expand();
int width = blockWidth*CELL, height = blockHeight*CELL, newWidth, newHeight;
vector2d tmp, ctl, cbr;
vector2d cornerso[4];
vector2d translateReal = translate;
// undo any translation caused by rotation
cornerso[0] = v2d_new(0,0);
cornerso[1] = v2d_new(width-1,0);
cornerso[2] = v2d_new(0,height-1);
cornerso[3] = v2d_new(width-1,height-1);
for (int i = 0; i < 4; i++)
{
tmp = m2d_multiply_v2d(transform,cornerso[i]);
if (i==0) ctl = cbr = tmp; // top left, bottom right corner
if (tmp.x<ctl.x) ctl.x = tmp.x;
if (tmp.y<ctl.y) ctl.y = tmp.y;
if (tmp.x>cbr.x) cbr.x = tmp.x;
if (tmp.y>cbr.y) cbr.y = tmp.y;
}
// casting as int doesn't quite do what we want with negative numbers, so use floor()
tmp = v2d_new(floor(ctl.x+0.5f),floor(ctl.y+0.5f));
translate = v2d_sub(translate,tmp);
newWidth = floor(cbr.x+0.5f)-floor(ctl.x+0.5f)+1;
newHeight = floor(cbr.y+0.5f)-floor(ctl.y+0.5f)+1;
Transform(transform, translate, translateReal, newWidth, newHeight);
}
// transform is a matrix describing how we want to rotate this save
// translate can vary depending on whether the save is bring rotated, or if a normal translate caused it to expand
// translateReal is the original amount we tried to translate, used to calculate wall shifting
void GameSave::Transform(matrix2d transform, vector2d translate, vector2d translateReal, int newWidth, int newHeight)
{
if (Collapsed())
Expand();
if (newWidth>XRES) newWidth = XRES;
if (newHeight>YRES) newHeight = YRES;
int x, y, nx, ny, newBlockWidth = newWidth / CELL, newBlockHeight = newHeight / CELL;
vector2d pos, vel;
unsigned char ** blockMapNew;
float **fanVelXNew, **fanVelYNew, **pressureNew, **velocityXNew, **velocityYNew, **ambientHeatNew;
blockMapNew = Allocate2DArray<unsigned char>(newBlockWidth, newBlockHeight, 0);
fanVelXNew = Allocate2DArray<float>(newBlockWidth, newBlockHeight, 0.0f);
fanVelYNew = Allocate2DArray<float>(newBlockWidth, newBlockHeight, 0.0f);
pressureNew = Allocate2DArray<float>(newBlockWidth, newBlockHeight, 0.0f);
velocityXNew = Allocate2DArray<float>(newBlockWidth, newBlockHeight, 0.0f);
velocityYNew = Allocate2DArray<float>(newBlockWidth, newBlockHeight, 0.0f);
ambientHeatNew = Allocate2DArray<float>(newBlockWidth, newBlockHeight, 0.0f);
// rotate and translate signs, parts, walls
for (size_t i = 0; i < signs.size(); i++)
{
pos = v2d_new(signs[i].x, signs[i].y);
pos = v2d_add(m2d_multiply_v2d(transform,pos),translate);
nx = floor(pos.x+0.5f);
ny = floor(pos.y+0.5f);
if (nx<0 || nx>=newWidth || ny<0 || ny>=newHeight)
{
signs[i].text[0] = 0;
continue;
}
signs[i].x = nx;
signs[i].y = ny;
}
for (int i = 0; i < particlesCount; i++)
{
if (!particles[i].type) continue;
pos = v2d_new(particles[i].x, particles[i].y);
pos = v2d_add(m2d_multiply_v2d(transform,pos),translate);
nx = floor(pos.x+0.5f);
ny = floor(pos.y+0.5f);
if (nx<0 || nx>=newWidth || ny<0 || ny>=newHeight)
{
particles[i].type = PT_NONE;
continue;
}
particles[i].x = nx;
particles[i].y = ny;
vel = v2d_new(particles[i].vx, particles[i].vy);
vel = m2d_multiply_v2d(transform, vel);
particles[i].vx = vel.x;
particles[i].vy = vel.y;
}
// translate walls and other grid items when the stamp is shifted more than 4 pixels in any direction
int translateX = 0, translateY = 0;
if (translateReal.x > 0 && ((int)translated.x%CELL == 3
|| (translated.x < 0 && (int)translated.x%CELL == 0)))
translateX = CELL;
else if (translateReal.x < 0 && ((int)translated.x%CELL == -3
|| (translated.x > 0 && (int)translated.x%CELL == 0)))
translateX = -CELL;
if (translateReal.y > 0 && ((int)translated.y%CELL == 3
|| (translated.y < 0 && (int)translated.y%CELL == 0)))
translateY = CELL;
else if (translateReal.y < 0 && ((int)translated.y%CELL == -3
|| (translated.y > 0 && (int)translated.y%CELL == 0)))
translateY = -CELL;
for (y=0; y<blockHeight; y++)
for (x=0; x<blockWidth; x++)
{
pos = v2d_new(x*CELL+CELL*0.4f+translateX, y*CELL+CELL*0.4f+translateY);
pos = v2d_add(m2d_multiply_v2d(transform,pos),translate);
nx = pos.x/CELL;
ny = pos.y/CELL;
if (pos.x<0 || nx>=newBlockWidth || pos.y<0 || ny>=newBlockHeight)
continue;
if (blockMap[y][x])
{
blockMapNew[ny][nx] = blockMap[y][x];
if (blockMap[y][x]==WL_FAN)
{
vel = v2d_new(fanVelX[y][x], fanVelY[y][x]);
vel = m2d_multiply_v2d(transform, vel);
fanVelXNew[ny][nx] = vel.x;
fanVelYNew[ny][nx] = vel.y;
}
}
pressureNew[ny][nx] = pressure[y][x];
velocityXNew[ny][nx] = velocityX[y][x];
velocityYNew[ny][nx] = velocityY[y][x];
ambientHeatNew[ny][nx] = ambientHeat[y][x];
}
translated = v2d_add(m2d_multiply_v2d(transform, translated), translateReal);
for (int j = 0; j < blockHeight; j++)
{
delete[] blockMap[j];
delete[] fanVelX[j];
delete[] fanVelY[j];
delete[] pressure[j];
delete[] velocityX[j];
delete[] velocityY[j];
delete[] ambientHeat[j];
}
blockWidth = newBlockWidth;
blockHeight = newBlockHeight;
delete[] blockMap;
delete[] fanVelX;
delete[] fanVelY;
delete[] pressure;
delete[] velocityX;
delete[] velocityY;
delete[] ambientHeat;
blockMap = blockMapNew;
fanVelX = fanVelXNew;
fanVelY = fanVelYNew;
pressure = pressureNew;
velocityX = velocityXNew;
velocityY = velocityYNew;
ambientHeat = ambientHeatNew;
}
void GameSave::CheckBsonFieldUser(bson_iterator iter, const char *field, unsigned char **data, unsigned int *fieldLen)
{
if (!strcmp(bson_iterator_key(&iter), field))
{
if (bson_iterator_type(&iter)==BSON_BINDATA && ((unsigned char)bson_iterator_bin_type(&iter))==BSON_BIN_USER && (*fieldLen = bson_iterator_bin_len(&iter)) > 0)
{
*data = (unsigned char*)bson_iterator_bin_data(&iter);
}
else
{
fprintf(stderr, "Invalid datatype for %s: %d[%d] %d[%d] %d[%d]\n", field, bson_iterator_type(&iter), bson_iterator_type(&iter)==BSON_BINDATA, (unsigned char)bson_iterator_bin_type(&iter), ((unsigned char)bson_iterator_bin_type(&iter))==BSON_BIN_USER, bson_iterator_bin_len(&iter), bson_iterator_bin_len(&iter)>0);
}
}
}
void GameSave::CheckBsonFieldBool(bson_iterator iter, const char *field, bool *flag)
{
if (!strcmp(bson_iterator_key(&iter), field))
{
if (bson_iterator_type(&iter) == BSON_BOOL)
{
*flag = bson_iterator_bool(&iter);
}
else
{
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter));
}
}
}
void GameSave::CheckBsonFieldInt(bson_iterator iter, const char *field, int *setting)
{
if (!strcmp(bson_iterator_key(&iter), field))
{
if (bson_iterator_type(&iter) == BSON_INT)
{
*setting = bson_iterator_int(&iter);
}
else
{
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter));
}
}
}
void GameSave::readOPS(char * data, int dataLength)
{
unsigned char *inputData = (unsigned char*)data, *bsonData = NULL, *partsData = NULL, *partsPosData = NULL, *fanData = NULL, *wallData = NULL, *soapLinkData = NULL;
unsigned char *pressData = NULL, *vxData = NULL, *vyData = NULL, *ambientData = NULL;
unsigned int inputDataLen = dataLength, bsonDataLen = 0, partsDataLen, partsPosDataLen, fanDataLen, wallDataLen, soapLinkDataLen;
unsigned int pressDataLen, vxDataLen, vyDataLen, ambientDataLen;
unsigned partsCount = 0;
unsigned int blockX, blockY, blockW, blockH, fullX, fullY, fullW, fullH;
int savedVersion = inputData[4];
majorVersion = savedVersion;
bool fakeNewerVersion = false; // used for development builds only
bson b;
b.data = NULL;
bson_iterator iter;
auto bson_deleter = [](bson * b) { bson_destroy(b); };
// Use unique_ptr with a custom deleter to ensure that bson_destroy is called even when an exception is thrown
std::unique_ptr<bson, decltype(bson_deleter)> b_ptr(&b, bson_deleter);
//Block sizes
blockX = 0;
blockY = 0;
blockW = inputData[6];
blockH = inputData[7];
//Full size, normalised
fullX = blockX*CELL;
fullY = blockY*CELL;
fullW = blockW*CELL;
fullH = blockH*CELL;
//From newer version
if (savedVersion > SAVE_VERSION)
{
fromNewerVersion = true;
//throw ParseException(ParseException::WrongVersion, "Save from newer version");
}
//Incompatible cell size
if (inputData[5] > CELL)
throw ParseException(ParseException::InvalidDimensions, "Incorrect CELL size");
//Too large/off screen
if (blockX+blockW > XRES/CELL || blockY+blockH > YRES/CELL)
throw ParseException(ParseException::InvalidDimensions, "Save too large");
setSize(blockW, blockH);
bsonDataLen = ((unsigned)inputData[8]);
bsonDataLen |= ((unsigned)inputData[9]) << 8;
bsonDataLen |= ((unsigned)inputData[10]) << 16;
bsonDataLen |= ((unsigned)inputData[11]) << 24;
//Check for overflows, don't load saves larger than 200MB
unsigned int toAlloc = bsonDataLen+1;
if (toAlloc > 209715200 || !toAlloc)
throw ParseException(ParseException::InvalidDimensions, "Save data too large, refusing");
bsonData = (unsigned char*)malloc(toAlloc);
if (!bsonData)
throw ParseException(ParseException::InternalError, "Unable to allocate memory");
//Make sure bsonData is null terminated, since all string functions need null terminated strings
//(bson_iterator_key returns a pointer into bsonData, which is then used with strcmp)
bsonData[bsonDataLen] = 0;
int bz2ret;
if ((bz2ret = BZ2_bzBuffToBuffDecompress((char*)bsonData, &bsonDataLen, (char*)(inputData+12), inputDataLen-12, 0, 0)) != BZ_OK)
{
throw ParseException(ParseException::Corrupt, String::Build("Unable to decompress (ret ", bz2ret, ")"));
}
set_bson_err_handler([](const char* err) { throw ParseException(ParseException::Corrupt, "BSON error when parsing save: " + ByteString(err).FromUtf8()); });
bson_init_data_size(&b, (char*)bsonData, bsonDataLen);
bson_iterator_init(&iter, &b);
std::vector<sign> tempSigns;
while (bson_iterator_next(&iter))
{
CheckBsonFieldUser(iter, "parts", &partsData, &partsDataLen);
CheckBsonFieldUser(iter, "partsPos", &partsPosData, &partsPosDataLen);
CheckBsonFieldUser(iter, "wallMap", &wallData, &wallDataLen);
CheckBsonFieldUser(iter, "pressMap", &pressData, &pressDataLen);
CheckBsonFieldUser(iter, "vxMap", &vxData, &vxDataLen);
CheckBsonFieldUser(iter, "vyMap", &vyData, &vyDataLen);
CheckBsonFieldUser(iter, "ambientMap", &ambientData, &ambientDataLen);
CheckBsonFieldUser(iter, "fanMap", &fanData, &fanDataLen);
CheckBsonFieldUser(iter, "soapLinks", &soapLinkData, &soapLinkDataLen);
CheckBsonFieldBool(iter, "legacyEnable", &legacyEnable);
CheckBsonFieldBool(iter, "gravityEnable", &gravityEnable);
CheckBsonFieldBool(iter, "aheat_enable", &aheatEnable);
CheckBsonFieldBool(iter, "waterEEnabled", &waterEEnabled);
CheckBsonFieldBool(iter, "paused", &paused);
CheckBsonFieldInt(iter, "gravityMode", &gravityMode);
CheckBsonFieldInt(iter, "airMode", &airMode);
CheckBsonFieldInt(iter, "edgeMode", &edgeMode);
CheckBsonFieldInt(iter, "pmapbits", &pmapbits);
if (!strcmp(bson_iterator_key(&iter), "signs"))
{
if (bson_iterator_type(&iter)==BSON_ARRAY)
{
bson_iterator subiter;
bson_iterator_subiterator(&iter, &subiter);
while (bson_iterator_next(&subiter))
{
if (!strcmp(bson_iterator_key(&subiter), "sign"))
{
if (bson_iterator_type(&subiter) == BSON_OBJECT)
{
bson_iterator signiter;
bson_iterator_subiterator(&subiter, &signiter);
sign tempSign("", 0, 0, sign::Left);
while (bson_iterator_next(&signiter))
{
if (!strcmp(bson_iterator_key(&signiter), "text") && bson_iterator_type(&signiter) == BSON_STRING)
{
tempSign.text = format::CleanString(ByteString(bson_iterator_string(&signiter)).FromUtf8(), true, true, true).Substr(0, 45);
}
else if (!strcmp(bson_iterator_key(&signiter), "justification") && bson_iterator_type(&signiter) == BSON_INT)
{
tempSign.ju = (sign::Justification)bson_iterator_int(&signiter);
}
else if (!strcmp(bson_iterator_key(&signiter), "x") && bson_iterator_type(&signiter) == BSON_INT)
{
tempSign.x = bson_iterator_int(&signiter)+fullX;
}
else if (!strcmp(bson_iterator_key(&signiter), "y") && bson_iterator_type(&signiter) == BSON_INT)
{
tempSign.y = bson_iterator_int(&signiter)+fullY;
}
else
{
fprintf(stderr, "Unknown sign property %s\n", bson_iterator_key(&signiter));
}
}
tempSigns.push_back(tempSign);
}
else
{
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&subiter));
}
}
}
}
else
{
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter));
}
}
else if (!strcmp(bson_iterator_key(&iter), "stkm"))
{
if (bson_iterator_type(&iter) == BSON_OBJECT)
{
bson_iterator stkmiter;
bson_iterator_subiterator(&iter, &stkmiter);
while (bson_iterator_next(&stkmiter))
{
CheckBsonFieldBool(stkmiter, "rocketBoots1", &stkm.rocketBoots1);
CheckBsonFieldBool(stkmiter, "rocketBoots1", &stkm.rocketBoots1);
CheckBsonFieldBool(stkmiter, "fan1", &stkm.fan1);
CheckBsonFieldBool(stkmiter, "fan2", &stkm.fan2);
if (!strcmp(bson_iterator_key(&stkmiter), "rocketBootsFigh") && bson_iterator_type(&stkmiter) == BSON_ARRAY)
{
bson_iterator fighiter;
bson_iterator_subiterator(&stkmiter, &fighiter);
while (bson_iterator_next(&fighiter))
{
if (bson_iterator_type(&fighiter) == BSON_INT)
stkm.rocketBootsFigh.push_back(bson_iterator_int(&fighiter));
}
}
else if (!strcmp(bson_iterator_key(&stkmiter), "fanFigh") && bson_iterator_type(&stkmiter) == BSON_ARRAY)
{
bson_iterator fighiter;
bson_iterator_subiterator(&stkmiter, &fighiter);
while (bson_iterator_next(&fighiter))
{
if (bson_iterator_type(&fighiter) == BSON_INT)
stkm.fanFigh.push_back(bson_iterator_int(&fighiter));
}
}
else
fprintf(stderr, "Unknown stkm property %s\n", bson_iterator_key(&stkmiter));
}
}
else
{
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter));
}
}
else if (!strcmp(bson_iterator_key(&iter), "palette"))
{
palette.clear();
if (bson_iterator_type(&iter) == BSON_ARRAY)
{
bson_iterator subiter;
bson_iterator_subiterator(&iter, &subiter);
while (bson_iterator_next(&subiter))
{
if (bson_iterator_type(&subiter) == BSON_INT)
{
ByteString id = bson_iterator_key(&subiter);
int num = bson_iterator_int(&subiter);
palette.push_back(PaletteItem(id, num));
}
}
}
}
else if (!strcmp(bson_iterator_key(&iter), "minimumVersion"))
{
if (bson_iterator_type(&iter) == BSON_OBJECT)
{
int major = INT_MAX, minor = INT_MAX;
#ifdef RENDERER
int renderMajor = INT_MAX, renderMinor = INT_MAX;
#endif
bson_iterator subiter;
bson_iterator_subiterator(&iter, &subiter);
while (bson_iterator_next(&subiter))
{
if (bson_iterator_type(&subiter) == BSON_INT)
{
#ifdef RENDERER
if (!strcmp(bson_iterator_key(&subiter), "rendermajor"))
renderMajor = bson_iterator_int(&subiter);
else if (!strcmp(bson_iterator_key(&subiter), "renderminor"))
renderMinor = bson_iterator_int(&subiter);
#else
if (!strcmp(bson_iterator_key(&subiter), "major"))
major = bson_iterator_int(&subiter);
else if (!strcmp(bson_iterator_key(&subiter), "minor"))
minor = bson_iterator_int(&subiter);
#endif
}
}
#ifdef RENDERER
if (renderMajor > SAVE_VERSION || (renderMajor == SAVE_VERSION && renderMinor > MINOR_VERSION))
#elif defined(SNAPSHOT) || defined(DEBUG)
if (major > FUTURE_SAVE_VERSION || (major == FUTURE_SAVE_VERSION && minor > FUTURE_MINOR_VERSION))
#else
if (major > SAVE_VERSION || (major == SAVE_VERSION && minor > MINOR_VERSION))
#endif
{
#ifdef RENDERER
String errorMessage = String::Build("Save from a newer version: Requires render version ", renderMajor, ".", renderMinor);
#else
String errorMessage = String::Build("Save from a newer version: Requires version ", major, ".", minor);
#endif
throw ParseException(ParseException::WrongVersion, errorMessage);
}
#if defined(SNAPSHOT) || defined(DEBUG)
else if (major > SAVE_VERSION || (major == SAVE_VERSION && minor > MINOR_VERSION))
fakeNewerVersion = true;
#endif
}
else
{
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter));
}
}
#ifndef RENDERER
else if (!strcmp(bson_iterator_key(&iter), "authors"))
{
if (bson_iterator_type(&iter) == BSON_OBJECT)
{
// we need to clear authors because the save may be read multiple times in the stamp browser (loading and rendering twice)
// seems inefficient ...
authors.clear();
ConvertBsonToJson(&iter, &authors);
}
else
{
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter));
}
}
#endif
}
//Read wall and fan data
if(wallData)
{
unsigned int j = 0;
if (blockW * blockH > wallDataLen)
throw ParseException(ParseException::Corrupt, "Not enough wall data");
for (unsigned int x = 0; x < blockW; x++)
{
for (unsigned int y = 0; y < blockH; y++)
{
if (wallData[y*blockW+x])
blockMap[blockY+y][blockX+x] = wallData[y*blockW+x];
if (blockMap[y][x]==O_WL_WALLELEC)
blockMap[y][x]=WL_WALLELEC;
if (blockMap[y][x]==O_WL_EWALL)
blockMap[y][x]=WL_EWALL;
if (blockMap[y][x]==O_WL_DETECT)
blockMap[y][x]=WL_DETECT;
if (blockMap[y][x]==O_WL_STREAM)
blockMap[y][x]=WL_STREAM;
if (blockMap[y][x]==O_WL_FAN||blockMap[y][x]==O_WL_FANHELPER)
blockMap[y][x]=WL_FAN;
if (blockMap[y][x]==O_WL_ALLOWLIQUID)
blockMap[y][x]=WL_ALLOWLIQUID;
if (blockMap[y][x]==O_WL_DESTROYALL)
blockMap[y][x]=WL_DESTROYALL;
if (blockMap[y][x]==O_WL_ERASE)
blockMap[y][x]=WL_ERASE;
if (blockMap[y][x]==O_WL_WALL)
blockMap[y][x]=WL_WALL;
if (blockMap[y][x]==O_WL_ALLOWAIR)
blockMap[y][x]=WL_ALLOWAIR;
if (blockMap[y][x]==O_WL_ALLOWSOLID)
blockMap[y][x]=WL_ALLOWPOWDER;
if (blockMap[y][x]==O_WL_ALLOWALLELEC)
blockMap[y][x]=WL_ALLOWALLELEC;
if (blockMap[y][x]==O_WL_EHOLE)
blockMap[y][x]=WL_EHOLE;
if (blockMap[y][x]==O_WL_ALLOWGAS)
blockMap[y][x]=WL_ALLOWGAS;
if (blockMap[y][x]==O_WL_GRAV)
blockMap[y][x]=WL_GRAV;
if (blockMap[y][x]==O_WL_ALLOWENERGY)
blockMap[y][x]=WL_ALLOWENERGY;
if (blockMap[y][x] == WL_FAN && fanData)
{
if(j+1 >= fanDataLen)
{
fprintf(stderr, "Not enough fan data\n");
}
fanVelX[blockY+y][blockX+x] = (fanData[j++]-127.0f)/64.0f;
fanVelY[blockY+y][blockX+x] = (fanData[j++]-127.0f)/64.0f;
}
if (blockMap[y][x] >= UI_WALLCOUNT)
blockMap[y][x] = 0;
}
}
}
//Read pressure data
if (pressData)
{
unsigned int j = 0;
unsigned char i, i2;
if (blockW * blockH > pressDataLen)
throw ParseException(ParseException::Corrupt, "Not enough pressure data");
for (unsigned int x = 0; x < blockW; x++)
{
for (unsigned int y = 0; y < blockH; y++)
{
i = pressData[j++];
i2 = pressData[j++];
pressure[blockY+y][blockX+x] = ((i+(i2<<8))/128.0f)-256;
}
}
hasPressure = true;
}
//Read vx data
if (vxData)
{
unsigned int j = 0;
unsigned char i, i2;
if (blockW * blockH > vxDataLen)
throw ParseException(ParseException::Corrupt, "Not enough vx data");
for (unsigned int x = 0; x < blockW; x++)
{
for (unsigned int y = 0; y < blockH; y++)
{
i = vxData[j++];
i2 = vxData[j++];
velocityX[blockY+y][blockX+x] = ((i+(i2<<8))/128.0f)-256;
}
}
}
//Read vy data
if (vyData)
{
unsigned int j = 0;
unsigned char i, i2;
if (blockW * blockH > vyDataLen)
throw ParseException(ParseException::Corrupt, "Not enough vy data");
for (unsigned int x = 0; x < blockW; x++)
{
for (unsigned int y = 0; y < blockH; y++)
{
i = vyData[j++];
i2 = vyData[j++];
velocityY[blockY+y][blockX+x] = ((i+(i2<<8))/128.0f)-256;
}
}
}
//Read ambient data
if (ambientData)
{
unsigned int i = 0, tempTemp;
if (blockW * blockH > ambientDataLen)
throw ParseException(ParseException::Corrupt, "Not enough ambient heat data");
for (unsigned int x = 0; x < blockW; x++)
{
for (unsigned int y = 0; y < blockH; y++)
{
tempTemp = ambientData[i++];
tempTemp |= (((unsigned)ambientData[i++]) << 8);
ambientHeat[blockY+y][blockX+x] = tempTemp;
}
}
hasAmbientHeat = true;
}
//Read particle data
if (partsData && partsPosData)
{
int newIndex = 0, fieldDescriptor, tempTemp;
int posCount, posTotal, partsPosDataIndex = 0;
if (fullW * fullH * 3 > partsPosDataLen)
throw ParseException(ParseException::Corrupt, "Not enough particle position data");
partsCount = 0;
unsigned int i = 0;
unsigned int saved_x, saved_y, x, y;
newIndex = 0;
for (saved_y = 0; saved_y < fullH; saved_y++)
{
for (saved_x = 0; saved_x < fullW; saved_x++)
{
//Read total number of particles at this position
posTotal = 0;
posTotal |= partsPosData[partsPosDataIndex++]<<16;
posTotal |= partsPosData[partsPosDataIndex++]<<8;
posTotal |= partsPosData[partsPosDataIndex++];
//Put the next posTotal particles at this position
for (posCount = 0; posCount < posTotal; posCount++)
{
particlesCount = newIndex+1;