-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsav_cli.py
More file actions
executable file
·4046 lines (3485 loc) · 217 KB
/
sav_cli.py
File metadata and controls
executable file
·4046 lines (3485 loc) · 217 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
#!/usr/bin/env python3
# This file is part of the Satisfactory Save Parser distribution
# (https://github.com/GreyHak/sat_sav_parse).
# Copyright (c) 2024-2026 GreyHak (github.com/GreyHak).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import enum
import datetime
import json
import math
import os
import sys
import uuid
import sav_parse
import sav_to_resave
import sav_data.data
try:
import sav_to_html
from PIL import Image, ImageDraw, ImageFont
pilAvailableFlag = True
except ModuleNotFoundError:
pilAvailableFlag = False
VERIFY_CREATED_SAVE_FILES = False
USERNAME_FILENAME = "sav_cli_usernames.json"
CHECK_ITEMS_FOR_PLAYER_INVENTORY = False
UNCOLLECTED_MAP_MARKER_SCALE = 0.5
ENFORCE_MAP_MARKER_LIMIT = 250 # Critical for servers that will delete all map markers if above the limit.
DEFAULT_ICON_ID_FOR_NEW_CATEGORIES = sav_data.data.ICON_NAMES_TO_IDS["FICSIT Check Mark"]
def getBlankCategory(objectGameVersion: int, categoryName: str, iconId: int = -1) -> list:
if objectGameVersion < 53:
return [[['CategoryName', categoryName],
['IconID', iconId],
['MenuPriority', 0.0],
['IsUndefined', False],
['SubCategoryRecords',
[[[['SubCategoryName', 'Undefined'],
['MenuPriority', 0.0],
['IsUndefined', ["None", 1]],
['BlueprintNames', []]],
[['SubCategoryName', 'StrProperty', 0],
['MenuPriority', 'FloatProperty', 0],
['IsUndefined', 'ByteProperty', 0],
['BlueprintNames', 'ArrayProperty', 0, 'StrProperty', 0]]]]]],
[['CategoryName', 'StrProperty', 0],
['IconID', 'IntProperty', 0],
['MenuPriority', 'FloatProperty', 0],
['IsUndefined', 'BoolProperty', 0],
['SubCategoryRecords', 'ArrayProperty', 0, 'StructProperty', 0, 'BlueprintSubCategoryRecord', None]]]
else:
if iconId == -1:
iconId = DEFAULT_ICON_ID_FOR_NEW_CATEGORIES
return [[['CategoryName', categoryName],
['IconID', iconId],
['MenuPriority', 0.0],
['IsUndefined', 0],
['SubCategoryRecords',
[[[['SubCategoryName', 'Undefined'],
['MenuPriority', 0.0],
['IsUndefined', [None, 0]],
['BlueprintNames', []],
['lastEditedBy', b'\x06\x00\x00\x00\x00']],
[['SubCategoryName', 'StrProperty', 0],
['MenuPriority', 'FloatProperty', 0],
['IsUndefined', 'ByteProperty', 0],
['BlueprintNames', 'ArrayProperty', 1, 'StrProperty', 0, 0],
['lastEditedBy', 'StructProperty', 1, 'PlayerInfoHandle', ['/Script/FactoryGame'], 8]]]]],
['lastEditedBy', b'\x06\x00\x00\x00\x00']],
[['CategoryName', 'StrProperty', 0],
['IconID', 'IntProperty', 0],
['MenuPriority', 'FloatProperty', 0],
['IsUndefined', 'BoolProperty', 0],
['SubCategoryRecords', 'ArrayProperty', 1, 'StructProperty', 1, 'BlueprintSubCategoryRecord', ['/Script/FactoryGame'], 0],
['lastEditedBy', 'StructProperty', 1, 'PlayerInfoHandle', ['/Script/FactoryGame'], 8]]]
def getBlankSubcategory(objectGameVersion: int, subcategoryName: str) -> list:
if objectGameVersion < 53:
return [[['SubCategoryName', subcategoryName],
['MenuPriority', 0.0],
['IsUndefined', ["None", 1]],
['BlueprintNames', []]],
[['SubCategoryName', 'StrProperty', 0],
['MenuPriority', 'FloatProperty', 0],
['IsUndefined', 'ByteProperty', 0],
['BlueprintNames', 'ArrayProperty', 0, 'StrProperty', 0]]]
else:
return [[['SubCategoryName', subcategoryName],
['MenuPriority', 0.0],
['IsUndefined', [None, 0]],
['BlueprintNames', []],
['lastEditedBy', b'\x06\x00\x00\x00\x00']],
[['SubCategoryName', 'StrProperty', 0],
['MenuPriority', 'FloatProperty', 0],
['IsUndefined', 'ByteProperty', 0],
['BlueprintNames', 'ArrayProperty', 1, 'StrProperty', 0, 0],
['lastEditedBy', 'StructProperty', 1, 'PlayerInfoHandle', ['/Script/FactoryGame'], 8]]]
playerUsernames: dict[str, str] = {}
def getPlayerPaths(levels: list) -> list:
playerPaths = [] # = (playerStateInstanceName, characterPlayer, inventoryPath, armsPath, backPath, legsPath, headPath, bodyPath, healthPath)
playerStateInstances = []
for level in levels:
for actorOrComponentObjectHeader in level.actorAndComponentObjectHeaders:
# "/Game/FactoryGame/Character/Player/BP_PlayerState.BP_PlayerState_C" leads to ShoppingListComponent, FGPlayerHotbar_*
# This gives the "mOwnedPawn" property which gives the Char_Player_C. These are different numbers.
# "/Game/FactoryGame/Character/Player/Char_Player.Char_Player_C" leads to BodySlot, HeadSlot, HealthComponent, LegsSlot, BackSlot, ArmSlot, inventory
if isinstance(actorOrComponentObjectHeader, sav_parse.ActorHeader) and actorOrComponentObjectHeader.typePath == "/Game/FactoryGame/Character/Player/BP_PlayerState.BP_PlayerState_C":
playerStateInstances.append(actorOrComponentObjectHeader.instanceName)
playerCharacterInstances = {} # Looked up by playerCharacter for the playerState value
for level in levels:
for object in level.objects:
if object.instanceName in playerStateInstances:
# mPlayerHotbars, mCurrentHotbarIndex, mBuildableSubCategoryDefaultMatDesc, mMaterialSubCategoryDefaultMatDesc, mNewRecipes, mPlayerRules, mOwnedPawn,
# mHasReceivedInitialItems, mVisitedAreas, mCustomColorData, mRememberedFirstTimeEquipmentClasses, mCollapsedMapCategories, mNumObservedInventorySlots,
# mShoppingListComponent, mOpenedWidgetsPersistent, mPlayerSpecificSchematics
ownedPawn = sav_parse.getPropertyValue(object.properties, "mOwnedPawn")
if ownedPawn is not None:
playerHotbars = sav_parse.getPropertyValue(object.properties, "mPlayerHotbars")
if playerHotbars is not None:
playerCharacterInstances[ownedPawn.pathName] = (object.instanceName)
for level in levels:
for object in level.objects:
if object.instanceName in playerCharacterInstances:
inventory = sav_parse.getPropertyValue(object.properties, "mInventory")
if inventory is not None:
armsEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mArmsEquipmentSlot")
if armsEquipmentSlot is not None:
backEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mBackEquipmentSlot")
if backEquipmentSlot is not None:
legsEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mLegsEquipmentSlot")
if legsEquipmentSlot is not None:
headEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mHeadEquipmentSlot")
if headEquipmentSlot is not None:
bodyEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mBodyEquipmentSlot")
if bodyEquipmentSlot is not None:
healthComponent = sav_parse.getPropertyValue(object.properties, "mHealthComponent")
if healthComponent is not None:
(playerStateInstanceName) = playerCharacterInstances[object.instanceName]
playerPaths.append((playerStateInstanceName, object.instanceName, inventory.pathName, armsEquipmentSlot.pathName, backEquipmentSlot.pathName, legsEquipmentSlot.pathName, headEquipmentSlot.pathName, bodyEquipmentSlot.pathName, healthComponent.pathName))
return playerPaths
def getPlayerName(levels: list, playerCharacter: str) -> str | None:
global playerUsernames
loc = playerCharacter.rfind("_")
playerId = playerCharacter[loc+1:]
if playerId in playerUsernames:
return playerUsernames[playerId]
for level in levels:
for object in level.objects:
if object.instanceName == playerCharacter:
cachedPlayerName = sav_parse.getPropertyValue(object.properties, "mCachedPlayerName")
if cachedPlayerName is not None:
return cachedPlayerName
return None
def characterPlayerMatch(characterPlayer: str, playerId: str, levels: dict[dict]) -> bool:
return characterPlayer == f"Persistent_Level:PersistentLevel.Char_Player_C_{playerId}" or playerId == getPlayerName(levels, characterPlayer)
def orderBlueprintCategoryMenuPriorities(blueprintCategoryRecords) -> None:
for categoryIdx in range(len(blueprintCategoryRecords)):
category = blueprintCategoryRecords[categoryIdx]
for propertyIdx in range(len(category[0])):
if category[0][propertyIdx][0] == "MenuPriority":
# Must preserve the same propertyIdx because the property type is at this index
category[0][propertyIdx] = [category[0][propertyIdx][0], float(categoryIdx)]
subCategoryRecords = sav_parse.getPropertyValue(category[0], "SubCategoryRecords")
if subCategoryRecords is not None:
for subcategoryIdx in range(len(subCategoryRecords)):
subcategory = subCategoryRecords[subcategoryIdx]
for propertyIdx in range(len(subcategory[0])):
if subcategory[0][propertyIdx][0] == "MenuPriority":
# Must preserve the same propertyIdx because the property type is at this index
subcategory[0][propertyIdx] = [subcategory[0][propertyIdx][0], float(subcategoryIdx)]
# Converts an sRGB component in hex to a luminance component (a linear measure of light)
#def hexToLc(channel):
# channel = int(channel, 16)
# channel = channel / 255
# if channel <= 0:
# return 0
# if channel >= 1:
# return 1
# if channel < 0.04045:
# return channel / 12.92
# return pow((channel + 0.055) / 1.055, 2.4)
# Converts a luminance component (a linear measure of light) an sRGB component from 0 to 1
def lcToSRGBFloat(linearCol) -> float:
if linearCol <= 0.0031308:
return linearCol * 12.92
else:
return pow(abs(linearCol), 1.0/2.4) * 1.055 - 0.055
# Converts a luminance component (a linear measure of light) an sRGB component from 0 to 255
def lcToSRGBInt(linearCol) -> int:
return max(0, min(255, round(lcToSRGBFloat(linearCol) * 255)))
def lcTupleToSrgbHex(linearCTuple) -> str:
srgb = ""
for i in range(3):
srgb += "{:x}".format(lcToSRGBInt(linearCTuple[i])).zfill(2)
return srgb
def radiansToDegrees(radians) -> float:
return radians / math.pi * 180
# Credit to Addison Sears-Collins
# From https://automaticaddison.com/how-to-convert-a-quaternion-into-euler-angles-in-python/
def quaternionToEuler(quaternion):
(x, y, z, w) = quaternion
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = math.asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
yaw_z = math.atan2(t3, t4)
return [roll_x, pitch_y, yaw_z] # in radians
# Credit to Addison Sears-Collins
# From https://automaticaddison.com/how-to-convert-euler-angles-to-quaternions-using-python/
def eulerToQuaternion(euler):
(roll, pitch, yaw) = euler
qx = math.sin(roll/2) * math.cos(pitch/2) * math.cos(yaw/2) - math.cos(roll/2) * math.sin(pitch/2) * math.sin(yaw/2)
qy = math.cos(roll/2) * math.sin(pitch/2) * math.cos(yaw/2) + math.sin(roll/2) * math.cos(pitch/2) * math.sin(yaw/2)
qz = math.cos(roll/2) * math.cos(pitch/2) * math.sin(yaw/2) - math.sin(roll/2) * math.sin(pitch/2) * math.cos(yaw/2)
qw = math.cos(roll/2) * math.cos(pitch/2) * math.cos(yaw/2) + math.sin(roll/2) * math.sin(pitch/2) * math.sin(yaw/2)
return (qx, qy, qz, qw)
def toJSON(object):
if object is None or isinstance(object, (str, int, float, bool, complex)):
return object
if isinstance(object, bytes):
return {"jsonhexstr": object.hex()}
if isinstance(object, datetime.datetime):
return object.strftime('%m/%d/%Y %I:%M:%S %p')
if isinstance(object, (tuple, list)):
value = []
for element in object:
value.append(toJSON(element))
return value
if isinstance(object, dict):
value = {}
for key in object:
value[key] = toJSON(object[key])
return value
if isinstance(object, sav_parse.Object):
araData = None
if object.actorReferenceAssociations is not None:
(parentObjectReference, actorComponentReferences) = object.actorReferenceAssociations
acrData = []
for actorComponentReference in actorComponentReferences:
acrData.append(toJSON(actorComponentReference))
araData = {"parentObjectReference": toJSON(parentObjectReference), "actorComponentReferences": acrData}
return {"instanceName": object.instanceName,
"objectGameVersion": object.objectGameVersion,
"smortpFlag": object.shouldMigrateObjectRefsToPersistentFlag,
"actorReferenceAssociations": araData,
"properties": toJSON(object.properties),
"propertyTypes": toJSON(object.propertyTypes),
"actorSpecificInfo": toJSON(object.actorSpecificInfo),
"perObjectVersionData": toJSON(object.perObjectVersionData)}
jdata = {}
for element in object.__dict__:
jdata[element] = toJSON(object.__dict__[element])
return jdata
def fromJSON(object):
if object is None or isinstance(object, (str, int, float, bool, complex)):
return object
if isinstance(object, dict) and len(object) == 1 and "jsonhexstr" in object:
return bytes.fromhex(object["jsonhexstr"])
if isinstance(object, dict) and len(object) == 2 and "levelName" in object and "pathName" in object:
objectReference = sav_parse.ObjectReference()
objectReference.levelName = object["levelName"]
objectReference.pathName = object["pathName"]
return objectReference
if isinstance(object, (tuple, list)):
value = []
for element in object:
value.append(fromJSON(element))
return value
print(object)
return None
def addSomersloop(levels, targetPathName: str) -> bool:
# For those items present in (both) collectables1 and collectables2, remove those,
# and replace the original ActorHeader and Object. Nothing unique is saved in the Object.
for level in levels:
if level.collectables1 is not None:
for collectable in level.collectables1:
if collectable.pathName == targetPathName:
level.collectables1.remove(collectable)
print(f"Clearing removal of {collectable.pathName}")
break
for collectable in level.collectables2:
if collectable.pathName == targetPathName:
level.collectables2.remove(collectable)
instanceName = collectable.pathName
(rootObject, rotation, position, details) = sav_data.somersloop.SOMERSLOOPS[collectable.pathName]
newActor = sav_parse.ActorHeader()
newActor.typePath = sav_parse.SOMERSLOOP
newActor.rootObject = rootObject
newActor.instanceName = instanceName
newActor.flags = 0
newActor.needTransform = False
newActor.rotation = list(rotation)
newActor.position = list(position)
newActor.scale = [1.600000023841858, 1.600000023841858, 1.600000023841858]
newActor.wasPlacedInLevel = True
level.actorAndComponentObjectHeaders.append(newActor)
newObject = sav_parse.Object()
newObject.instanceName = instanceName
newObject.objectGameVersion = parsedSave.saveFileInfo.saveVersion
newObject.shouldMigrateObjectRefsToPersistentFlag = False
nullParentObjectReference = sav_parse.ObjectReference()
newObject.actorReferenceAssociations = [nullParentObjectReference, []]
newObject.properties = []
newObject.propertyTypes = []
newObject.actorSpecificInfo = None
newObject.perObjectVersionData = None
level.objects.append(newObject)
print(f"Restored Somersloop {instanceName} at {position}")
return True
return False
def addMercerSphere(levels, targetPathName: str) -> bool:
# For those items present in (both) collectables1 and collectables2, remove those,
# and replace the original ActorHeader and Object. Nothing unique is saved in the Object.
for level in levels:
if level.collectables1 is not None:
for collectable in level.collectables1:
if collectable.pathName == targetPathName:
level.collectables1.remove(collectable)
print(f"Clearing removal of sphere {collectable.pathName}")
break
for collectable in level.collectables2:
if collectable.pathName == targetPathName:
level.collectables2.remove(collectable)
instanceName = collectable.pathName
(rootObject, rotation, position, details) = sav_data.mercerSphere.MERCER_SPHERES[collectable.pathName]
newActor = sav_parse.ActorHeader()
newActor.typePath = sav_parse.MERCER_SPHERE
newActor.rootObject = rootObject
newActor.instanceName = instanceName
newActor.flags = 0
newActor.needTransform = False
newActor.rotation = list(rotation)
newActor.position = list(position)
newActor.scale = [2.700000047683716, 2.6999998092651367, 2.6999998092651367]
newActor.wasPlacedInLevel = True
level.actorAndComponentObjectHeaders.append(newActor)
newObject = sav_parse.Object()
newObject.instanceName = instanceName
newObject.objectGameVersion = parsedSave.saveFileInfo.saveVersion
newObject.shouldMigrateObjectRefsToPersistentFlag = False
nullParentObjectReference = sav_parse.ObjectReference()
newObject.actorReferenceAssociations = [nullParentObjectReference, []]
newObject.properties = []
newObject.propertyTypes = []
newObject.actorSpecificInfo = None
newObject.perObjectVersionData = None
level.objects.append(newObject)
print(f"Restored Mercer Sphere {instanceName} at {position}")
return True
return False
def addMercerShrine(levels, targetPathName: str) -> bool:
# For those items present in (both) collectables1 and collectables2, remove those,
# and replace the original ActorHeader and Object. Nothing unique is saved in the Object.
for level in levels:
if level.collectables1 is not None:
for collectable in level.collectables1:
if collectable.pathName == targetPathName:
level.collectables1.remove(collectable)
print(f"Clearing removal of shrine {collectable.pathName}")
break
for collectable in level.collectables2:
if collectable.pathName == targetPathName:
level.collectables2.remove(collectable)
# This loop is here because the same entry might be present multiple
# times. Is this an error? It was observed when a save from
# v1.0 without the duplication was opened/resaved in v1.1.1.6.
for duplicate in level.collectables2:
if duplicate.pathName == targetPathName:
print(f"Removing duplicate removed entry for {targetPathName}")
level.collectables2.remove(duplicate)
instanceName = collectable.pathName
(rootObject, rotation, position, scale) = sav_data.mercerSphere.MERCER_SHRINES[collectable.pathName]
newActor = sav_parse.ActorHeader()
newActor.typePath = sav_parse.MERCER_SHRINE
newActor.rootObject = rootObject
newActor.instanceName = instanceName
newActor.flags = 0
newActor.needTransform = False
newActor.rotation = list(rotation)
newActor.position = list(position)
newActor.scale = [scale, scale, scale]
newActor.wasPlacedInLevel = True
level.actorAndComponentObjectHeaders.append(newActor)
newObject = sav_parse.Object()
newObject.instanceName = instanceName
newObject.objectGameVersion = parsedSave.saveFileInfo.saveVersion
newObject.shouldMigrateObjectRefsToPersistentFlag = False
nullParentObjectReference = sav_parse.ObjectReference()
newObject.actorReferenceAssociations = [nullParentObjectReference, []]
newObject.properties = []
newObject.propertyTypes = []
newObject.actorSpecificInfo = None
newObject.perObjectVersionData = None
level.objects.append(newObject)
print(f"Restored Mercer Shrine {instanceName} at {position}")
return True
return False
def removeInstance(levels: list, humanReadableName: str, rootObject, targetInstanceName: str, position = None) -> bool:
removedObjectCollectionReference = sav_parse.ObjectReference()
removedObjectCollectionReference.levelName = rootObject
removedObjectCollectionReference.pathName = targetInstanceName
for level in levels:
for actorOrComponentObjectHeader in level.actorAndComponentObjectHeaders:
if actorOrComponentObjectHeader.instanceName == targetInstanceName:
level.actorAndComponentObjectHeaders.remove(actorOrComponentObjectHeader)
for object in level.objects:
if object.instanceName == targetInstanceName:
level.objects.remove(object)
if level.collectables1 is None:
level.collectables1 = []
level.collectables1.append(removedObjectCollectionReference)
level.collectables2.append(removedObjectCollectionReference)
print(f"Removed {humanReadableName} {targetInstanceName} at {position}")
return True
# If present, removed above. If removed, return False.
for level in levels:
for collectable in level.collectables2:
if collectable.pathName == targetInstanceName:
return False
# If execution gets here, the object isn't present in the save, so add it.
# This has only been observed when collectables1 is missing, so can't just append.
for level in levels:
if level.levelName == rootObject:
print(f"Removed {humanReadableName} {targetInstanceName} at {position} (unvisited)")
if level.collectables1 is not None:
level.collectables1.append(removedObjectCollectionReference)
level.collectables2.append(removedObjectCollectionReference)
return True
print(f"CAUTION: Failed to remove {humanReadableName} {targetInstanceName} at {position}")
return False
def removeSomersloop(levels, targetInstanceName: str) -> bool:
(rootObject, rotation, position, details) = sav_data.somersloop.SOMERSLOOPS[targetInstanceName]
print(f"Removing Somersloop {targetInstanceName} at {position}")
return removeInstance(levels, "Somersloops", rootObject, targetInstanceName, position)
def removeMercerSphere(levels, targetInstanceName: str) -> bool:
(rootObject, rotation, position, details) = sav_data.mercerSphere.MERCER_SPHERES[targetInstanceName]
print(f"Removing Mercer Sphere {targetInstanceName} at {position}")
return removeInstance(levels, "Mercer Sphere", rootObject, targetInstanceName, position)
def removeMercerShrine(levels, targetInstanceName: str) -> bool:
(rootObject, rotation, position, scale) = sav_data.mercerSphere.MERCER_SHRINES[targetInstanceName]
print(f"Removing Mercer Shrine {targetInstanceName} at {position}")
return removeInstance(levels, "Mercer Shrine", rootObject, targetInstanceName, position)
def addMapMarker(levels, markerName: str, markerLocation: list[float, float, float] | tuple[float, float, float], markerIconId_key: str, markerColor: list[float, float, float] | tuple[float, float, float] = (0.6, 0.6, 0.6), markerViewDistance: sav_data.data.ECompassViewDistance = sav_data.data.ECompassViewDistance.CVD_Mid, scale: float = 1.0, subcategory: str = "") -> bool:
if len(markerLocation) != 3:
print(f"ERROR: Invalid markerLocation passed to addMapMarker: {markerLocation}")
return False
if len(markerColor) != 3:
print(f"ERROR: Invalid markerColor passed to addMapMarker: {markerColor}")
return False
for level in levels:
for object in level.objects:
if object.instanceName == "Persistent_Level:PersistentLevel.MapManager":
mapMarkers = sav_parse.getPropertyValue(object.properties, "mMapMarkers")
if mapMarkers is not None:
if isinstance(ENFORCE_MAP_MARKER_LIMIT, int) and ENFORCE_MAP_MARKER_LIMIT > 0 and len(mapMarkers) >= ENFORCE_MAP_MARKER_LIMIT:
print(f"Skipping map marker {markerName} at {markerLocation} due to marker limit of {ENFORCE_MAP_MARKER_LIMIT}")
return False
if object.objectGameVersion < 53:
newMarker = [[["markerGuid", uuid.uuid4().bytes],
["Location", [
[["X", markerLocation[0]], ["Y", markerLocation[1]], ["Z", markerLocation[2]]],
[["X", "DoubleProperty", 0], ["Y", "DoubleProperty", 0], ["Z", "DoubleProperty", 0]]]],
["Name", markerName],
["CategoryName", subcategory], # This is called "Subcategory" in-game
["MapMarkerType", ["ERepresentationType", "ERepresentationType::RT_MapMarker"]],
["IconID", sav_data.data.ICON_NAMES_TO_IDS[markerIconId_key]],
["Color", [markerColor[0], markerColor[1], markerColor[2], 1.0]],
["Scale", scale],
["compassViewDistance", ["ECompassViewDistance", f"ECompassViewDistance::{markerViewDistance.name}"]],
["MarkerPlacedByAccountID", ""]],
[["markerGuid", "StructProperty", 0, "Guid", None, 0],
["Location", "StructProperty", 0, "Vector_NetQuantize", None, 0],
["Name", "StrProperty", 0], ["CategoryName", "StrProperty", 0],
["MapMarkerType", "EnumProperty", 0],
["IconID", "IntProperty", 0],
["Color", "StructProperty", 0, "LinearColor", None, 0],
["Scale", "FloatProperty", 0],
["compassViewDistance", "EnumProperty", 0],
["MarkerPlacedByAccountID", "StrProperty", 0]]]
else:
newMarker = [[["markerGuid", uuid.uuid4().bytes],
["Location",[
[["X", markerLocation[0]], ["Y", markerLocation[1]], ["Z", markerLocation[2]]],
[["X", "DoubleProperty", 0], ["Y", "DoubleProperty", 0], ["Z", "DoubleProperty", 0]]]],
["Name", markerName],
["CategoryName", subcategory], # This is called "Subcategory" in-game
["MapMarkerType", ["ERepresentationType", "ERepresentationType::RT_MapMarker"]],
["IconID", sav_data.data.ICON_NAMES_TO_IDS[markerIconId_key]],
["Color", [markerColor[0], markerColor[1], markerColor[2], 1.0]],
["Scale", scale],
["compassViewDistance", ["ECompassViewDistance", f"ECompassViewDistance::{markerViewDistance.name}"]],
["lastEditedBy", b'\x06\x00\x00\x00\x00']],
[["markerGuid", "StructProperty", 1, "Guid", ["/Script/CoreUObject"], 8],
["Location", "StructProperty", 1, "Vector_NetQuantize", ["/Script/Engine"], 0],
["Name", "StrProperty", 0],
["CategoryName", "StrProperty", 0],
["MapMarkerType", "EnumProperty", 2, "ERepresentationType", ["/Script/FactoryGame"]],
["IconID", "IntProperty", 0],
["Color", "StructProperty", 1, "LinearColor", ["/Script/CoreUObject"], 8],
["Scale", "FloatProperty", 0],
["compassViewDistance", "EnumProperty", 2, "ECompassViewDistance", ["/Script/FactoryGame"]],
["lastEditedBy", "StructProperty", 1, "PlayerInfoHandle", ["/Script/FactoryGame"], 8]]]
mapMarkers.append(newMarker)
return True
return False
class ChangeResultEnum(enum.Enum):
NO_CHANGE = 0
CHANGE = 1
ERROR = 2
def setNodeType(originalNodeName, nodeType, nodePurity):
LIQUID_OIL = "/Game/FactoryGame/Resource/RawResources/CrudeOil/Desc_LiquidOil.Desc_LiquidOil_C"
ITEM_NODE_TYPES = {
"Coal": "/Game/FactoryGame/Resource/RawResources/Coal/Desc_Coal.Desc_Coal_C",
"Bauxite": "/Game/FactoryGame/Resource/RawResources/OreBauxite/Desc_OreBauxite.Desc_OreBauxite_C",
"Copper Ore": "/Game/FactoryGame/Resource/RawResources/OreCopper/Desc_OreCopper.Desc_OreCopper_C",
"Caterium Ore": "/Game/FactoryGame/Resource/RawResources/OreGold/Desc_OreGold.Desc_OreGold_C",
"Crude Oil": LIQUID_OIL,
"Iron Ore": "/Game/FactoryGame/Resource/RawResources/OreIron/Desc_OreIron.Desc_OreIron_C",
"Uranium": "/Game/FactoryGame/Resource/RawResources/OreUranium/Desc_OreUranium.Desc_OreUranium_C",
"Raw Quartz": "/Game/FactoryGame/Resource/RawResources/RawQuartz/Desc_RawQuartz.Desc_RawQuartz_C",
"SAM Ore": "/Game/FactoryGame/Resource/RawResources/SAM/Desc_SAM.Desc_SAM_C",
"Limestone": "/Game/FactoryGame/Resource/RawResources/Stone/Desc_Stone.Desc_Stone_C",
"Sulfur": "/Game/FactoryGame/Resource/RawResources/Sulfur/Desc_Sulfur.Desc_Sulfur_C"}
FRACKING_NODE_TYPES = {
"Crude Oil": LIQUID_OIL,
"Nitrogen Gas": "/Game/FactoryGame/Resource/RawResources/NitrogenGas/Desc_NitrogenGas.Desc_NitrogenGas_C",
"Water": "/Game/FactoryGame/Resource/RawResources/Water/Desc_Water.Desc_Water_C"}
NODE_PURITIES = {"Impure": "RP_Impure", "Normal": "RP_Normal", "Pure": "RP_Pure"}
if nodeType in ITEM_NODE_TYPES:
requestedTypeIsFrackingFlag = False
nodeType = ITEM_NODE_TYPES[nodeType]
elif nodeType in FRACKING_NODE_TYPES:
requestedTypeIsFrackingFlag = True
nodeType = FRACKING_NODE_TYPES[nodeType]
else:
return (ChangeResultEnum.ERROR, f"ERROR: Invalid node type '{nodeType}' for node {originalNodeName}")
if nodePurity is not None:
if nodePurity not in NODE_PURITIES:
return (ChangeResultEnum.ERROR, f"ERROR: Invalid node purity '{nodePurity}'")
nodePurity = NODE_PURITIES[nodePurity]
nodeName = f"Persistent_Level:PersistentLevel.{originalNodeName}"
level = parsedSave.levels[-1]
for actorOrComponentObjectHeader in level.actorAndComponentObjectHeaders:
if isinstance(actorOrComponentObjectHeader, sav_parse.ActorHeader) and \
actorOrComponentObjectHeader.typePath in ("/Game/FactoryGame/Resource/BP_ResourceNode.BP_ResourceNode_C",
"/Game/FactoryGame/Resource/BP_FrackingCore.BP_FrackingCore_C",
"/Game/FactoryGame/Resource/BP_FrackingSatellite.BP_FrackingSatellite_C") and \
actorOrComponentObjectHeader.instanceName == nodeName:
# Note is confirmed to be the correct typePath, so continue
for object in level.objects:
if object.instanceName == nodeName:
if nodeType != LIQUID_OIL:
requestedNodeIsFrackingFlag = actorOrComponentObjectHeader.typePath != "/Game/FactoryGame/Resource/BP_ResourceNode.BP_ResourceNode_C"
if requestedTypeIsFrackingFlag != requestedNodeIsFrackingFlag:
return (ChangeResultEnum.ERROR, f"ERROR: Mismatch between {originalNodeName} type {actorOrComponentObjectHeader.typePath} and new type {nodeType}")
successType = ChangeResultEnum.NO_CHANGE
successMessage = f"{object.instanceName}:"
resourceClassOverride = sav_parse.getPropertyValue(object.properties, "mResourceClassOverride")
if resourceClassOverride:
if resourceClassOverride.pathName != nodeType:
successMessage += f" Changed type from {sav_parse.pathNameToReadableName(resourceClassOverride.pathName)} to {sav_parse.pathNameToReadableName(nodeType)}."
resourceClassOverride.pathName = nodeType
successType = ChangeResultEnum.CHANGE
else:
successMessage += f" Type already {sav_parse.pathNameToReadableName(nodeType)}."
else:
resourceClassOverride = sav_parse.ObjectReference()
resourceClassOverride.pathName = nodeType
object.properties.append(["mResourceClassOverride", resourceClassOverride])
object.propertyTypes.append(["mResourceClassOverride", "ObjectProperty", 0])
successMessage += f" Setting type to {sav_parse.pathNameToReadableName(nodeType)}."
successType = ChangeResultEnum.CHANGE
purityOverride = sav_parse.getPropertyValue(object.properties, "mPurityOverride")
if purityOverride:
if purityOverride[1] != nodePurity:
successMessage += f" Changed purity from {purityOverride[1]} to {nodePurity}."
purityOverride[1] = nodePurity
successType = ChangeResultEnum.CHANGE
else:
successMessage += f" Purity already {nodePurity}."
elif actorOrComponentObjectHeader.typePath != "/Game/FactoryGame/Resource/BP_FrackingCore.BP_FrackingCore_C":
object.properties.append(["mPurityOverride", ["EResourcePurity", nodePurity]])
object.propertyTypes.append(["mPurityOverride", "ByteProperty", 1, "EResourcePurity", ["/Script/FactoryGame"]])
successMessage += f" Setting purity to {nodePurity}."
successType = ChangeResultEnum.CHANGE
return (successType, successMessage)
if nodeName not in sav_data.resourcePurity.RESOURCE_PURITY:
return (ChangeResultEnum.ERROR, f"ERROR: Invalid node name '{originalNodeName}'")
else:
return (ChangeResultEnum.ERROR, f"ERROR: Node not found '{originalNodeName}'")
def printUsage() -> None:
print()
print("USAGE:")
print(" py sav_cli.py --info <save-filename>")
print(" py sav_cli.py --to-json <save-filename> <output-json-filename>")
print(" py sav_cli.py --from-json <input-json-filename> <new-save-filename>")
print(" py sav_cli.py --set-session-name <new-session-name> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --find-free-stuff [item] [save-filename]")
print(" py sav_cli.py --list-players <save-filename>")
print(" py sav_cli.py --list-player-inventory <player-num> <save-filename>")
print(" py sav_cli.py --find-node <x> <y> [save-filename]")
print(" py sav_cli.py --find-node-near <player-num> <save-filename>")
print(" py sav_cli.py --set-node <name> <type> <purity> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --export-node-types <save-filename> <output-json-filename>")
print(" py sav_cli.py --import-node-types <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --export-player-inventory <player-num> <save-filename> <output-json-filename>")
print(" py sav_cli.py --import-player-inventory <player-num> <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --tweak-player-inventory <player-num> <slot-index> <item> <quantity> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --rotate-foundations <primary-color-hex-or-preset> <secondary-color-hex-or-preset> <clockwise-degrees> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --clear-fog <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --export-hotbar <player-num> <save-filename> <output-json-filename>")
print(" py sav_cli.py --import-hotbar <player-num> <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --change-num-inventory-slots <num-inventory-slots> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --restore-somersloops <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --restore-mercer-spheres <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --export-somersloops <save-filename> <output-json-filename>")
print(" py sav_cli.py --export-mercer-spheres <save-filename> <output-json-filename>")
print(" py sav_cli.py --import-somersloops <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --import-mercer-spheres <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --remember-username <player-num> <username-alias>")
print(" py sav_cli.py --list-vehicle-paths <save-filename>")
print(" py sav_cli.py --export-vehicle-path <path-name> <save-filename> <output-json-filename>")
print(" py sav_cli.py --import-vehicle-path <path-name> <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --export-dimensional-depot <save-filename> <output-json-filename>")
print(" py sav_cli.py --reorder-dimensional-depot <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --adjust-dimensional-depot <original-save-filename> <item-name> <new-quantity> <new-save-filename> [--same-time]")
print(" py sav_cli.py --export-crash-sites <save-filename> <output-json-filename>")
print(" py sav_cli.py --dismantle-crash-site <drop-pod-name> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --list-map-markers <save-filename>")
print(" py sav_cli.py --export-map-markers <save-filename> <output-json-filename>")
print(" py sav_cli.py --remove-marker <marker-guid> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --add-map-markers-json <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --add-map-markers-somersloops <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --add-map-markers-mercer-spheres <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --add-map-markers-hard-drives <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --add-map-markers-collectable <item> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --show <save-filename>")
print(" py sav_cli.py --blueprint --sort <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --export <save-filename> <output-json-filename>")
print(" py sav_cli.py --blueprint --import <original-save-filename> <input-json-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --add-category <category> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --add-subcategory <category> <subcategory> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --add-blueprint <category> <subcategory> <blueprint> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --remove-category <category> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --remove-subcategory <category> <subcategory> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --remove-blueprint <category> <subcategory> <blueprint> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --move-blueprint <old-category> <old-subcategory> <new-category> <new-subcategory> <blueprint> <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --blueprint --reset <original-save-filename> <new-save-filename> [--same-time]")
print(" py sav_cli.py --resave-only <original-save-filename> <new-save-filename>")
print(" py sav_cli.py --add-missing-items-to-sav_stack_sizes")
print(" py sav_cli.py --list-crash-site-guards")
print()
# TODO: Add manipulation of cheat flags
# mapOptions ends in "?enableAdvancedGameSettings"
# isCreativeModeEnabled=True
# <Object: instanceName=Persistent_Level:PersistentLevel.GameRulesSubsystem
# properties=[[('mHasInitialized', True)]]
# properties=[[('mHasInitialized', False), ('mUnlockInstantAltRecipes', True), ('mDisableArachnidCreatures', True), ('mNoUnlockCost', True)]]
# <Object: instanceName=Persistent_Level:PersistentLevel.BP_GameState_C_2147478581
# ('mIsCreativeModeEnabled', False), ('mCheatNoPower', True), ('mCheatNoFuel', True), ('mCheatNoCost', True)
# <Object: instanceName=Persistent_Level:PersistentLevel.BP_PlayerState_C_2147195792
# ('mPlayerRules', ([('HasInitialized', True)], [('HasInitialized', 'BoolProperty', 0)]))
# ('mPlayerRules', ([('HasInitialized', True), ('NoBuildCost', True), ('FlightMode', True), ('GodMode', True)], [('HasInitialized', 'BoolProperty', 0), ('NoBuildCost', 'BoolProperty', 0), ('FlightMode', 'BoolProperty', 0), ('GodMode', 'BoolProperty', 0)]))
if __name__ == '__main__':
if os.path.isfile(USERNAME_FILENAME):
with open(USERNAME_FILENAME, "r") as fin:
playerUsernames = json.load(fin)
if len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] in ("-h", "--help")):
printUsage()
elif len(sys.argv) == 3 and sys.argv[1] == "--info" and os.path.isfile(sys.argv[2]):
savFilename = sys.argv[2]
try:
parsedSave = sav_parse.readFullSaveFile(savFilename)
print(f"Save Header Type: {parsedSave.saveFileInfo.saveHeaderType}")
print(f"Save Version: {parsedSave.saveFileInfo.saveVersion}")
print(f"Build Version: {parsedSave.saveFileInfo.buildVersion}")
print(f"Save Name: {parsedSave.saveFileInfo.saveName}")
print(f"Map Name: {parsedSave.saveFileInfo.mapName}")
print(f"Map Options: {parsedSave.saveFileInfo.mapOptions}")
print(f"Session Name: {parsedSave.saveFileInfo.sessionName}")
print(f"Play Duration: {parsedSave.saveFileInfo.playDurationInSeconds} seconds")
print(f"Save Date Time: {parsedSave.saveFileInfo.saveDateTimeInTicks} ticks ({parsedSave.saveFileInfo.saveDatetime.strftime('%m/%d/%Y %I:%M:%S %p')})")
print(f"Session Visibility: {parsedSave.saveFileInfo.sessionVisibility}")
print(f"Editor Object Version: {parsedSave.saveFileInfo.editorObjectVersion}")
print(f"Is Modded Save: {parsedSave.saveFileInfo.isModdedSave}")
if not parsedSave.saveFileInfo.isModdedSave and len(parsedSave.saveFileInfo.modMetadata) > 0: # This should never happen
print(f"Mod Metadata: {parsedSave.saveFileInfo.modMetadata}")
print(f"Save Identifier: {parsedSave.saveFileInfo.saveIdentifier}")
print(f"Save Data Hash: {parsedSave.saveFileInfo.saveDataHash}")
print(f"Is Creative Mode Enabled: {parsedSave.saveFileInfo.isCreativeModeEnabled}")
playerPaths = getPlayerPaths(parsedSave.levels)
gameStateInstanceName = None
for level in parsedSave.levels:
for actorOrComponentObjectHeader in level.actorAndComponentObjectHeaders:
if isinstance(actorOrComponentObjectHeader, sav_parse.ActorHeader) and actorOrComponentObjectHeader.typePath == "/Game/FactoryGame/-Shared/Blueprint/BP_GameState.BP_GameState_C":
gameStateInstanceName = actorOrComponentObjectHeader.instanceName
for level in parsedSave.levels:
for object in level.objects:
if object.instanceName == "Persistent_Level:PersistentLevel.GameRulesSubsystem":
mStartingTier = sav_parse.getPropertyValue(object.properties, "mStartingTier")
if mStartingTier is not None:
print(f"Game Rules, mStartingTier: {mStartingTier}")
mUnlockInstantAltRecipes = sav_parse.getPropertyValue(object.properties, "mUnlockInstantAltRecipes")
if mUnlockInstantAltRecipes is not None:
print(f"Game Rules, mUnlockInstantAltRecipes: {mUnlockInstantAltRecipes}")
mUnlockAllMilestoneSchematics = sav_parse.getPropertyValue(object.properties, "mUnlockAllMilestoneSchematics")
if mUnlockAllMilestoneSchematics is not None:
print(f"Game Rules, mUnlockAllMilestoneSchematics: {mUnlockAllMilestoneSchematics}")
mUnlockAllResourceSinkSchematics = sav_parse.getPropertyValue(object.properties, "mUnlockAllResourceSinkSchematics")
if mUnlockAllResourceSinkSchematics is not None:
print(f"Game Rules, mUnlockAllResourceSinkSchematics: {mUnlockAllResourceSinkSchematics}")
mUnlockAllResearchSchematics = sav_parse.getPropertyValue(object.properties, "mUnlockAllResearchSchematics")
if mUnlockAllResearchSchematics is not None:
print(f"Game Rules, mUnlockAllResearchSchematics: {mUnlockAllResearchSchematics}")
mNoUnlockCost = sav_parse.getPropertyValue(object.properties, "mNoUnlockCost")
if mNoUnlockCost is not None:
print(f"Game Rules, mNoUnlockCost: {mNoUnlockCost}")
elif object.instanceName == gameStateInstanceName:
mIsCreativeModeEnabled = sav_parse.getPropertyValue(object.properties, "mIsCreativeModeEnabled")
if mIsCreativeModeEnabled is not None:
print(f"Game State, mIsCreativeModeEnabled: {mIsCreativeModeEnabled}")
mCheatNoPower = sav_parse.getPropertyValue(object.properties, "mCheatNoPower")
if mCheatNoPower is not None:
print(f"Game State, mCheatNoPower: {mCheatNoPower}")
mCheatNoFuel = sav_parse.getPropertyValue(object.properties, "mCheatNoFuel")
if mCheatNoFuel is not None:
print(f"Game State, mCheatNoFuel: {mCheatNoFuel}")
mCheatNoCost = sav_parse.getPropertyValue(object.properties, "mCheatNoCost")
if mCheatNoCost is not None:
print(f"Game State, mCheatNoCost: {mCheatNoCost}")
# Game Modes
mEnergyCostMultiplier = sav_parse.getPropertyValue(object.properties, "mEnergyCostMultiplier")
if mEnergyCostMultiplier is not None:
print(f"Game State, mEnergyCostMultiplier: {mEnergyCostMultiplier}")
mPartsCostMultiplier = sav_parse.getPropertyValue(object.properties, "mPartsCostMultiplier")
if mPartsCostMultiplier is not None:
print(f"Game State, mPartsCostMultiplier: {mPartsCostMultiplier}")
mSpacePartsCostMultiplier = sav_parse.getPropertyValue(object.properties, "mSpacePartsCostMultiplier")
if mSpacePartsCostMultiplier is not None:
print(f"Game State, mSpacePartsCostMultiplier: {mSpacePartsCostMultiplier}")
mNodeRandomization = sav_parse.getPropertyValue(object.properties, "mNodeRandomization")
if mNodeRandomization is not None:
print(f"Game State, mNodeRandomization: {mNodeRandomization[1].lstrip('ENodeRandomizationMode::NRM_')}")
mNodePuritySettings = sav_parse.getPropertyValue(object.properties, "mNodePuritySettings")
if mNodePuritySettings is not None:
print(f"Game State, mNodePuritySettings: {mNodePuritySettings[1].lstrip('ENodePuritySettings::NPS_')}")
mNodeRandomizationSeed = sav_parse.getPropertyValue(object.properties, "mNodeRandomizationSeed")
if mNodeRandomizationSeed is not None:
print(f"Game State, mNodeRandomizationSeed: {mNodeRandomizationSeed}")
print("Players:")
for level in parsedSave.levels:
for object in level.objects:
for (playerStateInstanceName, characterPlayer, inventoryPath, armsPath, backPath, legsPath, headPath, bodyPath, healthPath) in playerPaths:
if object.instanceName == playerStateInstanceName:
playerName = getPlayerName(parsedSave.levels, characterPlayer)
if playerName is None:
print(f" {characterPlayer}")
else:
print(f" {characterPlayer} ({playerName})")
mPlayerRules = sav_parse.getPropertyValue(object.properties, "mPlayerRules")
if mPlayerRules is not None:
noBuildCost = sav_parse.getPropertyValue(mPlayerRules[0], "NoBuildCost")
if noBuildCost is not None:
print(f" Player Rules, NoBuildCost: {noBuildCost}")
flightMode = sav_parse.getPropertyValue(mPlayerRules[0], "FlightMode")
if flightMode is not None:
print(f" Player Rules, FlightMode: {flightMode}")
godMode = sav_parse.getPropertyValue(mPlayerRules[0], "GodMode")
if godMode is not None:
print(f" Player Rules, GodMode: {godMode}")
if parsedSave.saveFileInfo.isModdedSave:
# modMetadata is of type str representing a JSON dict
print(f"Mod Metadata:")
jdata = json.loads(parsedSave.saveFileInfo.modMetadata)
if "Mods" in jdata:
for mod in jdata["Mods"]:
if "Name" in mod and "Version" in mod:
print(f" {mod['Name']}, {mod['Version']}")
crashSitesInSave, crashSitesNotOpened, crashSitesOpenWithDrive, crashSitesOpenAndEmpty, crashSitesDismantled = sav_to_html.getCrashSiteState(parsedSave.levels)
print(f"{len(sav_data.crashSites.CRASH_SITES)} total crash sites on map.")
print(f" {len(crashSitesInSave) + len(crashSitesDismantled)} found in save file.")
print(f" {len(crashSitesNotOpened)} not opened.")
print(f" {len(crashSitesOpenWithDrive)} opened with hard drive.")
print(f" {len(crashSitesOpenAndEmpty)} opened and empty.")
print(f" {len(crashSitesDismantled)} dismantled.")
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
elif len(sys.argv) == 4 and sys.argv[1] == "--to-json" and os.path.isfile(sys.argv[2]):
savFilename = sys.argv[2]
outFilename = sys.argv[3]
modifiedFlag = False
try:
parsedSave = sav_parse.readFullSaveFile(savFilename)
jdata = {}
jdata["saveFileInfo"] = toJSON(parsedSave.saveFileInfo)
jdata["persistentLevelSaveObjectVersionData"] = toJSON(parsedSave.persistentLevelSaveObjectVersionData)
jdata["partitions"] = toJSON(parsedSave.partitions)
ldata = jdata["levels"] = {}
for level in parsedSave.levels:
ldata[level.levelName] = {
"objectHeaders": toJSON(level.actorAndComponentObjectHeaders),
"levelPersistentFlag": toJSON(level.levelPersistentFlag),
"collectables1": toJSON(level.collectables1),
"objects": toJSON(level.objects),
"levelSaveVersion": toJSON(level.levelSaveVersion),
"collectables2": toJSON(level.collectables2),
"saveObjectVersionData": toJSON(level.saveObjectVersionData)}
jdata["aLevelName"] = toJSON(parsedSave.aLevelName)
jdata["dropPodObjectReferenceList"] = toJSON(parsedSave.dropPodObjectReferenceList)
jdata["extraObjectReferenceList"] = toJSON(parsedSave.extraObjectReferenceList)
print(f"Writing {outFilename}")
with open(outFilename, "w") as fout:
json.dump(jdata, fout, indent=2)
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
elif len(sys.argv) == 4 and sys.argv[1] == "--from-json" and os.path.isfile(sys.argv[2]):
jsonFilename = sys.argv[2]
outFilename = sys.argv[3]
print("Reading JSON")
with open(jsonFilename, "r") as fin:
jdata = json.load(fin)
print("Parsing JSON")
saveFileInfo = sav_parse.SaveFileInfo()
saveFileInfo.saveHeaderType = jdata["saveFileInfo"]["saveHeaderType"]
saveFileInfo.saveVersion = jdata["saveFileInfo"]["saveVersion"]
saveFileInfo.buildVersion = jdata["saveFileInfo"]["buildVersion"]
saveFileInfo.saveName = jdata["saveFileInfo"]["saveName"]
saveFileInfo.mapName = jdata["saveFileInfo"]["mapName"]
saveFileInfo.mapOptions = jdata["saveFileInfo"]["mapOptions"]
saveFileInfo.sessionName = jdata["saveFileInfo"]["sessionName"]
saveFileInfo.playDurationInSeconds = jdata["saveFileInfo"]["playDurationInSeconds"]
saveFileInfo.saveDateTimeInTicks = jdata["saveFileInfo"]["saveDateTimeInTicks"]
saveFileInfo.saveDatetime = datetime.datetime.fromtimestamp(saveFileInfo.saveDateTimeInTicks / sav_parse.TICKS_IN_SECOND - sav_parse.EPOCH_1_TO_1970)
saveFileInfo.sessionVisibility = fromJSON(jdata["saveFileInfo"]["sessionVisibility"])
saveFileInfo.editorObjectVersion = jdata["saveFileInfo"]["editorObjectVersion"]
saveFileInfo.modMetadata = jdata["saveFileInfo"]["modMetadata"]
saveFileInfo.isModdedSave = jdata["saveFileInfo"]["isModdedSave"]
saveFileInfo.saveIdentifier = jdata["saveFileInfo"]["saveIdentifier"]
saveFileInfo.saveDataHash = jdata["saveFileInfo"]["saveDataHash"]
saveFileInfo.isCreativeModeEnabled = jdata["saveFileInfo"]["isCreativeModeEnabled"]
persistentLevelSaveObjectVersionData = jdata["persistentLevelSaveObjectVersionData"]
partitions = jdata["partitions"]
aLevelName = jdata["aLevelName"]
dropPodObjectReferenceList = []
for objectReference in jdata["dropPodObjectReferenceList"]:
dropPodObjectReferenceList.append(fromJSON(objectReference))
extraObjectReferenceList = []
for objectReference in jdata["extraObjectReferenceList"]:
extraObjectReferenceList.append(fromJSON(objectReference))
levels = []
for level in jdata["levels"]:
levelName = level
if levelName == "null":
levelName = None
levelData = jdata["levels"][level]
actorAndComponentObjectHeaders = []
for objectHeaderJson in levelData["objectHeaders"]:
if len(objectHeaderJson) == 9:
objectHeaderCopy = sav_parse.ActorHeader()
objectHeaderCopy.typePath = objectHeaderJson["typePath"]
objectHeaderCopy.rootObject = objectHeaderJson["rootObject"]
objectHeaderCopy.instanceName = objectHeaderJson["instanceName"]
objectHeaderCopy.flags = objectHeaderJson["flags"]
objectHeaderCopy.needTransform = objectHeaderJson["needTransform"]
objectHeaderCopy.rotation = objectHeaderJson["rotation"]
objectHeaderCopy.position = objectHeaderJson["position"]
objectHeaderCopy.scale = objectHeaderJson["scale"]
objectHeaderCopy.wasPlacedInLevel = objectHeaderJson["wasPlacedInLevel"]
else:
objectHeaderCopy = sav_parse.ComponentHeader()