-
Notifications
You must be signed in to change notification settings - Fork 40
/
control.lua
1402 lines (1261 loc) · 49.5 KB
/
control.lua
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
require("layout")
local HasLayout = HasLayout
require("connections")
local Connections = Connections
require("updates")
local Updates = Updates
require("compat.factoriomaps")
local mod_gui = require("mod-gui")
-- DATA STRUCTURE --
-- Factory buildings are entities of type "storage-tank" internally, because reasons
local BUILDING_TYPE = "storage-tank"
--[[
factory = {
+outside_surface = *,
+outside_x = *,
+outside_y = *,
+outside_door_x = *,
+outside_door_y = *,
+inside_surface = *,
+inside_x = *,
+inside_y = *,
+inside_door_x = *,
+inside_door_y = *,
+force = *,
+layout = *,
+building = *,
+outside_energy_sender = *,
+outside_energy_receiver = *,
+outside_overlay_displays = {*},
+outside_fluid_dummy_connectors = {*},
+outside_port_markers = {*},
(+)outside_other_entities = {*},
+inside_energy_sender = *,
+inside_energy_receiver = *,
+inside_overlay_controller = *,
+inside_fluid_dummy_connectors = {*},
(+)inside_other_entities = {*},
+energy_indicator = *,
+transfer_rate = *,
+transfers_outside = *,
+stored_pollution = *,
+connections = {*},
+connection_settings = {{*}*},
+connection_indicators = {*},
+upgrades = {},
}
]]--
-- INITIALIZATION --
local function init_globals()
-- List of all factories
global.factories = global.factories or {}
-- Map: Save name -> Factory it is currently saving
global.saved_factories = global.saved_factories or {}
-- Map: Player or robot -> Save name to give him on the next relevant event
global.pending_saves = global.pending_saves or {}
-- Map: Entity unit number -> Factory it is a part of
global.factories_by_entity = global.factories_by_entity or {}
-- Map: Surface name -> list of factories on it
global.surface_factories = global.surface_factories or {}
-- Map: Surface name -> number of used factory spots on it
global.surface_factory_counters = global.surface_factory_counters or {}
-- Scalar
global.next_factory_surface = global.next_factory_surface or 0
-- Map: Player index -> Last teleport time
global.last_player_teleport = global.last_player_teleport or {}
-- Map: Player index -> Whether preview is activated
global.player_preview_active = global.player_preview_active or {}
end
local prepare_gui = 0 -- Function stub
local update_hidden_techs = 0 -- Function stub
local function init_gui()
for _, player in pairs(game.players) do
prepare_gui(player)
end
end
script.on_init(function()
init_globals()
Connections.init_data_structure()
Updates.init()
init_gui()
for _, force in pairs(game.forces) do
update_hidden_techs(force)
end
Compat.handle_factoriomaps()
end)
script.on_load(function()
Compat.handle_factoriomaps()
end)
script.on_configuration_changed(function(config_changed_data)
init_globals()
Updates.run()
init_gui()
for surface_name, _ in pairs(global.surface_factories or {}) do
if remote.interfaces["RSO"] then -- RSO compatibility
pcall(remote.call, "RSO", "ignoreSurface", surface_name)
end
end
end)
-- DATA MANAGEMENT --
local function set_entity_to_factory(entity, factory)
global.factories_by_entity[entity.unit_number] = factory
end
local function get_factory_by_entity(entity)
if entity == nil then return nil end
return global.factories_by_entity[entity.unit_number]
end
local function get_factory_by_building(entity)
local factory = global.factories_by_entity[entity.unit_number]
if factory == nil then
game.print("ERROR: Unbound factory building: " .. entity.name .. "@" .. entity.surface.name .. "(" .. entity.position.x .. ", " .. entity.position.y .. ")")
end
return factory
end
local function find_factory_by_building(surface, area)
local candidates = surface.find_entities_filtered{area=area, type=BUILDING_TYPE}
for _,entity in pairs(candidates) do
if HasLayout(entity.name) then return get_factory_by_building(entity) end
end
return nil
end
local function find_surrounding_factory(surface, position)
local factories = global.surface_factories[surface.name]
if factories == nil then return nil end
local x = math.floor(0.5+position.x/(16*32))
local y = math.floor(0.5+position.y/(16*32))
if (x > 7 or x < 0) then return nil end
return factories[8*y+x+1]
end
-- POWER MANAGEMENT --
-- Don't mess with this unless you mess with prototypes/entity/component.lua too.
-- Every number needs to correspond to a valid indicator entity name
local VALID_POWER_TRANSFER_RATES = {1,2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000,100000} -- MW
local function make_valid_transfer_rate(rate)
for _,v in pairs(VALID_POWER_TRANSFER_RATES) do
if v == rate then return v end
end
return 0 -- Catchall
end
local function update_power_settings(factory)
if factory.built then
local layout = factory.layout
-- Inside sender
local new_ies = factory.inside_surface.create_entity{
name = "factory-power-output-2-" .. factory.transfer_rate,
position = {factory.inside_x + layout.inside_energy_x, factory.inside_y + layout.inside_energy_y},
force = factory.force
}
new_ies.destructible = false
new_ies.operable = false
new_ies.rotatable = false
if factory.inside_energy_sender.valid then
factory.inside_energy_sender.destroy()
end
factory.inside_energy_sender = new_ies
-- Inside receiver
local new_ier = factory.inside_surface.create_entity{
name = "factory-power-input-2-" .. factory.transfer_rate,
position = {factory.inside_x + layout.inside_energy_x, factory.inside_y + layout.inside_energy_y},
force = factory.force
}
new_ier.destructible = false
new_ier.operable = false
new_ier.rotatable = false
if factory.inside_energy_receiver.valid then
factory.inside_energy_receiver.destroy()
end
factory.inside_energy_receiver = new_ier
-- Outside sender
local new_oes = factory.outside_surface.create_entity{
name = layout.outside_energy_sender_type .. "-" .. factory.transfer_rate,
position = {factory.outside_x, factory.outside_y},
force = factory.force
}
new_oes.destructible = false
new_oes.operable = false
new_oes.rotatable = false
if factory.outside_energy_sender.valid then
factory.outside_energy_sender.destroy()
end
factory.outside_energy_sender = new_oes
-- Outside receiver
local new_oer = factory.outside_surface.create_entity{
name = layout.outside_energy_receiver_type .. "-" .. factory.transfer_rate,
position = {factory.outside_x, factory.outside_y},
force = factory.force
}
new_oer.destructible = false
new_oer.operable = false
new_oer.rotatable = false
if factory.outside_energy_receiver.valid then
factory.outside_energy_receiver.destroy()
end
factory.outside_energy_receiver = new_oer
local e = factory.transfer_rate*16667 -- conversion factor of MW to J/U
if factory.transfers_outside then
factory.inside_energy_sender.energy = 0--e
factory.inside_energy_receiver.energy = 0
factory.outside_energy_sender.energy = 0
factory.outside_energy_receiver.energy = 0--e
else
factory.inside_energy_sender.energy = 0
factory.inside_energy_receiver.energy = 0--e
factory.outside_energy_sender.energy = 0--e
factory.outside_energy_receiver.energy = 0
end
end
if factory.energy_indicator and factory.energy_indicator.valid then
factory.energy_indicator.destroy()
factory.energy_indicator = nil
end
local direction = (factory.transfers_outside and defines.direction.south) or defines.direction.north
local energy_indicator = factory.inside_surface.create_entity{
name = "factory-connection-indicator-energy-d" .. make_valid_transfer_rate(factory.transfer_rate),
direction = direction, force = factory.force,
position = {x = factory.inside_x + factory.layout.energy_indicator_x, y = factory.inside_y + factory.layout.energy_indicator_y}
}
energy_indicator.destructible = false
factory.energy_indicator = energy_indicator
end
-- For update 11
function update_all_power_settings()
for _, factory in pairs(global.factories) do
update_power_settings(factory)
end
end
local function adjust_power_transfer_rate(factory, positive)
local transfer_rate = factory.transfer_rate
if positive then
for i = 1,#VALID_POWER_TRANSFER_RATES do
if transfer_rate < VALID_POWER_TRANSFER_RATES[i] then
transfer_rate = VALID_POWER_TRANSFER_RATES[i]
break
end
end
if transfer_rate > VALID_POWER_TRANSFER_RATES[#VALID_POWER_TRANSFER_RATES] then
transfer_rate = VALID_POWER_TRANSFER_RATES[#VALID_POWER_TRANSFER_RATES]
end
else
for i = #VALID_POWER_TRANSFER_RATES,1,-1 do
if transfer_rate > VALID_POWER_TRANSFER_RATES[i] then
transfer_rate = VALID_POWER_TRANSFER_RATES[i]
break
end
end
if transfer_rate < VALID_POWER_TRANSFER_RATES[1] then
transfer_rate = VALID_POWER_TRANSFER_RATES[1]
end
end
factory.transfer_rate = transfer_rate
local power_string, transfer_text = "",""
if transfer_rate >= 1000 then
power_string = (transfer_rate / 1000) .. "GW"
else
power_string = transfer_rate .. "MW"
end
if positive then
transfer_text = "factory-connection-text.power-transfer-increased"
else
transfer_text = "factory-connection-text.power-transfer-decreased"
end
factory.inside_surface.create_entity{
name = "flying-text",
position = {x = factory.inside_x + factory.layout.energy_indicator_x, y = factory.inside_y + factory.layout.energy_indicator_y}, color = {r = 228/255, g = 236/255, b = 0},
text = {transfer_text, power_string},
force = factory.force
}
update_power_settings(factory)
end
-- FACTORY UPGRADES --
local function build_lights_upgrade(factory)
if factory.upgrades.lights then return end
factory.upgrades.lights = true
for _, pos in pairs(factory.layout.lights) do
local light = factory.inside_surface.create_entity{name = "factory-ceiling-light", position = {factory.inside_x + pos.x, factory.inside_y + pos.y}, force = factory.force}
light.destructible = false
light.operable = false
light.rotatable = false
table.insert(factory.inside_other_entities, light)
end
end
function build_display_upgrade(factory)
if not factory.force.technologies["factory-interior-upgrade-display"].researched then return end
if factory.inside_overlay_controller and factory.inside_overlay_controller.valid then return end
pos = factory.layout.overlays
local controller = factory.inside_surface.create_entity{
name = "factory-overlay-controller",
position = {
factory.inside_x + pos.inside_x,
factory.inside_y + pos.inside_y
},
force = factory.force
}
controller.minable = false
controller.destructible = false
controller.rotatable = false
factory.inside_overlay_controller = controller
end
-- OVERLAY MANAGEMENT --
local sprite_path_translation = {
item = "item",
fluid = "fluid",
virtual = "virtual-signal",
}
local function draw_overlay_sprite(signal, target_entity, offset, scale, id_table)
local sprite_name = sprite_path_translation[signal.type] .. "/" .. signal.name
if target_entity.valid then
local sprite_data = {
sprite = sprite_name,
x_scale = scale,
y_scale = scale,
target = target_entity,
surface = target_entity.surface,
only_in_alt_mode = true,
render_layer = "entity-info-icon",
}
-- Fake shadows
local shadow_radius = 0.07 * scale
for _, shadow_offset in pairs({{0,shadow_radius}, {0, -shadow_radius}, {shadow_radius, 0}, {-shadow_radius, 0}}) do
sprite_data.tint = {0, 0, 0, 0.5} -- Transparent black
sprite_data.target_offset = {offset[1] + shadow_offset[1], offset[2] + shadow_offset[2]}
table.insert(id_table, rendering.draw_sprite(sprite_data))
end
-- Proper sprite
sprite_data.tint = nil
sprite_data.target_offset = offset
table.insert(id_table, rendering.draw_sprite(sprite_data))
end
end
local function get_nice_overlay_arrangement(width, height, amount)
-- Computes a nice arrangement of square sprites within a rectangle of given size
-- Returned coordinates are relative to the center of the rectangle
if amount <= 0 then return {} end
local opt_rows = 1
local opt_cols = 1
local opt_scale = 0
-- Determine the optimal number of rows to use
-- This assumes width >= height
for rows = 1, math.ceil(math.sqrt(amount)) do
local cols = math.ceil(amount/rows)
local scale = math.min(width/cols, height/rows)
if scale > opt_scale then
opt_rows = rows
opt_cols = cols
opt_scale = scale
end
end
-- Adjust scale to ensure that sprites do not become too big
opt_scale = math.pow(opt_scale, 0.8) * math.pow(1.5, 0.8 - 1)
-- Create evenly spaced coordinates
local result = {}
for i = 0, amount-1 do
local col = i % opt_cols
local row = math.floor(i / opt_cols)
local cols_in_row = (row < opt_rows - 1 and opt_cols or (amount - 1) % opt_cols + 1)
table.insert(result, {
x = (2 * col + 1 - cols_in_row) * width / (2 * opt_cols),
y = (2 * row + 1 - opt_rows) * height / (2 * opt_rows),
scale = opt_scale
})
end
return result
end
function update_overlay(factory)
for _, id in pairs(factory.outside_overlay_displays) do
rendering.destroy(id)
end
factory.outside_overlay_displays = {}
if factory.built and factory.inside_overlay_controller and factory.inside_overlay_controller.valid then
local params = factory.inside_overlay_controller.get_or_create_control_behavior().parameters
local nonempty_params = {}
for _, param in pairs(params) do
if param and param.signal and param.signal.name then
table.insert(nonempty_params, param)
end
end
local sprite_positions = get_nice_overlay_arrangement(
factory.layout.overlays.outside_w,
factory.layout.overlays.outside_h,
#nonempty_params
)
local i = 0
for _, param in pairs(nonempty_params) do
i = i + 1
draw_overlay_sprite(param.signal, factory.building,
{
sprite_positions[i].x + factory.layout.overlays.outside_x,
sprite_positions[i].y + factory.layout.overlays.outside_y,
},
sprite_positions[i].scale,
factory.outside_overlay_displays)
end
end
end
-- FACTORY GENERATION --
local function update_destructible(factory)
if factory.built and factory.building.valid then
factory.building.destructible = not settings.global["Factorissimo2-indestructible-buildings"].value
end
end
local function create_factory_position()
global.next_factory_surface = global.next_factory_surface + 1
local max_surface_id = settings.global["Factorissimo2-max-surfaces"].value
if (max_surface_id > 0 and global.next_factory_surface > max_surface_id) then
global.next_factory_surface = 1
end
local surface_name = "Factory floor " .. global.next_factory_surface
local surface = game.surfaces[surface_name]
if surface == nil then
if #(game.surfaces) < 256 then
surface = game.create_surface(surface_name, {width = 2, height = 2})
surface.daytime = 0.5
surface.freeze_daytime = true
if remote.interfaces["RSO"] then -- RSO compatibility
pcall(remote.call, "RSO", "ignoreSurface", surface_name)
end
else
global.next_factory_surface = 1
surface_name = "Factory floor 1"
surface = game.surfaces[surface_name]
if surface == nil then
error("Unfortunately you have no available surfaces left for Factorissimo2. You cannot use Factorissimo2 on this map.")
end
end
end
local n = global.surface_factory_counters[surface_name] or 0
global.surface_factory_counters[surface_name] = n+1
local cx = 16*(n % 8)
local cy = 16*math.floor(n / 8)
-- To make void chunks show up on the map, you need to tell them they've finished generating.
surface.set_chunk_generated_status({cx-2, cy-2}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx-1, cy-2}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx+0, cy-2}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx+1, cy-2}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx-2, cy-1}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx-1, cy-1}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx+0, cy-1}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx+1, cy-1}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx-2, cy+0}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx-1, cy+0}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx+0, cy+0}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx+1, cy+0}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx-2, cy+1}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx-1, cy+1}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx+0, cy+1}, defines.chunk_generated_status.entities)
surface.set_chunk_generated_status({cx+1, cy+1}, defines.chunk_generated_status.entities)
surface.destroy_decoratives{area={{32*(cx-2),32*(cy-2)},{32*(cx+2),32*(cy+2)}}}
local factory = {}
factory.inside_surface = surface
factory.inside_x = 32*cx
factory.inside_y = 32*cy
factory.stored_pollution = 0
factory.upgrades = {}
global.surface_factories[surface_name] = global.surface_factories[surface_name] or {}
global.surface_factories[surface_name][n+1] = factory
local fn = #(global.factories)+1
global.factories[fn] = factory
factory.id = fn
return factory
end
local function add_tile_rect(tiles, tile_name, xmin, ymin, xmax, ymax) -- tiles is rw
local i = #tiles
for x = xmin, xmax-1 do
for y = ymin, ymax-1 do
i = i + 1
tiles[i] = {name = tile_name, position = {x, y}}
end
end
end
local function add_tile_mosaic(tiles, tile_name, xmin, ymin, xmax, ymax, pattern) -- tiles is rw
local i = #tiles
for x = 0, xmax-xmin-1 do
for y = 0, ymax-ymin-1 do
if (string.sub(pattern[y+1],x+1, x+1) == "+") then
i = i + 1
tiles[i] = {name = tile_name, position = {x+xmin, y+ymin}}
end
end
end
end
local function create_factory_interior(layout, force)
local factory = create_factory_position()
factory.layout = layout
factory.force = force
factory.inside_door_x = layout.inside_door_x + factory.inside_x
factory.inside_door_y = layout.inside_door_y + factory.inside_y
local tiles = {}
for _, rect in pairs(layout.rectangles) do
add_tile_rect(tiles, rect.tile, rect.x1 + factory.inside_x, rect.y1 + factory.inside_y, rect.x2 + factory.inside_x, rect.y2 + factory.inside_y)
end
for _, mosaic in pairs(layout.mosaics) do
add_tile_mosaic(tiles, mosaic.tile, mosaic.x1 + factory.inside_x, mosaic.y1 + factory.inside_y, mosaic.x2 + factory.inside_x, mosaic.y2 + factory.inside_y, mosaic.pattern)
end
for _, cpos in pairs(layout.connections) do
table.insert(tiles, {name = layout.connection_tile, position = {factory.inside_x + cpos.inside_x, factory.inside_y + cpos.inside_y}})
end
factory.inside_surface.set_tiles(tiles)
local ier = factory.inside_surface.create_entity{name = "factory-power-input-2-10", position = {factory.inside_x + layout.inside_energy_x, factory.inside_y + layout.inside_energy_y}, force = force}
ier.destructible = false
ier.operable = false
ier.rotatable = false
factory.inside_energy_receiver = ier
local ies = factory.inside_surface.create_entity{name = "factory-power-output-2-10", position = {factory.inside_x + layout.inside_energy_x, factory.inside_y + layout.inside_energy_y}, force = force}
ies.destructible = false
ies.operable = false
ies.rotatable = false
factory.inside_energy_sender = ies
local iet = factory.inside_surface.create_entity{name = "factory-power-pole", position = {factory.inside_x + layout.inside_energy_x, factory.inside_y + layout.inside_energy_y}, force = force}
iet.destructible = false
factory.inside_other_entities = {iet}
--if force.technologies["factory-interior-upgrade-power"].researched then
-- build_power_upgrade(factory)
--end
if force.technologies["factory-interior-upgrade-lights"].researched then
build_lights_upgrade(factory)
end
factory.inside_overlay_controllers = {}
if force.technologies["factory-interior-upgrade-display"].researched then
build_display_upgrade(factory)
end
factory.inside_fluid_dummy_connectors = {}
for id, cpos in pairs(layout.connections) do
local name = "factory-fluid-dummy-connector-" .. cpos.direction_in
local connector = factory.inside_surface.create_entity{name = name, position = {factory.inside_x + cpos.inside_x + cpos.indicator_dx, factory.inside_y + cpos.inside_y + cpos.indicator_dy}, force = force}
connector.destructible = false
connector.operable = false
connector.rotatable = false
factory.inside_fluid_dummy_connectors[id] = connector
end
factory.transfer_rate = factory.layout.default_power_transfer_rate or 10 -- MW
factory.transfers_outside = false
factory.connections = {}
factory.connection_settings = {}
factory.connection_indicators = {}
return factory
end
local function create_factory_exterior(factory, building)
local layout = factory.layout
local force = factory.force
factory.outside_x = building.position.x
factory.outside_y = building.position.y
factory.outside_door_x = factory.outside_x + layout.outside_door_x
factory.outside_door_y = factory.outside_y + layout.outside_door_y
factory.outside_surface = building.surface
local oer = factory.outside_surface.create_entity{name = layout.outside_energy_receiver_type .. "-10", position = {factory.outside_x, factory.outside_y}, force = force}
oer.destructible = false
oer.operable = false
oer.rotatable = false
factory.outside_energy_receiver = oer
local oes = factory.outside_surface.create_entity{name = layout.outside_energy_sender_type .. "-10", position = {factory.outside_x, factory.outside_y}, force = force}
oes.destructible = false
oes.operable = false
oes.rotatable = false
factory.outside_energy_sender = oes
factory.outside_overlay_displays = {}
factory.outside_fluid_dummy_connectors = {}
for id, cpos in pairs(layout.connections) do
local name = "factory-fluid-dummy-connector-" .. cpos.direction_out
local connector = factory.outside_surface.create_entity{name = name, position = {factory.outside_x + cpos.outside_x - cpos.indicator_dx, factory.outside_y + cpos.outside_y - cpos.indicator_dy}, force = force}
connector.destructible = false
connector.operable = false
connector.rotatable = false
factory.outside_fluid_dummy_connectors[id] = connector
end
local overlay = factory.outside_surface.create_entity{name = factory.layout.overlay_name, position = {factory.outside_x + factory.layout.overlay_x, factory.outside_y + factory.layout.overlay_y}, force = force}
overlay.destructible = false
overlay.operable = false
overlay.rotatable = false
factory.outside_other_entities = {overlay}
factory.outside_port_markers = {}
set_entity_to_factory(building, factory)
factory.building = building
factory.built = true
update_power_settings(factory)
Connections.recheck_factory(factory, nil, nil)
update_overlay(factory)
update_destructible(factory)
return factory
end
local function toggle_port_markers(factory)
if not factory.built then return end
if #(factory.outside_port_markers) == 0 then
for id, cpos in pairs(factory.layout.connections) do
local sprite_data = {
sprite = "utility/indication_arrow",
orientation = cpos.direction_out/8,
target = factory.building,
surface = factory.building.surface,
target_offset = {cpos.outside_x - 0.5 * cpos.indicator_dx, cpos.outside_y - 0.5 * cpos.indicator_dy},
only_in_alt_mode = true,
render_layer = "entity-info-icon",
}
table.insert(factory.outside_port_markers, rendering.draw_sprite(sprite_data))
end
else
for _, sprite in pairs(factory.outside_port_markers) do rendering.destroy(sprite) end
factory.outside_port_markers = {}
end
end
local function cleanup_factory_exterior(factory, building)
Connections.disconnect_factory(factory)
factory.outside_energy_sender.destroy()
factory.outside_energy_receiver.destroy()
for _, render_id in pairs(factory.outside_overlay_displays) do rendering.destroy(render_id) end
factory.outside_overlay_displays = {}
for _, entity in pairs(factory.outside_fluid_dummy_connectors) do entity.destroy() end
factory.outside_fluid_dummy_connectors = {}
for _, render_id in pairs(factory.outside_port_markers) do rendering.destroy(render_id) end
factory.outside_port_markers = {}
for _, entity in pairs(factory.outside_other_entities) do entity.destroy() end
factory.outside_other_entities = {}
factory.building = nil
factory.built = false
end
-- FACTORY SAVING AND LOADING --
local SAVE_NAMES = {} -- Set of all valid factory save names
local SAVE_ITEMS = {}
for _,f in ipairs({"factory-1", "factory-2", "factory-3"}) do
SAVE_ITEMS[f] = {}
for n = 10,99 do
SAVE_NAMES[f .. "-s" .. n] = true
SAVE_ITEMS[f][n] = f .. "-s" .. n
end
end
local function save_factory(factory)
for _,sf in pairs(SAVE_ITEMS[factory.layout.name] or {}) do
if global.saved_factories[sf] then
else
global.saved_factories[sf] = factory
return sf
end
end
--game.print("Could not save factory!")
return nil
end
local function is_invalid_save_slot(name)
return SAVE_NAMES[name] and not global.saved_factories[name]
end
local function init_factory_requester_chest(entity)
local saved_factories = global.saved_factories
local i = 0
for sf,_ in pairs(saved_factories) do
i = i+1
entity.set_request_slot({name=sf,count=1},i)
end
for j=i+1,entity.request_slot_count do
entity.clear_request_slot(j)
end
end
commands.add_command("give-lost-factory-buildings", {"command-help-message.give-lost-factory-buildings"}, function(event)
--game.print(serpent.line(event))
local player = game.players[event.player_index]
if not (player and player.connected and player.admin) then return end
if event.parameter == "destroyed" then
for _,factory in pairs(global.factories) do
local saved_or_built = factory.built
for _,saved_factory in pairs(global.saved_factories) do
if saved_factory.id == factory.id then
saved_or_built = true
break
end
end
if not saved_or_built then
save_factory(factory)
end
end
end
local main_inventory =
player.get_inventory(defines.inventory.player_main or defines.inventory.character_main)
or player.get_inventory(defines.inventory.god_main)
for save_name,_ in pairs(global.saved_factories) do
if main_inventory.get_item_count(save_name) == 0 and not (player.cursor_stack and player.cursor_stack.valid_for_read and player.cursor_stack.name == save_name) then
player.insert{name = save_name, count = 1}
end
end
end)
-- FACTORY PLACEMENT AND DESTRUCTION --
local function can_place_factory_here(tier, surface, position)
local factory = find_surrounding_factory(surface, position)
if not factory then return true end
local outer_tier = factory.layout.tier
if outer_tier > tier and (factory.force.technologies["factory-recursion-t1"].researched or settings.global["Factorissimo2-free-recursion"].value) then return true end
if (outer_tier >= tier or settings.global["Factorissimo2-better-recursion-2"].value)
and (factory.force.technologies["factory-recursion-t2"].researched or settings.global["Factorissimo2-free-recursion"].value) then return true end
if outer_tier > tier then
surface.create_entity{name="flying-text", position=position, text={"factory-connection-text.invalid-placement-recursion-1"}, force = factory.force}
elseif (outer_tier >= tier or settings.global["Factorissimo2-better-recursion-2"].value) then
surface.create_entity{name="flying-text", position=position, text={"factory-connection-text.invalid-placement-recursion-2"}, force = factory.force}
else
surface.create_entity{name="flying-text", position=position, text={"factory-connection-text.invalid-placement"}, force = factory.force}
end
return false
end
local function recheck_nearby_connections(entity, delayed)
local surface = entity.surface
-- Find nearby factory buildings
local bbox = entity.bounding_box
-- Expand box by one tile to catch factories and also avoid illegal zero-area finds
local bbox2 = {
left_top = {x = bbox.left_top.x - 1.5, y = bbox.left_top.y - 1.5},
right_bottom = {x = bbox.right_bottom.x + 1.5, y = bbox.right_bottom.y + 1.5}
}
local building_candidates = surface.find_entities_filtered{area = bbox2, type = BUILDING_TYPE}
for _,candidate in pairs(building_candidates) do
if candidate ~= entity and HasLayout(candidate.name) then
local factory = get_factory_by_building(candidate)
if factory then
if delayed then
Connections.recheck_factory_delayed(factory, bbox2, nil)
else
Connections.recheck_factory(factory, bbox2, nil)
end
end
end
end
local surrounding_factory = find_surrounding_factory(surface, entity.position)
if surrounding_factory then
if delayed then
Connections.recheck_factory_delayed(surrounding_factory, nil, bbox2)
else
Connections.recheck_factory(surrounding_factory, nil, bbox2)
end
end
end
script.on_event({defines.events.on_built_entity, defines.events.on_robot_built_entity, defines.events.script_raised_built, defines.events.script_raised_revive}, function(event)
local entity = event.created_entity or event.entity
--if BUILDING_TYPE ~= entity.type then return nil end
if HasLayout(entity.name) then
-- This is a fresh factory, we need to create it
local layout = CreateLayout(entity.name)
if can_place_factory_here(layout.tier, entity.surface, entity.position) then
local factory = create_factory_interior(layout, entity.force)
create_factory_exterior(factory, entity)
else
entity.surface.create_entity{name=entity.name .. "-i", position=entity.position, force=entity.force}
entity.destroy()
end
elseif global.saved_factories[entity.name] then
-- This is a saved factory, we need to unpack it
local factory = global.saved_factories[entity.name]
if can_place_factory_here(factory.layout.tier, entity.surface, entity.position) then
global.saved_factories[entity.name] = nil
local newbuilding = entity.surface.create_entity{name=factory.layout.name, position=entity.position, force=factory.force}
newbuilding.last_user = entity.last_user
create_factory_exterior(factory, newbuilding)
entity.destroy()
end
elseif is_invalid_save_slot(entity.name) then
entity.surface.create_entity{name="flying-text", position=entity.position, text={"factory-connection-text.invalid-factory-data"}}
entity.destroy()
else
if Connections.is_connectable(entity) then
recheck_nearby_connections(entity)
end
if entity.name == "factory-requester-chest" then
init_factory_requester_chest(entity)
end
end
end)
-- How players pick up factories
-- Working factory buildings don't return items, so we have to manually give the player an item
script.on_event(defines.events.on_pre_player_mined_item, function(event)
local entity = event.entity
if HasLayout(entity.name) then
local factory = get_factory_by_building(entity)
if factory then
local save = save_factory(factory)
if save then
cleanup_factory_exterior(factory, entity)
local player = game.players[event.player_index]
if player.insert{name = save, count = 1} < 1 then
player.print{"inventory-restriction.player-inventory-full", {"entity-name."..save}}
player.surface.spill_item_stack(player.position, {name = save, count = 1})
end
else
local newbuilding = entity.surface.create_entity{name=entity.name, position=entity.position, force=factory.force}
newbuilding.last_user = entity.last_user
entity.destroy()
set_entity_to_factory(newbuilding, factory)
factory.building = newbuilding
game.players[event.player_index].print("Could not pick up factory, too many factories picked up at once")
end
end
elseif Connections.is_connectable(entity) then
recheck_nearby_connections(entity, true) -- Delay
end
end)
-- How robots pick up factories
-- Since you can't insert items into construction robots, we'll have to swap out factories for fake placeholder factories
-- as soon as they are marked for deconstruction, and swap them back should they be unmarked.
script.on_event(defines.events.on_marked_for_deconstruction, function(event)
local entity = event.entity
if HasLayout(entity.name) then
local factory = get_factory_by_building(entity)
if factory then
local save = save_factory(factory)
if save then
-- Replace by placeholder
cleanup_factory_exterior(factory, entity)
local placeholder = entity.surface.create_entity{name=save, position=entity.position, force=factory.force}
placeholder.order_deconstruction(factory.force)
entity.destroy()
else
-- Not saved, so put it back
-- Don't cancel deconstruction (it'd cause another event), instead simply replace with new building
local newbuilding = entity.surface.create_entity{name=entity.name, position=entity.position, force=factory.force}
entity.destroy()
set_entity_to_factory(newbuilding, factory)
factory.building = newbuilding
newbuilding.surface.print("Could not pick up factory, too many factories picked up at once. Place some down before you pick up more.")
end
end
end
end)
-- Factories also need to start working again once they are unmarked
script.on_event(defines.events.on_cancelled_deconstruction, function(event)
local entity = event.entity
if global.saved_factories[entity.name] then
-- Rebuild factory from save
local factory = global.saved_factories[entity.name]
if can_place_factory_here(factory.layout.tier, entity.surface, entity.position) then
global.saved_factories[entity.name] = nil
local newbuilding = entity.surface.create_entity{name=factory.layout.name, position=entity.position, force=factory.force}
create_factory_exterior(factory, newbuilding)
entity.destroy()
end
end
end)
-- We need to check when a robot mines a piece of a connection
script.on_event(defines.events.on_robot_pre_mined, function(event)
local entity = event.entity
if Connections.is_connectable(entity) then
recheck_nearby_connections(entity, true) -- Delay
end
end)
script.on_event(defines.events.on_robot_mined, function(event)
local item = event.item
end)
-- How biters pick up factories
-- Too bad they don't have hands
script.on_event({defines.events.on_entity_died, defines.events.script_raised_destroy}, function(event)
local entity = event.entity
if HasLayout(entity.name) then
local factory = get_factory_by_building(entity)
if factory then
cleanup_factory_exterior(factory, entity)
-- Don't save it. It will be inaccessible from now on.
--save_factory(factory)
end
elseif Connections.is_connectable(entity) then
recheck_nearby_connections(entity, true) -- Delay
end
end)
-- How to clone your factory
-- This implementation will not actually clone factory buildings, but move them to where they were cloned.
local clone_forbidden_prefixes = {
"factory-1-",
"factory-2-",
"factory-3-",
"factory-power-input-",
"factory-power-output-",
"factory-connection-indicator-",
"factory-power-pole",
"factory-ceiling-light",
"factory-overlay-controller",
"factory-overlay-display",
"factory-port-marker",
"factory-fluid-dummy-connector"
}
local function is_entity_clone_forbidden(name)
for _, prefix in pairs(clone_forbidden_prefixes) do
if name:sub(1, #prefix) == prefix then
return true
end
end
return false
end
script.on_event(defines.events.on_entity_cloned, function(event)
local src_entity = event.source
local dst_entity = event.destination
if is_entity_clone_forbidden(dst_entity.name) then
dst_entity.destroy()
elseif HasLayout(src_entity.name) then
local factory = get_factory_by_building(src_entity)
cleanup_factory_exterior(factory, src_entity)
if src_entity.valid then src_entity.destroy() end
create_factory_exterior(factory, dst_entity)
end
end)
-- GUI --
local function get_camera_toggle_button(player)
local buttonflow = mod_gui.get_button_flow(player)
local button = buttonflow.factory_camera_toggle_button or buttonflow.add{type="sprite-button", name="factory_camera_toggle_button", sprite="technology/factory-architecture-t1"}
button.visible = player.force.technologies["factory-preview"].researched
return button
end
local function get_camera_frame(player)
local frameflow = mod_gui.get_frame_flow(player)