-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsav_cli.py
2597 lines (2247 loc) · 144 KB
/
sav_cli.py
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/python3
# This file is part of the Satisfactory Save Parser distribution
# (https://github.com/GreyHak/sat_sav_parse).
# Copyright (c) 2024 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 os
import sys
import json
import math
import uuid
import datetime
import sav_parse
import sav_to_resave
import sav_data_somersloop
import sav_data_mercerSphere
import sav_data_free
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"
def getBlankCategory(categoryName, iconId = -1):
return [[['CategoryName', categoryName], ['IconID', iconId], ['MenuPriority', 0.0], ['IsUndefined', False], ['SubCategoryRecords', [[[['SubCategoryName', 'Undefined'], ['MenuPriority', 0.0], ['IsUndefined', 1], ['BlueprintNames', []]], [['SubCategoryName', 'StrProperty', 0], ['MenuPriority', 'FloatProperty', 0], ['IsUndefined', 'ByteProperty', 0], ['BlueprintNames', ['ArrayProperty', 'StrProperty'], 0]]]]]], [['CategoryName', 'StrProperty', 0], ['IconID', 'IntProperty', 0], ['MenuPriority', 'FloatProperty', 0], ['IsUndefined', 'BoolProperty', 0], ['SubCategoryRecords', ['ArrayProperty', 'StructProperty', 'BlueprintSubCategoryRecord'], 0]]]
def getBlankSubcategory(subcategoryName):
return [[['SubCategoryName', subcategoryName], ['MenuPriority', 0.0], ['IsUndefined', 0], ['BlueprintNames', []]], [['SubCategoryName', 'StrProperty', 0], ['MenuPriority', 'FloatProperty', 0], ['IsUndefined', 'ByteProperty', 0], ['BlueprintNames', ['ArrayProperty', 'StrProperty'], 0]]]
playerUsernames = {}
def getPlayerPaths(levels):
playerPaths = [] # = (playerStateInstanceName, characterPlayer, inventoryPath, armsPath, backPath, legsPath, headPath, bodyPath, healthPath)
playerStateInstances = []
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for actorOrComponentObjectHeader in 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 (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for object in 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 != None:
playerHotbars = sav_parse.getPropertyValue(object.properties, "mPlayerHotbars")
if playerHotbars != None:
playerCharacterInstances[ownedPawn.pathName] = (object.instanceName)
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for object in objects:
if object.instanceName in playerCharacterInstances:
inventory = sav_parse.getPropertyValue(object.properties, "mInventory")
if inventory != None:
armsEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mArmsEquipmentSlot")
if armsEquipmentSlot != None:
backEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mBackEquipmentSlot")
if backEquipmentSlot != None:
legsEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mLegsEquipmentSlot")
if legsEquipmentSlot != None:
headEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mHeadEquipmentSlot")
if headEquipmentSlot != None:
bodyEquipmentSlot = sav_parse.getPropertyValue(object.properties, "mBodyEquipmentSlot")
if bodyEquipmentSlot != None:
healthComponent = sav_parse.getPropertyValue(object.properties, "mHealthComponent")
if healthComponent != 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, playerCharacter):
global playerUsernames
loc = playerCharacter.rfind("_")
playerId = playerCharacter[loc+1:]
if playerId in playerUsernames:
return playerUsernames[playerId]
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for object in objects:
if object.instanceName == playerCharacter:
cachedPlayerName = sav_parse.getPropertyValue(object.properties, "mCachedPlayerName")
if cachedPlayerName != None:
return cachedPlayerName
return None
def characterPlayerMatch(characterPlayer, playerId):
return characterPlayer == f"Persistent_Level:PersistentLevel.Char_Player_C_{playerId}"
def orderBlueprintCategoryMenuPriorities(blueprintCategoryRecords):
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 != 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):
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):
return max(0, min(255, round(lcToSRGBFloat(linearCol) * 255)))
def lcTupleToSrgbHex(linearCTuple):
srgb = ""
for i in range(3):
srgb += "{:x}".format(lcToSRGBInt(linearCTuple[i])).zfill(2)
return srgb
def radiansToDegrees(radians):
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 == 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 != 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)}
jdata = {}
for element in object.__dict__:
jdata[element] = toJSON(object.__dict__[element])
return jdata
def fromJSON(object):
if object == 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):
# 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 (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
if collectables1 != None:
for collectable in collectables1:
if collectable.pathName == targetPathName:
collectables1.remove(collectable)
print(f"Clearing removal of {collectable.pathName}")
break
for collectable in collectables2:
if collectable.pathName == targetPathName:
collectables2.remove(collectable)
instanceName = collectable.pathName
(rootObject, rotation, position) = sav_data_somersloop.SOMERSLOOPS[collectable.pathName]
newActor = sav_parse.ActorHeader()
newActor.typePath = sav_parse.SOMERSLOOP
newActor.rootObject = rootObject
newActor.instanceName = instanceName
newActor.needTransform = False
newActor.rotation = rotation
newActor.position = position
newActor.scale = [1.600000023841858, 1.600000023841858, 1.600000023841858]
newActor.wasPlacedInLevel = 1
actorAndComponentObjectHeaders.append(newActor)
newObject = sav_parse.Object()
newObject.instanceName = instanceName
newObject.objectGameVersion = 46
newObject.shouldMigrateObjectRefsToPersistentFlag = False
nullParentObjectReference = sav_parse.ObjectReference()
nullParentObjectReference.levelName = ""
nullParentObjectReference.pathName = ""
newObject.actorReferenceAssociations = [nullParentObjectReference, []]
newObject.properties = []
newObject.propertyTypes = []
newObject.actorSpecificInfo = None
objects.append(newObject)
print(f"Restored Somersloop {instanceName} at {position}")
return True
return False
def addMercerSphere(levels, targetPathName):
# 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 (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
if collectables1 != None:
for collectable in collectables1:
if collectable.pathName == targetPathName:
collectables1.remove(collectable)
print(f"Clearing removal of sphere {collectable.pathName}")
break
for collectable in collectables2:
if collectable.pathName == targetPathName:
collectables2.remove(collectable)
instanceName = collectable.pathName
(rootObject, rotation, position) = sav_data_mercerSphere.MERCER_SPHERES[collectable.pathName]
newActor = sav_parse.ActorHeader()
newActor.typePath = sav_parse.MERCER_SPHERE
newActor.rootObject = rootObject
newActor.instanceName = instanceName
newActor.needTransform = False
newActor.rotation = rotation
newActor.position = position
newActor.scale = [2.700000047683716, 2.6999998092651367, 2.6999998092651367]
newActor.wasPlacedInLevel = 1
actorAndComponentObjectHeaders.append(newActor)
newObject = sav_parse.Object()
newObject.instanceName = instanceName
newObject.objectGameVersion = 46
newObject.shouldMigrateObjectRefsToPersistentFlag = False
nullParentObjectReference = sav_parse.ObjectReference()
nullParentObjectReference.levelName = ""
nullParentObjectReference.pathName = ""
newObject.actorReferenceAssociations = [nullParentObjectReference, []]
newObject.properties = []
newObject.propertyTypes = []
newObject.actorSpecificInfo = None
objects.append(newObject)
print(f"Restored Mercer Sphere {instanceName} at {position}")
return True
return False
def addMercerShrine(levels, targetPathName):
# 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 (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
if collectables1 != None:
for collectable in collectables1:
if collectable.pathName == targetPathName:
collectables1.remove(collectable)
print(f"Clearing removal of shrine {collectable.pathName}")
break
for collectable in collectables2:
if collectable.pathName == targetPathName:
collectables2.remove(collectable)
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.needTransform = False
newActor.rotation = rotation
newActor.position = position
newActor.scale = [scale, scale, scale]
newActor.wasPlacedInLevel = 1
actorAndComponentObjectHeaders.append(newActor)
newObject = sav_parse.Object()
newObject.instanceName = instanceName
newObject.objectGameVersion = 46
newObject.shouldMigrateObjectRefsToPersistentFlag = False
nullParentObjectReference = sav_parse.ObjectReference()
nullParentObjectReference.levelName = ""
nullParentObjectReference.pathName = ""
newObject.actorReferenceAssociations = [nullParentObjectReference, []]
newObject.properties = []
newObject.propertyTypes = []
newObject.actorSpecificInfo = None
objects.append(newObject)
print(f"Restored Mercer Shrine {instanceName} at {position}")
return True
return False
def removeInstance(levels, humanReadableName, rootObject, targetInstanceName, position=None):
removedObjectCollectionReference = sav_parse.ObjectReference()
removedObjectCollectionReference.levelName = rootObject
removedObjectCollectionReference.pathName = targetInstanceName
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for actorOrComponentObjectHeader in actorAndComponentObjectHeaders:
if actorOrComponentObjectHeader.instanceName == targetInstanceName:
actorAndComponentObjectHeaders.remove(actorOrComponentObjectHeader)
for object in objects:
if object.instanceName == targetInstanceName:
objects.remove(object)
collectables1.append(removedObjectCollectionReference)
collectables2.append(removedObjectCollectionReference)
print(f"Removed {humanReadableName} {targetInstanceName} at {position}")
return True
# If present, removed above. If removed, return False.
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for collectable in collectables2:
if collectable.pathName == targetInstanceName:
return False
# If got 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 levelIdx in range(len(levels)):
(levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) = levels[levelIdx]
if levelName == rootObject:
print(f"Removed {humanReadableName} {targetInstanceName} at {position} (unvisited)")
if collectables1 != None:
collectables1.append(removedObjectCollectionReference)
collectables2.append(removedObjectCollectionReference)
return True
print(f"CAUTION: Failed to remove {humanReadableName} {targetInstanceName} at {position}")
return False
def removeSomersloop(levels, targetInstanceName):
(rootObject, rotation, position) = sav_data_somersloop.SOMERSLOOPS[targetInstanceName]
return removeInstance(levels, "Somersloops", rootObject, targetInstanceName, position)
def removeMercerSphere(levels, targetInstanceName):
(rootObject, rotation, position) = sav_data_mercerSphere.MERCER_SPHERES[targetInstanceName]
return removeInstance(levels, "Mercer Sphere", rootObject, targetInstanceName, position)
def removeMercerShrine(levels, targetInstanceName):
(rootObject, rotation, position, scale) = sav_data_mercerSphere.MERCER_SHRINES[targetInstanceName]
return removeInstance(levels, "Mercer Shrine", rootObject, targetInstanceName, position)
def printUsage():
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>")
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 --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> <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 --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()
# TODO: Add manipulation of cheat flags
# mapOptions ends in "?enableAdvancedGameSettings"
# cheatFlag=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]
saveFileInfo = sav_parse.readSaveFileInfo(savFilename)
print(f"Save Header Type: {saveFileInfo.saveHeaderType}")
print(f"Save Version: {saveFileInfo.saveVersion}")
print(f"Build Version: {saveFileInfo.buildVersion}")
print(f"MapName: {saveFileInfo.mapName}")
print(f"Map Options: {saveFileInfo.mapOptions}")
print(f"Session Name: {saveFileInfo.sessionName}")
print(f"Play Duration: {saveFileInfo.playDurationInSeconds} seconds")
print(f"Save Date Time: {saveFileInfo.saveDateTimeInTicks} ticks ({saveFileInfo.saveDatetime.strftime('%m/%d/%Y %I:%M:%S %p')})")
print(f"Session Visibility: {saveFileInfo.sessionVisibility}")
print(f"Editor Object Version: {saveFileInfo.editorObjectVersion}")
print(f"Mod Metadata: {saveFileInfo.modMetadata}")
print(f"Is Modded Save: {saveFileInfo.isModdedSave}")
print(f"Persistent Save Identifier: {saveFileInfo.persistentSaveIdentifier}")
print(f"Random: {saveFileInfo.random}")
print(f"Cheat Flag: {saveFileInfo.cheatFlag}")
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:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
jdata = {}
jdata["saveFileInfo"] = toJSON(saveFileInfo)
jdata["headhex"] = toJSON(headhex)
jdata["grids"] = toJSON(grids)
ldata = jdata["levels"] = {}
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
ldata[levelName] = {
"objectHeaders": toJSON(actorAndComponentObjectHeaders),
"collectables1": toJSON(collectables1),
"objects": toJSON(objects),
"collectables2": toJSON(collectables2)}
jdata["extraObjectReferenceList"] = toJSON(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.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.persistentSaveIdentifier = jdata["saveFileInfo"]["persistentSaveIdentifier"]
saveFileInfo.random = jdata["saveFileInfo"]["random"]
saveFileInfo.cheatFlag = jdata["saveFileInfo"]["cheatFlag"]
headhex = jdata["headhex"]
grids = jdata["grids"]
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) == 8:
objectHeaderCopy = sav_parse.ActorHeader()
objectHeaderCopy.typePath = objectHeaderJson["typePath"]
objectHeaderCopy.rootObject = objectHeaderJson["rootObject"]
objectHeaderCopy.instanceName = objectHeaderJson["instanceName"]
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()
objectHeaderCopy.className = objectHeaderJson["className"]
objectHeaderCopy.rootObject = objectHeaderJson["rootObject"]
objectHeaderCopy.instanceName = objectHeaderJson["instanceName"]
objectHeaderCopy.parentActorName = objectHeaderJson["parentActorName"]
actorAndComponentObjectHeaders.append(objectHeaderCopy)
collectables1 = None
if levelData["collectables1"] != None:
collectables1 = []
for objectReference in levelData["collectables1"]:
collectables1.append(fromJSON(objectReference))
objects = []
for objectJson in levelData["objects"]:
objectCopy = sav_parse.Object()
objectCopy.instanceName = objectJson["instanceName"]
objectCopy.objectGameVersion = objectJson["objectGameVersion"]
objectCopy.shouldMigrateObjectRefsToPersistentFlag = objectJson["smortpFlag"]
objectCopy.actorReferenceAssociations = None
if objectJson["actorReferenceAssociations"] != None:
objectCopy.actorReferenceAssociations = [fromJSON(objectJson["actorReferenceAssociations"]["parentObjectReference"]), fromJSON(objectJson["actorReferenceAssociations"]["actorComponentReferences"])]
objectCopy.properties = fromJSON(objectJson["properties"])
objectCopy.propertyTypes = fromJSON(objectJson["propertyTypes"])
objectCopy.actorSpecificInfo = fromJSON(objectJson["actorSpecificInfo"])
objects.append(objectCopy)
collectables2 = []
for objectReference in levelData["collectables2"]:
collectables2.append(fromJSON(objectReference))
levels.append([levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2])
print("Writing Save")
try:
sav_to_resave.saveFile(saveFileInfo, headhex, grids, levels, extraObjectReferenceList, outFilename)
print("Validating Save")
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(outFilename)
print("Validation successful")
except Exception as error:
raise Exception(f"ERROR: While validating save to '{outFilename}': {error}")
elif len(sys.argv) == 5 and sys.argv[1] == "--set-session-name" and os.path.isfile(sys.argv[3]):
newSessionName = sys.argv[2]
savFilename = sys.argv[3]
outFilename = sys.argv[4]
try:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
saveFileInfo.sessionName = newSessionName
try:
sav_to_resave.saveFile(saveFileInfo, headhex, grids, levels, extraObjectReferenceList, outFilename)
if VERIFY_CREATED_SAVE_FILES:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(outFilename)
print("Validation successful")
except Exception as error:
raise Exception(f"ERROR: While validating resave of '{savFilename}' to '{outFilename}': {error}")
elif len(sys.argv) in (2, 3, 4) and sys.argv[1] == "--find-free-stuff" and (len(sys.argv) < 4 or os.path.isfile(sys.argv[3])):
if len(sys.argv) == 2:
for item in sav_data_free.FREE_DROPPED_ITEMS:
total = 0
for (quantity, position, instanceName) in sav_data_free.FREE_DROPPED_ITEMS[item]:
total += quantity
print(f"{total} x {sav_parse.pathNameToReadableName(item)}")
else:
itemName = sys.argv[2]
droppedInstances = {}
for item in sav_data_free.FREE_DROPPED_ITEMS:
if sav_parse.pathNameToReadableName(item) == itemName:
for idx in range(len(sav_data_free.FREE_DROPPED_ITEMS[item])):
(quantity, position, instanceName) = sav_data_free.FREE_DROPPED_ITEMS[item][idx]
droppedInstances[instanceName] = (quantity, position)
break
if len(droppedInstances) == 0:
print(f"No {itemName}")
else:
if len(sys.argv) == 4:
savFilename = sys.argv[3]
try:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
if collectables1 != None:
for collectable in collectables1:
if collectable.pathName in droppedInstances:
del droppedInstances[collectable.pathName]
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
total = 0
for instanceName in droppedInstances:
(quantity, position) = droppedInstances[instanceName]
print(f"{quantity} x {itemName} at {position}")
total += quantity
if pilAvailableFlag:
MAP_BASENAME_FREE_ITEM = "save_free.png"
if os.path.isfile(sav_to_html.MAP_BASENAME_BLANK):
imageFont = ImageFont.truetype(sav_to_html.FONT_FILENAME, sav_to_html.MAP_FONT_SIZE)
smallFont = ImageFont.truetype(sav_to_html.FONT_FILENAME, 400/sav_to_html.MAP_DESCALE)
diImage = Image.open(sav_to_html.MAP_BASENAME_BLANK)
diDraw = ImageDraw.Draw(diImage)
for instanceName in droppedInstances:
(quantity, position) = droppedInstances[instanceName]
posX = sav_to_html.adjPos(position[0], False)
posY = sav_to_html.adjPos(position[1], True)
diDraw.ellipse((posX-2, posY-2, posX+2, posY+2), fill=(255,255,0))
diDraw.text((posX, posY), str(quantity), font=smallFont, fill=(0,0,0))
if len(sys.argv) == 4:
diDraw.text(sav_to_html.MAP_TEXT_1, saveFileInfo.saveDatetime.strftime(f"{total} free {itemName} from save %m/%d/%Y %I:%M:%S %p"), font=imageFont, fill=(50,50,50))
diDraw.text(sav_to_html.MAP_TEXT_2, saveFileInfo.sessionName, font=imageFont, fill=(0,0,0))
else:
diDraw.text(sav_to_html.MAP_TEXT_1, f"All {total} free {itemName}", font=imageFont, fill=(0,0,0))
imageFilename = MAP_BASENAME_FREE_ITEM
diImage.crop(sav_to_html.CROP_SETTINGS).save(imageFilename)
sav_to_html.chown(imageFilename)
elif len(sys.argv) == 3 and sys.argv[1] == "--list-players" and os.path.isfile(sys.argv[2]):
savFilename = sys.argv[2]
try:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
playerPaths = getPlayerPaths(levels)
for (playerStateInstanceName, characterPlayer, inventoryPath, armsPath, backPath, legsPath, headPath, bodyPath, healthPath) in playerPaths:
playerName = getPlayerName(levels, characterPlayer)
if playerName == None:
print(characterPlayer)
else:
print(f"{characterPlayer} ({playerName})")
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
elif len(sys.argv) == 4 and sys.argv[1] == "--list-player-inventory" and os.path.isfile(sys.argv[3]):
playerId = sys.argv[2]
savFilename = sys.argv[3]
try:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
playerPaths = getPlayerPaths(levels)
playerInventory = None
for (playerStateInstanceName, characterPlayer, inventoryPath, armsPath, backPath, legsPath, headPath, bodyPath, healthPath) in playerPaths:
if characterPlayerMatch(characterPlayer, playerId):
playerInventory = inventoryPath
if playerInventory == None:
print(f"Unable to match player '{playerId}'", file=sys.stderr)
exit(1)
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for object in objects:
if object.instanceName == playerInventory:
inventoryStacks = sav_parse.getPropertyValue(object.properties, "mInventoryStacks")
if inventoryStacks:
for idx in range(len(inventoryStacks)):
item = inventoryStacks[idx][0]
if item[0][0] == "Item" and item[1][0] == "NumItems":
itemName = item[0][1][0]
if len(itemName) == 0:
print(f"[{str(idx).rjust(2)}] Empty")
else:
itemName = sav_parse.pathNameToReadableName(itemName)
itemQuantity = item[1][1]
extraInformation = item[0][1][1]
extraInformationStr = ""
if isinstance(extraInformation, list):
# Jetpack: ('/Script/FactoryGame.FGJetPackItemState', [('CurrentFuel', 1.0), ('CurrentFuelType', 2), ('SelectedFuelType', 0)], [('CurrentFuel', 'FloatProperty', 0), ('CurrentFuelType', 'IntProperty', 0), ('SelectedFuelType', 'IntProperty', 0)])
# Chainsaw: ('/Script/FactoryGame.FGChainsawItemState', [('EnergyStored', 79.14283752441406)], [('EnergyStored', 'FloatProperty', 0)])
extraInformationStr = f": {sav_parse.toString(extraInformation[1])}"
print(f"[{str(idx).rjust(2)}] {str(itemQuantity).rjust(3)} x {itemName}{extraInformationStr}")
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
elif len(sys.argv) == 5 and sys.argv[1] == "--export-player-inventory" and os.path.isfile(sys.argv[3]):
playerId = sys.argv[2]
savFilename = sys.argv[3]
outFilename = sys.argv[4]
try:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
playerPaths = getPlayerPaths(levels)
playerInventory = None
for (playerStateInstanceName, characterPlayer, inventoryPath, armsPath, backPath, legsPath, headPath, bodyPath, healthPath) in playerPaths:
if characterPlayerMatch(characterPlayer, playerId):
playerInventory = inventoryPath
if playerInventory == None:
print(f"Unable to match player '{playerId}'", file=sys.stderr)
exit(1)
inventoryContents = []
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for object in objects:
if object.instanceName == playerInventory:
inventoryStacks = sav_parse.getPropertyValue(object.properties, "mInventoryStacks")
if inventoryStacks:
for idx in range(len(inventoryStacks)):
item = inventoryStacks[idx][0]
if item[0][0] == "Item" and item[1][0] == "NumItems":
itemName = item[0][1][0]
if len(itemName) == 0:
inventoryContents.append(None)
elif isinstance(item[0][1][1], list):
inventoryContents.append([itemName, item[1][1], item[0][1][1][0], item[0][1][1][1]])
else:
inventoryContents.append([itemName, item[1][1]])
with open(outFilename, "w") as fout:
json.dump(inventoryContents, fout, indent=2)
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
elif len(sys.argv) in (6, 7) and sys.argv[1] == "--import-player-inventory" and os.path.isfile(sys.argv[3]) and os.path.isfile(sys.argv[4]):
playerId = sys.argv[2]
savFilename = sys.argv[3]
inFilename = sys.argv[4]
outFilename = sys.argv[5]
changeTimeFlag = True
if len(sys.argv) == 7 and sys.argv[6] == "--same-time":
changeTimeFlag = False
with open(inFilename, "r") as fin:
inventoryContents = json.load(fin)
for inventoryContent in inventoryContents:
if inventoryContent != None:
itemPathName = inventoryContent[0]
if itemPathName not in sav_parse.ITEMS_FOR_PLAYER_INVENTORY:
print(f"ERROR: {itemPathName} not a valid item path name.")
exit(1)
modifiedFlag = False
try:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
playerPaths = getPlayerPaths(levels)
playerInventory = None
for (playerStateInstanceName, characterPlayer, inventoryPath, armsPath, backPath, legsPath, headPath, bodyPath, healthPath) in playerPaths:
if characterPlayerMatch(characterPlayer, playerId):
playerInventory = inventoryPath
if playerInventory == None:
print(f"Unable to match player '{playerId}'")
exit(1)
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for object in objects:
if object.instanceName == playerInventory:
inventoryStacks = sav_parse.getPropertyValue(object.properties, "mInventoryStacks")
if inventoryStacks:
for idx in range(len(inventoryStacks)):
if idx < len(inventoryContents):
print(f"Replacing {sav_parse.toString(inventoryStacks[idx][0])}")
if inventoryContents[idx] == None:
inventoryStacks[idx][0][0] = ["Item", ["", 1]]
inventoryStacks[idx][0][1] = ["NumItems", 0]
print(f"Setting player {playerInventory}'s inventory slot {idx} to be Empty")
elif len(inventoryContents[idx]) == 2:
(itemPathName, itemQuantity) = inventoryContents[idx]
inventoryStacks[idx][0][0] = ["Item", [itemPathName, 1]]
inventoryStacks[idx][0][1] = ["NumItems", itemQuantity]
print(f"Setting player {playerInventory}'s inventory slot {idx} to include {itemQuantity} x {sav_parse.pathNameToReadableName(itemPathName)}")
elif len(inventoryContents[idx]) == 4:
(itemPathName, itemQuantity, itemPropName, itemProps) = inventoryContents[idx]
if itemPropName == "/Script/FactoryGame.FGJetPackItemState":
inventoryStacks[idx][0][0] = ["Item", [itemPathName, [itemPropName, itemProps, [['CurrentFuel', 'FloatProperty', 0], ['CurrentFuelType', 'IntProperty', 0], ['SelectedFuelType', 'IntProperty', 0]]]]]
if itemPropName == "/Script/FactoryGame.FGChainsawItemState":
inventoryStacks[idx][0][0] = ["Item", [itemPathName, [itemPropName, itemProps, [['EnergyStored', 'FloatProperty', 0]]]]]
inventoryStacks[idx][0][1] = ["NumItems", itemQuantity]
print(f"Setting player {playerInventory}'s inventory slot {idx} to include {itemQuantity} x {sav_parse.pathNameToReadableName(itemPathName)} with {sav_parse.toString(itemProps)}")
modifiedFlag = True
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
if not modifiedFlag:
print("ERROR: Failed to find inventory slot to modify.", file=sys.stderr)
exit(1)
try:
if changeTimeFlag:
saveFileInfo.saveDateTimeInTicks += sav_parse.TICKS_IN_SECOND
sav_to_resave.saveFile(saveFileInfo, headhex, grids, levels, extraObjectReferenceList, outFilename)
if VERIFY_CREATED_SAVE_FILES:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(outFilename)
print("Validation successful")
except Exception as error:
raise Exception(f"ERROR: While validating resave of '{savFilename}' to '{outFilename}': {error}")
elif len(sys.argv) in (8, 9) and sys.argv[1] == "--tweak-player-inventory" and os.path.isfile(sys.argv[6]):
playerId = sys.argv[2]
tweakSlotIdx = int(sys.argv[3])
tweakItemName = sys.argv[4]
tweakQuantity = int(sys.argv[5])
savFilename = sys.argv[6]
outFilename = sys.argv[7]
changeTimeFlag = True
if len(sys.argv) == 9 and sys.argv[8] == "--same-time":
changeTimeFlag = False
if tweakItemName not in sav_parse.ITEMS_FOR_PLAYER_INVENTORY:
for className in sav_parse.READABLE_PATH_NAME_CORRECTIONS:
if tweakItemName == sav_parse.READABLE_PATH_NAME_CORRECTIONS[className]:
suffixSearch = f".{className}"
for pathName in sav_parse.ITEMS_FOR_PLAYER_INVENTORY:
if pathName.endswith(suffixSearch):
print(f"Using '{pathName}' for {tweakItemName}")
tweakItemName = pathName
break
break
if tweakItemName not in sav_parse.ITEMS_FOR_PLAYER_INVENTORY:
print(f"ERROR: {tweakItemName} not a valid item path name.")
exit(1)
modifiedFlag = False
try:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
playerPaths = getPlayerPaths(levels)
playerInventory = None
for (playerStateInstanceName, characterPlayer, inventoryPath, armsPath, backPath, legsPath, headPath, bodyPath, healthPath) in playerPaths:
if characterPlayerMatch(characterPlayer, playerId):
playerInventory = inventoryPath
if playerInventory == None:
print(f"Unable to match player '{playerId}'")
exit(1)
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for object in objects:
if object.instanceName == playerInventory:
inventoryStacks = sav_parse.getPropertyValue(object.properties, "mInventoryStacks")
if inventoryStacks:
for idx in range(len(inventoryStacks)):
if idx == tweakSlotIdx:
print(f"Replacing {sav_parse.toString(inventoryStacks[idx][0])}")
inventoryStacks[idx][0][0] = ["Item", [tweakItemName, 1]]
inventoryStacks[idx][0][1] = ["NumItems", tweakQuantity]
print(f"Setting player {playerInventory}'s inventory slot {tweakSlotIdx} to include {tweakQuantity} x {sav_parse.pathNameToReadableName(tweakItemName)}")
modifiedFlag = True
except Exception as error:
raise Exception(f"ERROR: While processing '{savFilename}': {error}")
if not modifiedFlag:
print("ERROR: Failed to find inventory slot to modify.", file=sys.stderr)
exit(1)
try:
if changeTimeFlag:
saveFileInfo.saveDateTimeInTicks += sav_parse.TICKS_IN_SECOND
sav_to_resave.saveFile(saveFileInfo, headhex, grids, levels, extraObjectReferenceList, outFilename)
if VERIFY_CREATED_SAVE_FILES:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(outFilename)
print("Validation successful")
except Exception as error:
raise Exception(f"ERROR: While validating resave of '{savFilename}' to '{outFilename}': {error}")
elif len(sys.argv) in (6, 7) and sys.argv[1] == "--rotate-foundations" and os.path.isfile(sys.argv[4]):
colorPrimary = sys.argv[2]
colorSecondary = sys.argv[3]
savFilename = sys.argv[4]
outFilename = sys.argv[5]
changeTimeFlag = True
if len(sys.argv) == 7 and sys.argv[6] == "--same-time":
changeTimeFlag = False
modifiedFlag = False
try:
(saveFileInfo, headhex, grids, levels, extraObjectReferenceList) = sav_parse.readFullSaveFile(savFilename)
for (levelName, actorAndComponentObjectHeaders, collectables1, objects, collectables2) in levels:
for object in objects:
if object.instanceName.startswith("Persistent_Level:PersistentLevel.BP_GameState_C_"):
playerGlobalColorPresets = sav_parse.getPropertyValue(object.properties, "mPlayerGlobalColorPresets")
if playerGlobalColorPresets != None:
for color in playerGlobalColorPresets:
presetName = sav_parse.getPropertyValue(color[0], "PresetName")
if presetName != None:
presetName = presetName[3]