-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSatisfactoryLP.py
2115 lines (1678 loc) · 61.2 KB
/
SatisfactoryLP.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/env python
# pyright: basic
from dataclasses import dataclass
from fractions import Fraction
import scipy.optimize
import json
import numpy as np
import re
import sys
import argparse
from collections import defaultdict
from pprint import pprint
from typing import Any, Iterable, TypeVar, cast
T = TypeVar("T")
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
"--machine-penalty",
type=float,
default=1000.0,
help="objective penalty per machine built",
)
parser.add_argument(
"--conveyor-penalty",
type=float,
default=0.0,
help="objective penalty per conveyor belt of machine input/output",
)
parser.add_argument(
"--pipeline-penalty",
type=float,
default=0.0,
help="objective penalty per pipeline of machine input/output",
)
parser.add_argument(
"--machine-limit",
type=float,
help="hard limit on number of machines built",
)
parser.add_argument(
"--transport-power-cost",
type=float,
default=0.0,
help="added power cost to simulate transport per conveyor/pipeline of mined resource",
)
parser.add_argument(
"--drone-battery-cost",
type=float,
default=0.0,
help="added battery cost to simulate drone transport per conveyor/pipeline of mined resource",
)
parser.add_argument(
"--miner-clocks",
type=str,
default="2.5",
help="clock choices for miners (excluding Water Extractors)",
)
parser.add_argument(
"--manufacturer-clocks",
type=str,
default="0-2.5/0.05",
help="clock choices for non-somerslooped manufacturers (plus Water Extractors)",
)
parser.add_argument(
"--somersloop-clocks",
type=str,
default="2.5",
help="clock choices for somerslooped manufacturers",
)
parser.add_argument(
"--generator-clocks",
type=str,
default="2.5",
help="clock choices for power generators",
)
parser.add_argument(
"--num-alien-power-augmenters",
type=int,
default=0,
help="number of Alien Power Augmenters to build",
)
parser.add_argument(
"--num-fueled-alien-power-augmenters",
type=float,
default=0,
help="number of Alien Power Augmenters to fuel with Alien Power Matrix",
)
parser.add_argument(
"--disable-production-amplification",
action="store_true",
help="disable usage of somersloops in manufacturers",
)
parser.add_argument(
"--resource-multipliers",
type=str,
default="",
help="comma-separated list of item_class:multiplier to scale resource node availability",
)
parser.add_argument(
"--num-somersloops-available",
type=int,
help="override number of somersloops available for production and APAs",
)
parser.add_argument(
"--disabled-recipes",
type=str,
default="",
help="comma-separated list of recipe_class to disable",
)
parser.add_argument(
"--infinite-power",
action="store_true",
help="allow free infinite power consumption",
)
parser.add_argument(
"--allow-waste",
action="store_true",
help="allow accumulation of nuclear waste and other unsinkable items",
)
parser.add_argument(
"--show-unused",
action="store_true",
help="show unused LP columns (coeff 0) in the optimization result",
)
parser.add_argument(
"--dump-debug-info",
action="store_true",
help="dump debug info to DebugInfo.txt (items, recipes, LP matrix, etc.)",
)
parser.add_argument(
"--xlsx-report",
type=str,
default="Report.xlsx",
help="path to xlsx report output (empty string to disable)",
)
parser.add_argument(
"--xlsx-sheet-suffix",
type=str,
default="",
help="suffix to add to xlsx sheet names",
)
args = parser.parse_args()
### Constants ###
# Common
STACK_SIZES = {
"SS_HUGE": 500,
"SS_BIG": 200,
"SS_MEDIUM": 100,
"SS_SMALL": 50,
"SS_ONE": 1,
"SS_FLUID": 50000,
}
# Clock speeds
INVERSE_CLOCK_GRANULARITY = 100 * 10000
def float_to_clock(value: float) -> Fraction:
return Fraction(round(value * INVERSE_CLOCK_GRANULARITY), INVERSE_CLOCK_GRANULARITY)
def str_to_clock(s: str) -> Fraction:
return float_to_clock(float(s))
def clock_to_percent_str(clock: Fraction) -> str:
return f"{float(100 * clock)}%"
MACHINE_BASE_CLOCK = float_to_clock(1.0)
MACHINE_MAX_CLOCK = float_to_clock(2.5)
# Logistics
CONVEYOR_BELT_CLASS = "Build_ConveyorBeltMk6_C"
PIPELINE_CLASS = "Build_PipelineMK2_C"
# Miners
MINER_CLASS = "Build_MinerMk3_C"
OIL_EXTRACTOR_CLASS = "Build_OilPump_C"
WATER_EXTRACTOR_CLASS = "Build_WaterPump_C"
RESOURCE_WELL_EXTRACTOR_CLASS = "Build_FrackingExtractor_C"
RESOURCE_WELL_PRESSURIZER_CLASS = "Build_FrackingSmasher_C"
ALL_MINER_CLASSES = (
MINER_CLASS,
OIL_EXTRACTOR_CLASS,
WATER_EXTRACTOR_CLASS,
RESOURCE_WELL_PRESSURIZER_CLASS,
)
# Sink
SINK_CLASS = "Build_ResourceSink_C"
# Items
ALL_ITEM_NATIVE_CLASSES = (
"FGItemDescriptor",
"FGItemDescriptorBiomass",
"FGItemDescriptorNuclearFuel",
"FGItemDescriptorPowerBoosterFuel",
"FGResourceDescriptor",
"FGEquipmentDescriptor",
"FGConsumableDescriptor",
"FGPowerShardDescriptor",
"FGAmmoTypeProjectile",
"FGAmmoTypeInstantHit",
"FGAmmoTypeSpreadshot",
)
# Water
WATER_CLASS = "Desc_Water_C"
# Generators (excl. geothermal)
ALL_GENERATOR_NATIVE_CLASSES = (
"FGBuildableGeneratorFuel",
"FGBuildableGeneratorNuclear",
)
# Geothermal generator
GEOTHERMAL_GENERATOR_CLASS = "Build_GeneratorGeoThermal_C"
GEYSER_CLASS = "Desc_Geyser_C"
# Alien Power Augmenter
ALIEN_POWER_AUGMENTER_CLASS = "Build_AlienPowerBuilding_C"
ALIEN_POWER_MATRIX_CLASS = "Desc_AlienPowerFuel_C"
# Resource map
PURITY_MULTIPLIERS = {
"impure": 0.5,
"normal": 1.0,
"pure": 2.0,
}
RESOURCE_MAPPINGS = {
"Desc_LiquidOilWell_C": "Desc_LiquidOil_C",
}
# Miscellaneous
BATTERY_CLASS = "Desc_Battery_C"
ADDITIONAL_DISPLAY_NAMES = {
GEYSER_CLASS: "Geyser",
}
### Debug ###
DEBUG_INFO_PATH = r"DebugInfo.txt"
PPRINT_WIDTH = 120
debug_file = (
open(DEBUG_INFO_PATH, mode="w", encoding="utf-8") if args.dump_debug_info else None
)
def debug_dump(heading: str, obj: object):
if debug_file is None:
return
print(f"========== {heading} ==========", file=debug_file)
print("", file=debug_file)
if isinstance(obj, str):
print(obj, file=debug_file)
else:
pprint(obj, stream=debug_file, width=PPRINT_WIDTH, sort_dicts=False)
print("", file=debug_file)
### Configured clock speeds ###
def parse_clock_spec(s: str) -> list[Fraction]:
result: list[Fraction] = []
for token in s.split(","):
token = token.strip()
if "/" in token:
bounds, _, step_str = token.rpartition("/")
lower_str, _, upper_str = bounds.rpartition("-")
lower = str_to_clock(lower_str)
upper = str_to_clock(upper_str)
step = str_to_clock(step_str)
current = lower
while current <= upper:
result.append(current)
current += step
else:
result.append(str_to_clock(token))
result.sort()
return result
MINER_CLOCKS = parse_clock_spec(args.miner_clocks)
MANUFACTURER_CLOCKS = parse_clock_spec(args.manufacturer_clocks)
SOMERSLOOP_CLOCKS = parse_clock_spec(args.somersloop_clocks)
GENERATOR_CLOCKS = parse_clock_spec(args.generator_clocks)
debug_dump(
"Configured clock speeds",
f"""
{MINER_CLOCKS=}
{MANUFACTURER_CLOCKS=}
{SOMERSLOOP_CLOCKS=}
{GENERATOR_CLOCKS=}
""".strip(),
)
### Configured resource multipliers ###
def parse_resource_multipliers(s: str) -> dict[str, float]:
result: dict[str, float] = {}
if s:
for token in s.split(","):
item_class, _, multiplier = token.partition(":")
assert item_class not in result
result[item_class] = float(multiplier)
return result
RESOURCE_MULTIPLIERS = parse_resource_multipliers(args.resource_multipliers)
debug_dump(
"Configured resource multipliers",
f"""
{RESOURCE_MULTIPLIERS=}
""".strip(),
)
### Configured disabled recipes ###
DISABLED_RECIPES: list[str] = [
token.strip() for token in args.disabled_recipes.split(",")
]
debug_dump(
"Configured disabled recipes",
f"""
{DISABLED_RECIPES=}
""".strip(),
)
### Load json ###
DOCS_PATH = r"Docs.json"
MAP_INFO_PATH = r"MapInfo.json"
with open(DOCS_PATH, "r", encoding="utf-16") as f:
docs_raw = json.load(f)
### Initial parsing ###
class_name_to_entry: dict[str, dict[str, Any]] = {}
native_class_to_class_entries: dict[str, list[dict[str, Any]]] = {}
NATIVE_CLASS_REGEX = re.compile(r"/Script/CoreUObject.Class'/Script/FactoryGame.(\w+)'")
def parse_and_add_fg_entry(fg_entry: dict[str, Any]):
m = NATIVE_CLASS_REGEX.fullmatch(fg_entry["NativeClass"])
assert m is not None, fg_entry["NativeClass"]
native_class = m.group(1)
class_entries: list[dict[str, Any]] = []
for class_entry in fg_entry["Classes"]:
class_name = class_entry["ClassName"]
if class_name in class_name_to_entry:
print(f"WARNING: ignoring duplicate class {class_name}")
else:
class_name_to_entry[class_name] = class_entry
class_entries.append(class_entry)
native_class_to_class_entries[native_class] = class_entries
for fg_entry in docs_raw:
parse_and_add_fg_entry(fg_entry)
### Parsing helpers ###
def parse_paren_list(s: str) -> list[str] | None:
if not s:
return None
assert s.startswith("(") and s.endswith(")")
s = s[1:-1]
if not s:
return []
else:
return s.split(",")
QUALIFIED_CLASS_NAME_REGEX = re.compile(r"\"?/Script/[^']+'/[\w\-/]+\.(\w+)'\"?")
UNQUALIIFIED_CLASS_NAME_REGEX = re.compile(r"\"?/[\w\-/]+\.(\w+)\"?")
def extract_class_name(s: str) -> str:
m = QUALIFIED_CLASS_NAME_REGEX.fullmatch(
s
) or UNQUALIIFIED_CLASS_NAME_REGEX.fullmatch(s)
assert m is not None, s
return m.group(1)
def parse_class_list(s: str) -> list[str] | None:
l = parse_paren_list(s)
if l is None:
return None
return [extract_class_name(x) for x in l]
ITEM_AMOUNT_REGEX = re.compile(r"\(ItemClass=([^,]+),Amount=(\d+)\)")
def find_item_amounts(s: str) -> Iterable[tuple[str, int]]:
for m in ITEM_AMOUNT_REGEX.finditer(s):
yield (extract_class_name(m[1]), int(m[2]))
### Misc constants ###
CONVEYOR_BELT_LIMIT = 0.5 * float(class_name_to_entry[CONVEYOR_BELT_CLASS]["mSpeed"])
PIPELINE_LIMIT = 60000.0 * float(class_name_to_entry[PIPELINE_CLASS]["mFlowLimit"])
SINK_POWER_CONSUMPTION = float(class_name_to_entry[SINK_CLASS]["mPowerConsumption"])
debug_dump(
"Misc constants",
f"""
{CONVEYOR_BELT_LIMIT=}
{PIPELINE_LIMIT=}
{SINK_POWER_CONSUMPTION=}
""".strip(),
)
ALIEN_POWER_AUGMENTER_STATIC_POWER = float(
class_name_to_entry[ALIEN_POWER_AUGMENTER_CLASS]["mBasePowerProduction"]
)
ALIEN_POWER_AUGMENTER_BASE_CIRCUIT_BOOST = float(
class_name_to_entry[ALIEN_POWER_AUGMENTER_CLASS]["mBaseBoostPercentage"]
)
ALIEN_POWER_AUGMENTER_FUELED_CIRCUIT_BOOST = (
ALIEN_POWER_AUGMENTER_BASE_CIRCUIT_BOOST
+ float(class_name_to_entry[ALIEN_POWER_MATRIX_CLASS]["mBoostPercentage"])
)
ALIEN_POWER_AUGMENTER_FUEL_INPUT_RATE = 60.0 / float(
class_name_to_entry[ALIEN_POWER_MATRIX_CLASS]["mBoostDuration"]
)
debug_dump(
"Alien Power Augmenter constants",
f"""
{ALIEN_POWER_AUGMENTER_STATIC_POWER=}
{ALIEN_POWER_AUGMENTER_BASE_CIRCUIT_BOOST=}
{ALIEN_POWER_AUGMENTER_FUELED_CIRCUIT_BOOST=}
{ALIEN_POWER_AUGMENTER_FUEL_INPUT_RATE=}
""".strip(),
)
### Classes ###
@dataclass
class ClassObject:
class_name: str
display_name: str
@dataclass
class Machine(ClassObject):
min_clock: Fraction
max_clock: Fraction
@dataclass
class PowerConsumer(Machine):
power_consumption: float
power_consumption_exponent: float
is_variable_power: bool
@dataclass
class Miner(PowerConsumer):
extraction_rate_base: float
uses_resource_wells: bool
allowed_resource_forms: list[str]
only_allow_certain_resources: bool
allowed_resources: list[str] | None
def check_allowed_resource(self, item_class: str, form: str) -> bool:
if form not in self.allowed_resource_forms:
return False
if self.only_allow_certain_resources:
assert self.allowed_resources
return item_class in self.allowed_resources
else:
return True
@dataclass
class Manufacturer(PowerConsumer):
can_change_production_boost: bool
base_production_boost: float
production_shard_slot_size: int
production_shard_boost_multiplier: float
production_boost_power_consumption_exponent: float
@dataclass
class Recipe(ClassObject):
manufacturer: str
inputs: list[tuple[str, float]]
outputs: list[tuple[str, float]]
mean_variable_power_consumption: float
@dataclass
class Item(ClassObject):
class_name: str
display_name: str
form: str
points: int
stack_size: int
energy: float
@dataclass
class Fuel:
fuel_class: str
supplemental_resource_class: str | None
byproduct: str | None
byproduct_amount: int
@dataclass
class PowerGenerator(Machine):
fuels: list[Fuel]
power_production: float
requires_supplemental: bool
supplemental_to_power_ratio: float
@dataclass
class GeothermalGenerator(Machine):
mean_variable_power_production: float
### Miners ###
def parse_miner(entry: dict[str, Any]) -> Miner:
# Resource well extractors are aggregated under the pressurizer
if entry["ClassName"] == RESOURCE_WELL_PRESSURIZER_CLASS:
extractor = class_name_to_entry[RESOURCE_WELL_EXTRACTOR_CLASS]
uses_resource_wells = True
else:
extractor = entry
uses_resource_wells = False
assert entry["mCanChangePotential"] == "True"
assert str_to_clock(entry["mMaxPotential"]) == MACHINE_BASE_CLOCK
assert entry["mCanChangeProductionBoost"] == "False"
# This will be multiplied by the purity when applied to a node
# (or, for resource wells, the sum of satellite purities).
extraction_rate_base = (
60.0
/ float(extractor["mExtractCycleTime"])
* float(extractor["mItemsPerCycle"])
)
allowed_resource_forms = parse_paren_list(extractor["mAllowedResourceForms"])
assert allowed_resource_forms is not None
return Miner(
class_name=entry["ClassName"],
display_name=entry["mDisplayName"],
power_consumption=float(entry["mPowerConsumption"]),
power_consumption_exponent=float(entry["mPowerConsumptionExponent"]),
min_clock=str_to_clock(entry["mMinPotential"]),
max_clock=MACHINE_MAX_CLOCK,
is_variable_power=False,
extraction_rate_base=extraction_rate_base,
uses_resource_wells=uses_resource_wells,
allowed_resource_forms=allowed_resource_forms,
only_allow_certain_resources=(
extractor["mOnlyAllowCertainResources"] == "True"
),
allowed_resources=parse_class_list(extractor["mAllowedResources"]),
)
miners: dict[str, Miner] = {}
for class_name in ALL_MINER_CLASSES:
miners[class_name] = parse_miner(class_name_to_entry[class_name])
debug_dump("Parsed miners", miners)
### Manufacturers ###
def parse_manufacturer(entry: dict[str, Any], is_variable_power: bool) -> Manufacturer:
class_name = entry["ClassName"]
assert entry["mCanChangePotential"] == "True"
assert str_to_clock(entry["mMaxPotential"]) == MACHINE_BASE_CLOCK
can_change_production_boost = entry["mCanChangeProductionBoost"] == "True"
production_shard_slot_size = int(entry["mProductionShardSlotSize"])
# Smelter has "mProductionShardSlotSize": "0" when it should be 1
if class_name == "Build_SmelterMk1_C":
assert can_change_production_boost
if production_shard_slot_size == 0:
production_shard_slot_size = 1
return Manufacturer(
class_name=class_name,
display_name=entry["mDisplayName"],
power_consumption=float(entry["mPowerConsumption"]),
power_consumption_exponent=float(entry["mPowerConsumptionExponent"]),
min_clock=str_to_clock(entry["mMinPotential"]),
max_clock=MACHINE_MAX_CLOCK,
is_variable_power=is_variable_power,
can_change_production_boost=(entry["mCanChangeProductionBoost"] == "True"),
base_production_boost=float(entry["mBaseProductionBoost"]),
production_shard_slot_size=production_shard_slot_size,
production_shard_boost_multiplier=float(
entry["mProductionShardBoostMultiplier"]
),
production_boost_power_consumption_exponent=float(
entry["mProductionBoostPowerConsumptionExponent"]
),
)
manufacturers: dict[str, Manufacturer] = {}
for entry in native_class_to_class_entries["FGBuildableManufacturer"]:
manufacturer = parse_manufacturer(entry, is_variable_power=False)
manufacturers[manufacturer.class_name] = manufacturer
for entry in native_class_to_class_entries["FGBuildableManufacturerVariablePower"]:
manufacturer = parse_manufacturer(entry, is_variable_power=True)
manufacturers[manufacturer.class_name] = manufacturer
debug_dump("Parsed manufacturers", manufacturers)
### Recipes ###
def parse_recipe(entry: dict[str, Any]) -> Recipe | None:
produced_in = parse_class_list(entry["mProducedIn"]) or []
recipe_manufacturer = None
for manufacturer in produced_in:
if manufacturer in manufacturers:
recipe_manufacturer = manufacturer
break
if recipe_manufacturer is None:
# check that recipe is not automatable for known reasons
assert (
not produced_in
or "BP_WorkshopComponent_C" in produced_in
or "BP_BuildGun_C" in produced_in
or "FGBuildGun" in produced_in
), f"{entry["mDisplayName"]} {produced_in}"
return None
recipe_rate = 60.0 / float(entry["mManufactoringDuration"])
def item_rates(key: str):
return [
(item, recipe_rate * amount)
for (item, amount) in find_item_amounts(entry[key])
]
vpc_constant = float(entry["mVariablePowerConsumptionConstant"])
vpc_factor = float(entry["mVariablePowerConsumptionFactor"])
# Assuming the mean is exactly halfway for all of the variable power machine types.
# This appears to be accurate but it's hard to confirm exactly.
mean_variable_power_consumption = vpc_constant + 0.5 * vpc_factor
return Recipe(
class_name=entry["ClassName"],
display_name=entry["mDisplayName"],
manufacturer=recipe_manufacturer,
inputs=item_rates("mIngredients"),
outputs=item_rates("mProduct"),
mean_variable_power_consumption=mean_variable_power_consumption,
)
recipes: dict[str, Recipe] = {}
for entry in native_class_to_class_entries["FGRecipe"]:
recipe = parse_recipe(entry)
if recipe is not None:
recipes[recipe.class_name] = recipe
debug_dump("Parsed recipes", recipes)
### Items ###
def parse_item(entry: dict[str, Any]) -> Item:
return Item(
class_name=entry["ClassName"],
display_name=entry["mDisplayName"],
form=entry["mForm"],
points=int(entry["mResourceSinkPoints"]),
stack_size=STACK_SIZES[entry["mStackSize"]],
energy=float(entry["mEnergyValue"]),
)
items: dict[str, Item] = {}
for native_class in ALL_ITEM_NATIVE_CLASSES:
for entry in native_class_to_class_entries[native_class]:
item = parse_item(entry)
items[item.class_name] = item
debug_dump("Parsed items", items)
### Generators ###
def parse_fuel(entry: dict[str, Any]) -> Fuel:
byproduct_amount = entry["mByproductAmount"]
return Fuel(
fuel_class=entry["mFuelClass"],
supplemental_resource_class=entry["mSupplementalResourceClass"] or None,
byproduct=entry["mByproduct"] or None,
byproduct_amount=int(byproduct_amount) if byproduct_amount else 0,
)
def parse_generator(entry: dict[str, Any]) -> PowerGenerator:
fuels = [parse_fuel(fuel) for fuel in entry["mFuel"]]
assert entry["mCanChangePotential"] == "True"
assert str_to_clock(entry["mMaxPotential"]) == MACHINE_BASE_CLOCK
return PowerGenerator(
class_name=entry["ClassName"],
display_name=entry["mDisplayName"],
fuels=fuels,
power_production=float(entry["mPowerProduction"]),
min_clock=str_to_clock(entry["mMinPotential"]),
max_clock=MACHINE_MAX_CLOCK,
requires_supplemental=(entry["mRequiresSupplementalResource"] == "True"),
supplemental_to_power_ratio=float(entry["mSupplementalToPowerRatio"]),
)
def parse_geothermal_generator(entry: dict[str, Any]) -> GeothermalGenerator:
# "mVariablePowerProductionConstant": "0.000000" should be 100 MW, hardcode it here
vpp_constant = 100.0
vpp_factor = float(entry["mVariablePowerProductionFactor"])
# Assuming the mean power production is exactly halfway.
mean_variable_power_production = vpp_constant + 0.5 * vpp_factor
assert entry["mCanChangePotential"] == "False"
return GeothermalGenerator(
class_name=entry["ClassName"],
display_name=entry["mDisplayName"],
min_clock=MACHINE_BASE_CLOCK,
max_clock=MACHINE_BASE_CLOCK,
mean_variable_power_production=mean_variable_power_production,
)
generators: dict[str, PowerGenerator] = {}
for native_class in ALL_GENERATOR_NATIVE_CLASSES:
for entry in native_class_to_class_entries[native_class]:
generator = parse_generator(entry)
generators[generator.class_name] = generator
# geothermal generator (special case)
geothermal_generator = parse_geothermal_generator(
class_name_to_entry[GEOTHERMAL_GENERATOR_CLASS]
)
debug_dump("Parsed generators", generators)
debug_dump("Parsed geothermal generator", geothermal_generator)
### Map info ###
with open(MAP_INFO_PATH, "r") as f:
map_info_raw = json.load(f)
map_info: dict[str, Any] = {}
for tab in map_info_raw["options"]:
if "tabId" in tab:
map_info[tab["tabId"]] = tab["options"]
### Resources ###
@dataclass
class Resource:
resource_id: str
item_class: str
subtype: str
multiplier: float
is_unlimited: bool
count: int
is_resource_well: bool
num_satellites: int
resources: dict[str, Resource] = {}
geysers: dict[str, Resource] = {}
# Persistent_Level:PersistentLevel.BP_FrackingCore6_UAID_40B076DF2F79D3DF01_1961476789
# becomes #6. We can strip out the UAID as long as it's unique for each item type.
FRACKING_CORE_REGEX = re.compile(
r"Persistent_Level:PersistentLevel\.BP_FrackingCore_?(\d+)(_UAID_\w+)?"
)
def parse_fracking_core_name(s: str) -> str:
m = FRACKING_CORE_REGEX.fullmatch(s)
assert m is not None, s
return "#" + m.group(1)
def parse_and_add_resources(map_resource: dict[str, Any]):
if "type" not in map_resource:
return
item_class = map_resource["type"]
if item_class in RESOURCE_MAPPINGS:
item_class = RESOURCE_MAPPINGS[item_class]
if item_class == GEYSER_CLASS:
output = geysers
else:
output = resources
assert item_class in items, f"map has unknown resource: {item_class}"
for node_purity in map_resource["options"]:
purity = node_purity["purity"]
nodes = node_purity["markers"]
if not nodes:
continue
sample_node = nodes[0]
if "core" in sample_node:
# resource well satellite nodes, map to cores and sum the purity multipliers
for node in nodes:
subtype = parse_fracking_core_name(node["core"])
resource_id = f"{item_class}|{subtype}"
if resource_id not in output:
output[resource_id] = Resource(
resource_id=resource_id,
item_class=item_class,
subtype=subtype,
multiplier=0.0,
is_unlimited=False,
count=1,
is_resource_well=True,
num_satellites=0,
)
output[resource_id].multiplier += PURITY_MULTIPLIERS[purity]
output[resource_id].num_satellites += 1
else:
# normal nodes, add directly
subtype = purity # individual nodes are indistinguishable
resource_id = f"{item_class}|{subtype}"
assert resource_id not in output
output[resource_id] = Resource(
resource_id=resource_id,
item_class=item_class,
subtype=subtype,
multiplier=PURITY_MULTIPLIERS[purity],
is_unlimited=False,
count=len(nodes),
is_resource_well=False,
num_satellites=0,
)
for map_resource in map_info["resource_nodes"]:
parse_and_add_resources(map_resource)
for map_resource in map_info["resource_wells"]:
parse_and_add_resources(map_resource)
# Water from extractors is a special infinite resource
resources[f"{WATER_CLASS}|extractor"] = Resource(
resource_id=f"{WATER_CLASS}|extractor",
item_class=WATER_CLASS,
subtype="extractor",
multiplier=1,
is_unlimited=True,
count=0,
is_resource_well=False,
num_satellites=0,
)
debug_dump("Parsed resources", resources)
debug_dump("Parsed geysers", geysers)
### Somersloops ###
def find_somersloops_map_layer(
map_tab_artifacts: list[dict[str, list[dict[str, Any]]]]
):
for unknown_level in map_tab_artifacts:
for map_layer in unknown_level["options"]:
if map_layer["layerId"] == "somersloops":
return map_layer
raise RuntimeError("failed to find somersloops map layer")
def parse_num_somersloops_on_map(somersloops_map_layer: dict[str, Any]) -> int:
count = 0
for marker in somersloops_map_layer["markers"]:
if marker["type"] == "somersloop":
count += 1
return count
PRODUCTION_AMPLIFIER_UNLOCK_SOMERSLOOP_COST = 1
ALIEN_POWER_AUGMENTER_UNLOCK_SOMERSLOOP_COST = 1
ALIEN_POWER_AUGMENTER_BUILD_SOMERSLOOP_COST = 10
def get_num_somersloops_available() -> int:
if args.num_somersloops_available is not None:
return args.num_somersloops_available
num_somersloops_on_map = parse_num_somersloops_on_map(
find_somersloops_map_layer(map_info["artifacts"])
)
research_somersloop_cost = (
PRODUCTION_AMPLIFIER_UNLOCK_SOMERSLOOP_COST
if not args.disable_production_amplification
else 0
) + (
ALIEN_POWER_AUGMENTER_UNLOCK_SOMERSLOOP_COST
if args.num_alien_power_augmenters > 0
else 0
)
assert research_somersloop_cost <= num_somersloops_on_map
return num_somersloops_on_map - research_somersloop_cost
NUM_SOMERSLOOPS_AVAILABLE = get_num_somersloops_available()
POWER_SOMERSLOOP_COST: int = (
ALIEN_POWER_AUGMENTER_BUILD_SOMERSLOOP_COST * args.num_alien_power_augmenters
)
assert (
POWER_SOMERSLOOP_COST <= NUM_SOMERSLOOPS_AVAILABLE
), f"{POWER_SOMERSLOOP_COST=} {NUM_SOMERSLOOPS_AVAILABLE=}"
NUM_SOMERSLOOPS_AVAILABLE_FOR_PRODUCTION = (
NUM_SOMERSLOOPS_AVAILABLE - POWER_SOMERSLOOP_COST
)
assert args.num_fueled_alien_power_augmenters <= args.num_alien_power_augmenters
ALIEN_POWER_AUGMENTER_TOTAL_STATIC_POWER: float = (
ALIEN_POWER_AUGMENTER_STATIC_POWER * args.num_alien_power_augmenters
)
ALIEN_POWER_AUGMENTER_TOTAL_CIRCUIT_BOOST: float = (