-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdecode
More file actions
executable file
·2902 lines (2277 loc) · 91.6 KB
/
decode
File metadata and controls
executable file
·2902 lines (2277 loc) · 91.6 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/python3
import argparse
import sys
import struct
import json
import time
import traceback
from enum import Enum
import io
version = None # global state is not nice but that's how it is for now.
skipped_blueprints = 0
################################################################
#
# utilities
def debug(*args):
if opt.d:
print(*args, file=sys.stderr, flush=True)
def verbose(*args):
if opt.v or opt.d:
print(*args, file=sys.stderr, flush=True)
def error(*args):
print(*args, file=sys.stderr, flush=True)
def normalize_float(value):
rounded = round(value)
if rounded == value:
return rounded
else:
return value
def normalize_position(p):
p["x"] = normalize_float(p["x"])
p["y"] = normalize_float(p["y"])
class ParseError(Exception):
pass
################################################################
#
# Version
class Version(int):
def __new__(cls, v0: int, v1: int, v2: int, v3: int = 0):
encoded = (v0 << 48) + (v1 << 32) + (v2 << 16) + v3
return super().__new__(cls, encoded)
def __format__(self, spec):
decoded = self._decode()
return format(".".join(map(str, decoded)), spec)
def __repr__(self):
v0, v1, v2, v3 = self._decode()
return f"Version({v0}, {v1}, {v2}, {v3})"
def _decode(self):
def _(bits):
return int(self) >> bits & 0xffff
return ( _(48), _(32), _(16), _(0) )
V_1_0_0_0 = Version(1,0,0) # first stable in 1.0 -- obviously
V_1_1_0_0 = Version(1,1,0) # first EXPERIMENTAL in 1.1
V_1_1_4_0 = Version(1,1,4)
V_1_1_19_0 = Version(1,1,19) # first stable in 1.1 -- not so obvious
V_1_1_43_0 = Version(1,1,43)
V_1_1_51_4 = Version(1,1,51,4)
V_1_1_62_5 = Version(1,1,62,5)
STABLE_V_1_1 = V_1_1_19_0 # marker for "somewhere between 1.0 and first stable 1.1"
MINIMUM_VERSION = V_1_0_0_0
################################################################
#
# Index
class Index:
# types (distinct number ranges)
# `value` is the prototype-class (except "entity"). In BP exports the wording is just "virtual".
class Type(Enum):
ITEM = "item"
FLUID = "fluid"
VSIGNAL = "virtual-signal"
TILE = "tile"
ENTITY = "entity"
RECIPE = "recipe"
ITEM = Type.ITEM
FLUID = Type.FLUID
VSIGNAL = Type.VSIGNAL
TILE = Type.TILE
ENTITY = Type.ENTITY
RECIPE = Type.RECIPE
_type_mapping = {
# item
"ammo": ITEM,
"armor": ITEM,
"blueprint": ITEM,
"blueprint-book": ITEM,
"capsule": ITEM,
"deconstruction-item": ITEM,
"gun": ITEM,
"item": ITEM,
"item-with-entity-data": ITEM,
"module": ITEM,
"spidertron-remote": ITEM,
"rail-planner": ITEM,
"repair-tool": ITEM,
"tool": ITEM,
"upgrade-item": ITEM,
# item without known ways to put them into blueprints
"copy-paste-tool": ITEM,
"item-with-label": ITEM,
"item-with-inventory": ITEM,
"item-with-tags": ITEM,
"mining-tool": ITEM,
"selection-tool": ITEM,
# fluid
"fluid": FLUID,
# virtual-signal
"virtual-signal": VSIGNAL,
# entity
"accumulator": ENTITY,
"ammo-turret": ENTITY,
"arithmetic-combinator": ENTITY,
"artillery-turret": ENTITY,
"artillery-wagon": ENTITY,
"assembling-machine": ENTITY,
"beacon": ENTITY,
"boiler": ENTITY,
"burner-generator": ENTITY,
"cargo-wagon": ENTITY,
"cliff": ENTITY,
"constant-combinator": ENTITY,
"container": ENTITY,
"curved-rail": ENTITY,
"decider-combinator": ENTITY,
"electric-energy-interface": ENTITY,
"electric-pole": ENTITY,
"electric-turret": ENTITY,
"entity-ghost": ENTITY,
"fish": ENTITY,
"fluid-turret": ENTITY,
"fluid-wagon": ENTITY,
"furnace": ENTITY,
"gate": ENTITY,
"generator": ENTITY,
"heat-interface": ENTITY,
"heat-pipe": ENTITY,
"infinity-container": ENTITY,
"infinity-pipe": ENTITY,
"inserter": ENTITY,
"item-entity": ENTITY,
"item-request-proxy": ENTITY,
"lab": ENTITY,
"lamp": ENTITY,
"land-mine": ENTITY,
"linked-belt": ENTITY,
"linked-container": ENTITY,
"loader": ENTITY,
"loader-1x1": ENTITY,
"locomotive": ENTITY,
"logistic-container": ENTITY,
"mining-drill": ENTITY,
"offshore-pump": ENTITY,
"pipe": ENTITY,
"pipe-to-ground": ENTITY,
"power-switch": ENTITY,
"programmable-speaker": ENTITY,
"pump": ENTITY,
"radar": ENTITY,
"rail-chain-signal": ENTITY,
"rail-signal": ENTITY,
"reactor": ENTITY,
"roboport": ENTITY,
"rocket-silo": ENTITY,
"simple-entity": ENTITY,
"solar-panel": ENTITY,
"splitter": ENTITY,
"storage-tank": ENTITY,
"straight-rail": ENTITY,
"tile-ghost": ENTITY,
"train-stop": ENTITY,
"transport-belt": ENTITY,
"tree": ENTITY,
"underground-belt": ENTITY,
"wall": ENTITY,
# tile
"tile": TILE,
# recipe
"recipe": RECIPE,
# special
"flying-text": ENTITY, # no handler (yet), used for "unknown-entity" in upgrade- and deconstruction plans
}
class Entry:
def __init__(self, id: int, type, prototype: str, name: str):
self.id = id
self.type = type
self.prototype = prototype
self.name = name
def __init__(self):
self._data = {
self.ITEM: {},
self.FLUID: {},
self.VSIGNAL: {},
self.TILE: {},
self.ENTITY: {},
self.RECIPE: {},
}
def add(self, id: int, prototype: str, name: str) -> Entry:
if id == 0x00:
raise ValueError("ID 0 is not allowed")
if prototype not in self._type_mapping:
raise KeyError(f"unknown prototype '{prototype}'")
type = self._type_mapping[prototype]
bucket = self._data[type]
if id in bucket:
raise ValueError(f"ID {id} ({id:#x}) is already used for '{bucket[id]['name']}'")
entry = bucket[id] = Index.Entry(id, type, prototype, name)
return entry
def get(self, type: Type, id: int) -> Entry:
return self._data[type][id]
################################################################
#
# primitives
class PrimitiveStream:
def __init__(self, f):
self._f = f
def _read(self, format):
return struct.unpack(
format,
self._f.read(struct.calcsize(format)))[0]
def tell(self):
return self._f.tell()
def seek(self, offset, whence):
return self._f.seek(offset, whence)
def bool(self):
data = self.u8()
if data != 0x00 and data != 0x01:
position = self.tell() - 1
raise ParseError(f"invalid boolean value {data:#04x} at position {position} ({position:#x})")
return data == 0x01
def s8(self):
return self._read("<b")
def u8(self):
return self._read("<B")
def s16(self):
return self._read("<h")
def u16(self):
return self._read("<H")
def s32(self):
return self._read("<i")
def u32(self):
return self._read("<I")
# see https://en.wikipedia.org/wiki/Single-precision_floating-point_format#Single-precision_examples
# for remarkable examples like "0x3f80_0000" for "1"
def f32(self):
return self._read("<f")
# see https://en.wikipedia.org/wiki/Double-precision_floating-point_format#Double-precision_examples
# for remarkable examples like "0x3ff0_0000_0000_0000" for "1"
def f64(self):
return self._read("<d")
def count(self):
length = self.u8()
if length == 0xff:
return self.u32()
else:
return length
def count8(self):
data = self.u8()
if data == 0xff:
position = self.tell()
raise ParseError(f"unexpected flexible length 0xff at {position} ({position:#x})")
return data
def count16(self):
return self.u16()
def count32(self):
return self.u32()
def string(self):
length = self.count()
return self._f.read(length).decode("utf-8")
def mapped_u8(self, *args):
index = self.u8()
if index in range(len(args)):
return args[index]
else:
position = self.tell() - 1
raise ParseError(f"unexpected value {index} at position {position} ({position:#x}): only 0..{len(args)-1} expected")
def expect(self, *expected_bytes):
if not expected_bytes:
raise ValueError("expect at least one byte")
for expected in expected_bytes:
actual = self.u8()
if actual != expected:
position = self.tell() - 1
raise ParseError(f"expected {expected:#04x} but got {actual:#04x} at position {position} ({position:#x})")
def expect_oneof(self, *expected_values):
if not expected_values:
raise ValueError("expect at least one byte")
actual = self.u8()
if actual not in set(expected_values):
position = self.tell() - 1
expected = ", ".join([ f"{b:#04x}" for b in expected_values])
raise ParseError(f"expected one of ({expected}) but got {actual:#04x} at position {position} ({position:#x})")
def ignore(self, size, guess=None):
file_position = self.tell()
data = self._f.read(size)
data = self._to_hex(data)
if guess:
debug(f"#\tignored {guess} @{file_position:#x}: {data}")
else:
debug(f"#\tignored @{file_position:#x}: {data}")
def dump_trailing_data(self, offsets=True, printables=True):
position, data = self._f.tell(), self._f.read(16)
if data:
debug("trailing data:")
while data:
parts = []
if offsets:
parts.append(f"{position:06x}")
parts.append(self._to_hex(data))
if printables:
parts.append(self._to_print(data))
debug(*parts)
position, data = self._f.tell(), self._f.read(16)
@staticmethod
def _to_hex(data: bytes):
return " ".join([f'{b:02x}' for b in data])
@staticmethod
def _to_print(data: bytes):
return "".join([b if b.isprintable() else "." for b in data.decode("latin1")])
################################################################
#
# stream helpers
def read_entry(stream, index: Index, type: Index.Type) -> Index.Entry:
if type == Index.TILE:
id = stream.u8()
offset = 1
else:
id = stream.u16()
offset = 2
if id:
try:
return index.get(type, id)
except KeyError:
file_position = stream.tell() - offset
raise ParseError(f"unknown '{type.value}' ID {id:#x} at {file_position} ({file_position:#x})") from None
else:
return None
def read_name(stream, index: Index, type: Index.Type) -> str:
entry = read_entry(stream, index, type)
if entry:
return entry.name
else:
return None
def read_signal(stream, index: Index):
index_type = stream.mapped_u8(Index.ITEM, Index.FLUID, Index.VSIGNAL)
name = read_name(stream, index, index_type)
if not name:
return None
return {
"type": {Index.ITEM: "item", Index.FLUID: "fluid", Index.VSIGNAL: "virtual"}[index_type],
"name": name
}
# circuit condition, logistic condition, train schedules
#
# length: 12 byte
# default: 01 00 00 00 00 00 00 00 00 00 00 01
#
def read_condition(stream, index: Index):
# same order in drop-down
comparator = stream.mapped_u8(">", "<", "=", "≥", "≤", "≠")
first_signal = read_signal(stream, index)
second_signal = read_signal(stream, index)
constant = stream.s32()
use_constant = stream.bool()
# hide "default" condition
if not first_signal and not second_signal and comparator == "<" and not constant:
return None
condition = {}
if first_signal:
condition["first_signal"] = first_signal
condition["comparator"] = comparator
# The export does not output data if it is hidden in the UI.
if use_constant:
condition["constant"] = constant
else:
condition["second_signal"] = second_signal
return condition
#
# Property Tree
#
# See https://wiki.factorio.com/Property_tree
#
# Known differences:
#
# - Strings in keys (list and dictionaries) and values (type 3) have an
# additional `is_empty` flag.
#
# The wiki insinuates (by linking to Pascal strings) that keys don't
# have an additional flag, only "value" strings.
#
# - The `any-type` flag after the type field should be `False` by default but
# it seems to be `True` sometimes.
#
# Also:
#
# - Type 0 (`None`) cannot be set via Lua: `nil` values in tables just
# don't exist.
# - Type 4 (`List`) cannot be set via Lua: Both arrays and dictionaries are
# the same construct.
#
def read_tag_property_tree(stream):
type = stream.u8()
any_type = stream.bool() # ignored
if type == 0: # None
return None
elif type == 1: # Bool
return stream.bool()
elif type == 2: # Number
return normalize_float(stream.f64())
elif type == 3: # String
return read_tag_string(stream)
elif type == 4: # List
return read_tag_list(stream)
elif type == 5: # Dictionary
return read_tag_dictionary(stream)
else:
position = stream.tell() - 2
raise ParseError(f"invalid type {type} in property tree at position {position} ({position:#x})")
def read_tag_list(stream):
result = []
count = stream.count32()
for i in range(count):
entry_name = read_tag_string(stream) # ignored
entry_value = read_tag_property_tree(stream)
result.append(entry_value)
return result
def read_tag_dictionary(stream):
result = {}
count = stream.count32()
for i in range(count):
entry_name = read_tag_string(stream)
entry_value = read_tag_property_tree(stream)
result[entry_name] = entry_value
return result
def read_tag_string(stream):
is_empty = stream.bool()
if is_empty:
return None
else:
return stream.string()
################################################################
#
# entity parts (ep_*)
def ep_entity_id(stream, index, entity):
flags = stream.u8()
# 0x10 -- has entity id (default=0)
if flags | 0x10 != 0x10:
file_position = stream.tell() - 1
raise ParseError(f"unexpected flags {flags:#04x} at {file_position} ({file_position:#x})")
if flags & 0x10:
stream.expect(0x01)
entity_id = stream.u32()
entity["entity_id"] = entity_id
# Note: The export format uses "entity_number" here but means index
# number in the entity list. This "entity_number" is referenced by
# "entity_id" in the wire connections.
#
# The binary format uses another value - an unique number.
# The code therefore uses the term "entity_id" for the raw binary
# number. This number and the counterparts in the wire connection
# and train schedules must be replaced later when all entities
# (and their *number*) known.
def ep_v1_1_51_4_flag(stream, index, entity, *expected_values):
if version >= V_1_1_51_4:
# * In the vanilla game turrets, land-mines and radar have the
# value 0x01.
# * In the vanilla game rail vehicles (locomotive, cargo-wagon,
# fluid-wagon, artillery-wagon) have the value 0x00 but in
# Krastorio 2 the value is 0x01 without any change in the export.
if len(expected_values) == 1:
stream.expect(*expected_values)
else:
stream.expect_oneof(*expected_values)
def ep_v1_1_62_5_flag(stream, index, entity):
# Release-Notes 1.1.62:
# > Added support for container entities with filters
# > by using inventory_type = "with_bar" or "with_filters_and_bar".
# So this could be a flag opening a "filters" section.
if version >= V_1_1_62_5:
stream.expect(0x00)
def ep_bar(stream, index, entity):
# TODO: cargo-wagon wants to call this not with a real entity
# but with an "inventory" wrapper. Handle this case better.
# "Warehousing Mod" writes 2000 stacks but the UI reports 1800.
bar = stream.u16()
# The export format suppresses the default values. But these
# are - in general - unknown to me beyond the vanilla chests.
bar_defaults = {
# container
"wooden-chest" : 0x10,
"iron-chest" : 0x20,
"steel-chest" : 0x30,
# logistic-container
"logistic-chest-active-provider" : 0x30,
"logistic-chest-passive-provider" : 0x30,
"logistic-chest-storage" : 0x30,
"logistic-chest-requester" : 0x30,
"logistic-chest-buffer" : 0x30,
# cheat mode
"infinity-chest" : 0x30,
# trains
"cargo-wagon" : 0x28,
# Editor Extensions
"ee-infinity-chest" : 0x64,
"ee-infinity-chest-active-provider" : 0x64,
"ee-infinity-chest-passive-provider" : 0x64,
"ee-infinity-chest-storage" : 0x64,
"ee-infinity-chest-buffer" : 0x64,
"ee-infinity-chest-requester" : 0x64,
"ee-aggregate-chest" : -1,
"ee-aggregate-chest-passive-provider": -1,
"ee-infinity-cargo-wagon" : 0x64,
}
default_bar = bar_defaults.get(entity["name"])
if default_bar != -1 and default_bar != bar:
entity["bar"] = bar
# maybe helpfull: https://wiki.factorio.com/Types/Direction
# Turrets seem to support an additional value `8`.
def ep_direction(stream, index, entity):
direction = stream.u8()
if direction:
entity["direction"] = direction
def ep_orientation(stream, index, entity):
# 00 00 00 00 = 0.0f -> North
# 00 00 80 3e = 0.25f -> East
# 00 00 00 3f = 0.5f -> South
# 00 00 40 3f = 0.75f -> West
orientation = stream.f32()
orientation = normalize_float(orientation)
entity["orientation"] = orientation
def ep_logistic_settings(stream, index, entity):
# 1: active provider
# 2: storage
# 3: requester
# 4: passive provider
# 5: buffer
logistic_mode = stream.u8() # not used in export
if not 0 <= logistic_mode <= 5:
raise ParseError(f"unknown logistic mode {logistic_mode}")
stream.expect(0x03)
request_filters = []
filter_count = stream.count()
for f in range(filter_count):
item_name = read_name(stream, index, Index.ITEM)
item_count = stream.u32()
stream.expect(0x00)
if item_name:
request_filters.append({
"index": f + 1,
"name": item_name,
"count": item_count
})
if request_filters:
entity["request_filters"] = request_filters
if logistic_mode in (2,3,5) or version >= STABLE_V_1_1:
# In v1.0.0 every logistic chest which can have logistic-filters
# or -requests has the flag "request from buffers". But the UI
# shows this flag only for requester chests.
# In v1.0.0 the existence of the flag correlates with the number
# of filters because a fixed number of slots were always allocated
# for a specific type of chest.
# Since 1.1.19 the number of filter slots can be extended (and
# possibly shrunk), so this may not be a stable criteria any more.
# So it's nice that the flag is always present since v1.1.19.
request_from_buffers = stream.bool()
if request_from_buffers:
entity["request_from_buffers"] = True
def ep_circuit_connections(stream, index, entity, own_circuit_id="1"):
connections = {}
# How many "colors"?
# https://lua-api.factorio.com/latest/defines.html#defines.wire_type
for color in ("red", "green"):
peers = []
peer_count = stream.count8()
for p in range(peer_count):
entity_id = stream.u32()
circuit_id = stream.u8()
peers.append({
"entity_id": entity_id,
"circuit_id": circuit_id,
})
stream.expect(0xff)
if peers:
connections[color] = peers
# maybe helpfull: https://lua-api.factorio.com/latest/defines.html#defines.circuit_connector_id
if connections:
if "connections" not in entity:
entity["connections"] = {}
entity["connections"][str(own_circuit_id)] = connections
stream.expect(*[0x00]*9)
def ep_circuit_condition(stream, index, entity):
circuit_condition = read_condition(stream, index)
if circuit_condition:
control_behavior = entity.setdefault("control_behavior", {})
control_behavior["circuit_condition"] = circuit_condition
def ep_logistic_condition(stream, index, entity):
logistic_condition = read_condition(stream, index)
if logistic_condition:
control_behavior = entity.setdefault("control_behavior", {})
control_behavior["logistic_condition"] = logistic_condition
logistic_connected = stream.bool()
if logistic_connected:
control_behavior = entity.setdefault("control_behavior", {})
control_behavior["connect_to_logistic_network"] = True
def ep_railway_vehicle_common(stream, index, entity):
stream.expect(*[0x00]*10, 0x01)
# Setable in Krastorio 2 in locomotives, cargo wagon and artillery wagon
# but not fluid wagon.
# Strange: Seems to be stored only in the .dat file but not in the export
# strings. This defeats a perfect round-trip!
enable_logistics_while_moving = stream.bool()
stream.expect(*[0x00]*22)
# 26 22 4f
# e7 73 ed
# ac d3 65
# 84 38 b3 02 # first reported by PDiracDelta
# 56 47 07 09
# Seems to be stuck at (0,0,0,0) since v.1.1.19 or v1.1.21.
stream.ignore(4, "train-id(?)")
stream.expect(0x00)
def ep_filters(stream, index, entity):
# Even without filters the count is > 0 for filter-inserters.
filter_count = stream.u8()
filters = []
for f in range(filter_count):
filter_name = read_name(stream, index, Index.ITEM)
if filter_name:
filters.append({
"index": f + 1,
"name": filter_name
})
if filters:
entity["filters"] = filters
def ep_items(stream, index, entity):
# Interesting point: Items are not a simple list like icons.
# Instead the items are first sorted and then grouped by type.
# So building an assembler with modules Eff1, Sp1, Eff1, Sp1 the blueprint
# only contains the data "Sp1: 2, Eff:2". So some details are omitted.
items = {}
item_count = stream.u32()
for i in range(item_count):
item_name = read_name(stream, index, Index.ITEM)
item_count = stream.u32()
items[item_name] = item_count
if items:
entity["items"] = items
def ep_color(stream, index, entity):
use_color = stream.bool()
if use_color:
entity["color"] = {
"r": normalize_float(stream.f32()),
"g": normalize_float(stream.f32()),
"b": normalize_float(stream.f32()),
"a": normalize_float(stream.f32()),
}
def ep_turret_common(stream, index, entity):
ep_v1_1_51_4_flag(stream, index, entity, 0x01) # Strange: Why is that value "1" HERE!
stream.expect(*[0x00]*4)
stream.expect(0x00, 0x00, 0x80, 0x3f) # 1.0f
stream.expect(*[0x00]*17)
# Strictly speaking: artillery-turret doesn't have "orientation" besides 0.0f.
ep_orientation(stream, index, entity)
def fixup_turret_direction(stream, index, entity):
direction = entity.get("direction")
orientation = entity.pop("orientation", 0.0)
if direction == 8:
# This "precedence" is not backed by hard facts!
# But there are also no counterexamples.
#
# The vanilla game pins `direction` always to `8` for some turret
# types like gun-turrets. But at least one modded turret
# (shotgun-ammo-turret-rampant-arsenal) managed to store "synchronized"
# `direction`/`orientation` values -- just like vanilla flamethrower
# turrets.
direction = int(8 * orientation)
if direction:
entity["direction"] = direction
else:
del entity["direction"]
#
# Currently this is not setable in a vanilla game. The mod
# https://mods.factorio.com/mod/QuickbarTemplates sets a tag
# into a constant-combinator. See:
#
# https://github.com/raiguard/Factorio-SmallMods/blob/master/QuickbarTemplates/control.lua#L81
#
def ep_tags(stream, index, entity):
has_tags = stream.bool();
if has_tags:
tags = {}
# Strange: Although this is conceptually the same as a tag dictionary
# a different encoding is used. Since this encoding is simpler it is
# a pitty that the next layers are encoded more convolutly.
count = stream.count()
for i in range(count):
key = stream.string()
value = read_tag_property_tree(stream)
tags[key] = value
entity["tags"] = tags
################################################################
#
# entity handlers (eh_*)
def eh_container(stream, index, entity):
ep_v1_1_51_4_flag(stream, index, entity, 0x00)
ep_v1_1_62_5_flag(stream, index, entity)
# restriction aka. "bar"
ep_bar(stream, index, entity)
# circuit connections
has_circuit_connections = stream.bool()
if has_circuit_connections:
ep_circuit_connections(stream, index, entity)
def eh_logistic_container(stream, index, entity):
ep_v1_1_51_4_flag(stream, index, entity, 0x00)
ep_v1_1_62_5_flag(stream, index, entity)
# restriction aka. "bar"
ep_bar(stream, index, entity)
stream.expect(0x00)
# request filters and "request from buffers"
has_logistic_settings = stream.bool()
if has_logistic_settings:
ep_logistic_settings(stream, index, entity)
stream.expect(0x00, 0x00)
# circuit connections
has_circuit_connections = stream.bool()
if has_circuit_connections:
ep_circuit_connections(stream, index, entity)
mode_of_operation = stream.u8()
if mode_of_operation:
control_behavior = entity.setdefault("control_behavior", {})
control_behavior["circuit_mode_of_operation"] = mode_of_operation
def eh_infinity_container(stream, index, entity):
ep_v1_1_51_4_flag(stream, index, entity, 0x00)
ep_v1_1_62_5_flag(stream, index, entity)
# restriction aka. "bar"
ep_bar(stream, index, entity)
stream.expect(0x00)
# request filters and "request from buffers"
has_logistic_settings = stream.bool()
if has_logistic_settings:
ep_logistic_settings(stream, index, entity)
stream.expect(0x00, 0x00)
# circuit connections
has_circuit_connections = stream.bool()
if has_circuit_connections:
ep_circuit_connections(stream, index, entity)
mode_of_operation = stream.u8()
if mode_of_operation:
control_behavior = entity.setdefault("control_behavior", {})
control_behavior["circuit_mode_of_operation"] = mode_of_operation
# infinity settings
entity["infinity_settings"] = {}
filters = []
filter_count = stream.count()
for f in range(filter_count):
item_name = read_name(stream, index, Index.ITEM)
item_count = stream.u32()
mode = stream.mapped_u8("at-least", "at-most", "exactly")
filters.append({
"index": f + 1,
"name": item_name,
"count": item_count,
"mode": mode
})
if filters:
entity["infinity_settings"]["filters"] = filters
remove_unfiltered_items = stream.bool()
entity["infinity_settings"]["remove_unfiltered_items"] = remove_unfiltered_items
def eh_storage_tank(stream, index, entity):
ep_v1_1_51_4_flag(stream, index, entity, 0x00)
ep_direction(stream, index, entity)
# circuit network connections
has_circuit_connections = stream.bool()
if has_circuit_connections:
# connections
ep_circuit_connections(stream, index, entity)
def eh_transport_belt(stream, index, entity):
ep_v1_1_51_4_flag(stream, index, entity, 0x00)
ep_direction(stream, index, entity)
# circuit network connections
has_circuit_connections = stream.bool()
if has_circuit_connections:
# connections
ep_circuit_connections(stream, index, entity)
# circuit condition & logistic condition
ep_circuit_condition(stream, index, entity)
ep_logistic_condition(stream, index, entity)
stream.expect(0x00, 0x00)
# mode of operation (specific for transport-belt)
# maybe helpfull: https://lua-api.factorio.com/latest/defines.html#defines.control_behavior
control_behavior = entity.setdefault("control_behavior", {})
circuit_enable_disable = stream.bool()
control_behavior["circuit_enable_disable"] = circuit_enable_disable
circuit_read_hand_contents = stream.bool()
control_behavior["circuit_read_hand_contents"] = circuit_read_hand_contents
circuit_contents_read_mode = stream.u8()
control_behavior["circuit_contents_read_mode"] = circuit_contents_read_mode
# really strange stuff
stream.expect(0xff, 0xff, 0xff, 0xff)
stream.expect(0xff, 0xff, 0xff, 0xff)
def eh_underground_belt(stream, index, entity):
ep_v1_1_51_4_flag(stream, index, entity, 0x00)
ep_direction(stream, index, entity)
type = stream.mapped_u8("input", "output")
entity["type"] = type
def eh_splitter(stream, index, entity):
ep_v1_1_51_4_flag(stream, index, entity, 0x00)
ep_direction(stream, index, entity)
priorities = stream.u8()
# "explanation": masks
# => 0x10 -> output prio enabled
# => 0x20 -> input priority enabled
# => 0x0c -> input priority left
# => 0x03 -> output priority left
# strange thing: why two bits for both 0x0c and 0x03?
priority_mapping = {
0x00 : [None, None],
0x10 : [None, "right"],
0x13 : [None, "left"],
0x20 : ["right", None],
0x2c : ["left", None],
0x30 : ["right", "right"],