forked from Crimso777/Factorio-Access
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcontrol.lua
More file actions
4183 lines (3729 loc) · 141 KB
/
control.lua
File metadata and controls
4183 lines (3729 loc) · 141 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
require("syntrax")
--Main file for mod runtime
local Logging = require("scripts.logging")
Logging.init()
-- Set logging level
--Logging.set_level("DEBUG")
-- Create logger for control.lua
local logger = Logging.Logger("control")
local util = require("util")
local AreaOperations = require("scripts.area-operations")
local AudioCues = require("scripts.audio-cues")
local Blueprints = require("scripts.blueprints")
local BuildingTools = require("scripts.building-tools")
local BuildDimensions = require("scripts.build-dimensions")
local BuildLock = require("scripts.build-lock")
-- Register build lock backends (tiles must be first to catch tile items before simple backend)
BuildLock.register_backend(require("scripts.build-lock-backends.tiles"))
BuildLock.register_backend(require("scripts.build-lock-backends.transport-belts"))
BuildLock.register_backend(require("scripts.build-lock-backends.electric-poles"))
BuildLock.register_backend(require("scripts.build-lock-backends.simple"))
local BumpDetection = require("scripts.bump-detection")
local CircuitNetworks = require("scripts.circuit-network")
local Combat = require("scripts.combat")
local Consts = require("scripts.consts")
local SettingDecls = require("scripts.settings-decls")
local SETTING_NAMES = SettingDecls.SETTING_NAMES
local Crafting = require("scripts.crafting")
local CursorChanges = require("scripts.cursor-changes")
local Driving = require("scripts.driving")
local HandMonitor = require("scripts.hand-monitor")
local Electrical = require("scripts.electrical")
local EntitySelection = require("scripts.entity-selection")
local Equipment = require("scripts.equipment")
local EventManager = require("scripts.event-manager")
local FaCommands = require("scripts.fa-commands")
local FaInfo = require("scripts.fa-info")
local FaUtils = require("scripts.fa-utils")
local F = require("scripts.field-ref")
local Filters = require("scripts.filters")
local Graphics = require("scripts.graphics")
local InventoryTransfers = require("scripts.inventory-transfers")
local InventoryUtils = require("scripts.inventory-utils")
local ItemInfo = require("scripts.item-info")
local KruiseKontrol = require("scripts.kruise-kontrol-wrapper")
local Localising = require("scripts.localising")
local NoHover = require("scripts.no-hover")
local Speech = require("scripts.speech")
local MessageBuilder = Speech.MessageBuilder
local Mouse = require("scripts.mouse")
local MovementHistory = require("scripts.movement-history")
local PlayerInit = require("scripts.player-init")
local PlayerMiningTools = require("scripts.player-mining-tools")
local Quickbar = require("scripts.quickbar")
local Research = require("scripts.research")
require("scripts.rich-text") -- registers rich text processor with speech.lua
local Rulers = require("scripts.rulers")
local ScannerEntrypoint = require("scripts.scanner.entrypoint")
local Spidertron = require("scripts.spidertron")
local SpidertronRemote = require("scripts.spidertron-remote")
local TH = require("scripts.table-helpers")
local Teleport = require("scripts.teleport")
local TestFramework = require("scripts.test-framework")
local TileReader = require("scripts.tile-reader")
local TransportBelts = require("scripts.transport-belts")
local TravelTools = require("scripts.travel-tools")
local UpgradePlanner = require("scripts.upgrade-planner")
local PlannerUtils = require("scripts.planner-utils")
local VanillaMode = require("scripts.vanilla-mode")
local VirtualTrainDriving = require("scripts.rails.virtual-train-driving")
local SonifierTickHandler = require("scripts.sonifiers.tick-handler")
local GridSonifier = require("scripts.sonifiers.grid-sonifier")
local CraftingBackend = require("scripts.sonifiers.grid-backends.crafting")
local BattleNotice = require("scripts.sonifiers.battle-notice")
local ForceGhostEnabler = require("scripts.force-ghost-enabler")
local AimAssist = require("scripts.combat.aim-assist")
local Capsules = require("scripts.combat.capsules")
local PlayerWeapon = require("scripts.combat.player-weapon")
local Zoom = require("scripts.zoom")
-- UI modules (required for registration with router)
require("scripts.ui.belt-analyzer")
local EntityUI = require("scripts.ui.entity-ui")
require("scripts.ui.menus.blueprints-menu")
require("scripts.ui.menus.blueprint-book-menu")
require("scripts.ui.selectors.decon-selector")
require("scripts.ui.selectors.upgrade-selector")
require("scripts.ui.selectors.blueprint-selector")
require("scripts.ui.menus.blueprint-setup")
require("scripts.ui.menus.blueprint-setup-config")
require("scripts.ui.planners.upgrade-planner-menu")
require("scripts.ui.planners.decon-planner-menu")
require("scripts.ui.tabs.tile-chooser")
require("scripts.ui.selectors.copy-paste-selector")
require("scripts.ui.menus.gun-menu")
local MainMenu = require("scripts.ui.menus.main-menu")
local WorldMenu = require("scripts.ui.menus.world-menu")
require("scripts.ui.menus.fast-travel-menu")
require("scripts.ui.menus.debug-menu")
require("scripts.ui.menus.settings-menu")
require("scripts.ui.menus.rail-builder")
require("scripts.ui.menus.syntrax-program")
local SpidertronRemoteSelector = require("scripts.ui.menus.spidertron-remote-selector")
require("scripts.ui.tabs.item-chooser")
require("scripts.ui.tabs.signal-chooser")
require("scripts.ui.tabs.fluid-chooser")
require("scripts.ui.tabs.entity-chooser")
require("scripts.ui.tabs.prototype-lister")
require("scripts.ui.tabs.equipment-selector")
local Help = require("scripts.ui.help")
local MessageLists = require("scripts.message-lists")
require("scripts.ui.logistics-config")
require("scripts.ui.selectors.logistic-group-selector")
require("scripts.ui.selectors.train-group-selector")
require("scripts.ui.selectors.interrupt-selector")
require("scripts.ui.selectors.stop-selector")
require("scripts.ui.constant-combinator")
require("scripts.ui.decider-combinator")
require("scripts.ui.power-switch")
require("scripts.ui.schedule-editor")
require("scripts.ui.programmable-speaker")
require("scripts.ui.circuit-navigator")
require("scripts.ui.selectors.spidertron-autopilot-selector")
require("scripts.ui.selectors.spidertron-follow-selector")
require("scripts.ui.menus.offshore-pump-placement")
require("scripts.ui.menus.warnings")
require("scripts.ui.generic-inventory")
require("scripts.ui.simple-textbox")
require("scripts.ui.internal.search-setter")
require("scripts.ui.internal.cursor-coordinate-input")
require("scripts.ui.internal.syntrax-input")
require("scripts.ui.help")
require("scripts.ui.menus.tutorial")
local GameGui = require("scripts.ui.game-gui")
local UiRouter = require("scripts.ui.router")
local VehicleCycler = require("scripts.vehicle-cycler")
local Viewpoint = require("scripts.viewpoint")
local Wires = require("scripts.wires")
local Walking = require("scripts.walking")
local Warnings = require("scripts.warnings")
local WorkQueue = require("scripts.work-queue")
local WorkerRobots = require("scripts.worker-robots")
local sounds = require("scripts.ui.sounds")
---@meta scripts.shared-types
-- Register grid sonifier backends
GridSonifier.register_backend_factory("crafting", CraftingBackend.new, CraftingBackend.ENTITY_TYPES)
entity_types = {}
production_types = {}
building_types = {}
local dirs = defines.direction
---Check if in combat mode and speak feedback if so
---@param pindex integer
---@return boolean true if in combat mode (caller should return early)
local function skip_in_combat_mode(pindex)
if Combat.is_combat_mode(pindex) then
Speech.speak(pindex, { "fa.not-available-in-combat-mode" })
return true
end
return false
end
-- Initialize players as a deny-access table to catch any direct usage
players = TH.deny_access_table()
--Reads the item in hand, its facing direction if applicable, its count, and its total count including units in the main inventory.
---@param pindex number
local function read_hand(pindex)
if storage.players[pindex].skip_read_hand == true then
storage.players[pindex].skip_read_hand = false
return
end
local cursor_stack = game.get_player(pindex).cursor_stack
local cursor_ghost = game.get_player(pindex).cursor_ghost
if cursor_stack and cursor_stack.valid_for_read then
if cursor_stack.is_blueprint then
--Blueprint extra info
Speech.speak(pindex, Blueprints.get_blueprint_info(cursor_stack, true, pindex))
elseif cursor_stack.is_blueprint_book then
Speech.speak(pindex, Blueprints.get_blueprint_book_info(cursor_stack, true))
elseif cursor_stack.is_upgrade_item then
local message = MessageBuilder.new()
UpgradePlanner.describe_planner(message, cursor_stack)
Speech.speak(pindex, message:build())
elseif cursor_stack.is_deconstruction_item then
local label = cursor_stack.label
if label and label ~= "" then
Speech.speak(pindex, { "fa.item-decon-planner-labeled", label })
else
Speech.speak(pindex, { "item-name.deconstruction-planner" })
end
else
--Any other valid item
local vp = Viewpoint.get_viewpoint(pindex)
local out = { "fa.cursor-description" }
table.insert(out, cursor_stack.prototype.localised_name)
local build_entity = cursor_stack.prototype.place_result
if build_entity and build_entity.supports_direction then
table.insert(out, 1)
table.insert(out, { "fa.facing-direction", FaUtils.direction_lookup(vp:get_hand_direction()) })
else
table.insert(out, 0)
table.insert(out, "")
end
table.insert(out, cursor_stack.count)
local extra = game.get_player(pindex).get_main_inventory().get_item_count(cursor_stack.name)
if extra > 0 then
table.insert(out, cursor_stack.count + extra)
else
table.insert(out, 0)
end
Speech.speak(pindex, out)
end
elseif cursor_ghost ~= nil then
--Any ghost
local vp = Viewpoint.get_viewpoint(pindex)
local out = { "fa.cursor-description" }
table.insert(out, cursor_ghost.localised_name)
local build_entity = cursor_ghost.place_result
if build_entity and build_entity.supports_direction then
table.insert(out, 1)
table.insert(out, { "fa.facing-direction", FaUtils.direction_lookup(vp:get_hand_direction()) })
else
table.insert(out, 0)
table.insert(out, "")
end
table.insert(out, 0)
local extra = 0
if extra > 0 then
table.insert(out, cursor_stack.count + extra)
else
table.insert(out, 0)
end
Speech.speak(pindex, out)
else
Speech.speak(pindex, { "fa.empty_cursor" })
end
end
--Checks if the storage players table has been created, and if the table entry for this player exists. Otherwise it is initialized.
function check_for_player(index)
if storage.players[index] == nil then
local player = game.get_player(index)
if player then PlayerInit.initialize(player) end
return false
else
return true
end
end
---Local helper: Reads tile info and adds build preview info if player is holding a building
---@param pindex integer Player index
---@param start_text LocalisedString? Optional text to prepend to the result
local function read_tile_with_preview_info(pindex, start_text)
local message = MessageBuilder.new()
if start_text then message:fragment(start_text) end
TileReader.read_tile_inner(pindex, message)
-- Add build preview info if holding a building and tile is empty/has resources
local ent = EntitySelection.get_first_ent_at_tile(pindex)
if not ent or ent.type == "resource" then
local stack = game.get_player(pindex).cursor_stack
if stack and stack.valid_for_read and stack.valid and stack.prototype.place_result ~= nil then
message:fragment(BuildingTools.build_preview_checks_info(stack, pindex))
end
end
Speech.speak(pindex, message:build())
end
--Update the position info and cursor info during smooth walking.
EventManager.on_event(
defines.events.on_player_changed_position,
---@param event EventData.on_player_changed_position
---@param pindex integer
function(event, pindex)
local p = game.get_player(pindex)
-- Check for teleportation (large position jump)
local reader = MovementHistory.get_movement_history_reader(pindex)
local prev_entry = reader:get(0)
local old_pos = prev_entry and prev_entry.position
if old_pos and util.distance(old_pos, p.position) > 10 then
MovementHistory.reset_and_increment_generation(pindex)
end
--Update cursor graphics
local stack = p.cursor_stack
if stack and stack.valid_for_read and stack.valid then Graphics.sync_build_cursor_graphics(pindex) end
end
)
--Handles a player joining into a game session.
function on_player_join(pindex)
local playerList = {}
for _, p in pairs(game.connected_players) do
playerList["_" .. p.index] = p.name
end
--Reset the player building direction to match the vanilla behavior (Factorio 2.0)
local vp = Viewpoint.get_viewpoint(pindex)
vp:set_hand_direction(dirs.north)
end
EventManager.on_event(
defines.events.on_player_joined_game,
---@param event EventData.on_player_joined_game
function(event)
if game.is_multiplayer() then on_player_join(event.player_index) end
end
)
--Called for every player on every tick, to manage automatic walking and enforcing mouse pointer position syncs.
--Todo: create a new function for all mouse pointer related updates within this function
local function move_characters(event)
for pindex, player in pairs(storage.players) do
local router = UiRouter.get_router(pindex)
local vp = Viewpoint.get_viewpoint(pindex)
local cursor_pos = vp:get_cursor_pos()
if VanillaMode.is_enabled(pindex) then
player.player.game_view_settings.update_entity_selection = true
elseif player.player.game_view_settings.update_entity_selection == false then
--Force the mouse pointer to the mod cursor if there is an item in hand
--(so that the game does not make a mess when you left click while the cursor is actually locked)
local stack = game.get_player(pindex).cursor_stack
if stack and stack.valid_for_read then
if
stack.prototype.place_result ~= nil
or stack.prototype.place_as_tile_result ~= nil
or stack.is_blueprint
or stack.is_deconstruction_item
or stack.is_upgrade_item
or stack.prototype.type == "selection-tool"
or stack.prototype.type == "copy-paste-tool"
then
--Force the pointer to the build preview location (and draw selection tool boxes)
Graphics.sync_build_cursor_graphics(pindex)
else
--Force the pointer to the cursor location (if on screen)
Mouse.move_mouse_pointer(vp:get_cursor_pos(), pindex)
end
end
end
end
end
--Called every tick.
function on_tick(event)
MessageLists.try_translate_all_players()
NoHover.on_tick()
ScannerEntrypoint.on_tick()
MovementHistory.update_all_players()
Rulers.update_all_players()
SonifierTickHandler.on_tick()
BattleNotice.on_tick()
ForceGhostEnabler.on_tick()
move_characters(event)
-- Check alerts via AudioCues
AudioCues.check_cues(event.tick, players)
-- Check bump detection every tick for all players
for _, player in pairs(game.players) do
if not player.connected then goto continue end
if VanillaMode.is_enabled(player.index) then goto continue end
BumpDetection.check_and_play_bump_alert_sound(player.index, event.tick)
BumpDetection.check_and_play_stuck_alert_sound(player.index, event.tick)
-- Process build lock for walking movement
BuildLock.process_walking_movement(player.index)
-- Process walking announcements (anchored cursor or entity detection)
Walking.process_walking_announcements(player.index)
-- Check for pending logistics announcements
WorkerRobots.on_tick(player.index)
-- Handle shooting (combat mode aim assist or shooting_selected with safe mode)
Combat.on_tick(player.index)
::continue::
end
if event.tick % 15 == 0 then
for pindex, player in pairs(players) do
-- Other periodic checks can go here
end
elseif event.tick % 61 == 0 then
-- Refresh search cache periodically (coprime with other updates)
for pindex, player in pairs(players) do
if player.connected then UiRouter.on_inventory_changed(pindex) end
end
elseif event.tick % 90 == 13 then
for pindex, player in pairs(players) do
--Fix running speed bug (toggle walk also fixes it)
fix_walk(pindex)
end
elseif event.tick % 450 == 14 then
--Run regular reminders every 7.5 seconds
for pindex, player in pairs(players) do
if game.get_player(pindex).ticks_to_respawn ~= nil then
Speech.speak(
pindex,
{ "fa.respawn-countdown", tostring(math.floor(game.get_player(pindex).ticks_to_respawn / 60)) }
)
end
--Report the KK state, if any.
KruiseKontrol.status_read(pindex, false)
end
end
end
EventManager.on_event(
defines.events.on_tick,
---@param event EventData.on_tick
function(event)
on_tick(event)
WorkQueue.on_tick()
TestFramework.on_tick(event)
HandMonitor.on_tick()
end
)
--Makes the character face the cursor, choosing the nearest of 4 cardinal directions (north or south only).
function turn_to_cursor_direction_cardinal(pindex)
local p = game.get_player(pindex)
if not p.character then return end
local vp = Viewpoint.get_viewpoint(pindex)
local dir = FaUtils.get_direction_precise(vp:get_cursor_pos(), p.position)
if dir == dirs.northwest or dir == dirs.north or dir == dirs.northeast then
p.character.direction = dirs.north
elseif dir == dirs.southwest or dir == dirs.south or dir == dirs.southeast then
p.character.direction = dirs.south
end
end
--Called when a player enters or exits a vehicle
EventManager.on_event(
defines.events.on_player_driving_changed_state,
---@param event EventData.on_player_driving_changed_state
---@param pindex integer
function(event, pindex)
local router = UiRouter.get_router(pindex)
BumpDetection.reset_bump_stats(pindex)
MovementHistory.reset_and_increment_generation(pindex)
game.get_player(pindex).clear_cursor()
if game.get_player(pindex).driving then
storage.players[pindex].last_vehicle = game.get_player(pindex).vehicle
Speech.speak(
pindex,
{ "fa.vehicle-entered", Localising.get_localised_name_with_fallback(game.get_player(pindex).vehicle) }
)
elseif storage.players[pindex].last_vehicle ~= nil then
Speech.speak(
pindex,
{ "fa.vehicle-exited", Localising.get_localised_name_with_fallback(storage.players[pindex].last_vehicle) }
)
Teleport.teleport_to_closest(pindex, storage.players[pindex].last_vehicle.position, true, true)
else
Speech.speak(pindex, { "fa.driving-state-changed" })
end
end
)
--Called when a player changes surface
EventManager.on_event(
defines.events.on_player_changed_surface,
---@param event EventData.on_player_changed_surface
---@param pindex integer
function(event, pindex)
MovementHistory.reset_and_increment_generation(pindex)
end
)
--Save info about last item pickup and draw radius
EventManager.on_event(
defines.events.on_picked_up_item,
---@param event EventData.on_picked_up_item
---@param pindex integer
function(event, pindex)
local p = game.get_player(pindex)
--Draw the pickup range
rendering.draw_circle({
color = { 0.3, 1, 0.3 },
radius = 1.25,
width = 1,
target = p.position,
surface = p.surface,
time_to_live = 10,
draw_on_ground = true,
})
storage.players[pindex].last_pickup_tick = event.tick
storage.players[pindex].last_item_picked_up = event.item_stack.name
end
)
--Quickbar event handlers
local quickbar_get_events = {}
local quickbar_set_events = {}
local quickbar_page_events = {}
for i = 1, 10 do
local key = tostring(i % 10)
table.insert(quickbar_get_events, "fa-" .. key)
table.insert(quickbar_set_events, "fa-c-" .. key)
table.insert(quickbar_page_events, "fa-s-" .. key)
end
EventManager.on_event(quickbar_get_events, Quickbar.quickbar_get_handler)
EventManager.on_event(quickbar_set_events, Quickbar.quickbar_set_handler)
EventManager.on_event(quickbar_page_events, Quickbar.quickbar_page_handler)
function swap_weapon_forward(pindex, write_to_character)
local p = game.get_player(pindex)
if p.character == nil then
return 0 --This is an intentionally selected error code
end
local gun_index = p.character.selected_gun_index
if gun_index == nil then
return 0 --This is an intentionally selected error code
end
local guns_inv = p.character.get_inventory(defines.inventory.character_guns)
local ammo_inv = game.get_player(pindex).character.get_inventory(defines.inventory.character_ammo)
--Simple index increment (not needed)
gun_index = gun_index + 1
if gun_index > 3 then gun_index = 1 end
--game.print("start " .. gun_index)--
assert(ammo_inv)
--Increment again if the new index has no guns or no ammo
local ammo_stack = ammo_inv[gun_index]
local gun_stack = guns_inv[gun_index]
local tries = 0
while
tries < 4
and (
ammo_stack == nil
or not ammo_stack.valid_for_read
or not ammo_stack.valid
or gun_stack == nil
or not gun_stack.valid_for_read
or not gun_stack.valid
)
do
gun_index = gun_index + 1
if gun_index > 3 then gun_index = 1 end
ammo_stack = ammo_inv[gun_index]
gun_stack = guns_inv[gun_index]
tries = tries + 1
end
if tries > 3 then
--game.print("error " .. gun_index)--
return -1
end
if write_to_character then p.character.selected_gun_index = gun_index end
--game.print("end " .. gun_index)--
return gun_index
end
function swap_weapon_backward(pindex, write_to_character)
local p = game.get_player(pindex)
if p.character == nil then
return 0 --This is an intentionally selected error code
end
local gun_index = p.character.selected_gun_index
if gun_index == nil then
return 0 --This is an intentionally selected error code
end
local guns_inv = p.get_inventory(defines.inventory.character_guns)
local ammo_inv = game.get_player(pindex).get_inventory(defines.inventory.character_ammo)
--Simple index increment (not needed)
gun_index = gun_index - 1
if gun_index < 1 then gun_index = 3 end
--Increment again if the new index has no guns or no ammo
local ammo_stack = ammo_inv[gun_index]
local gun_stack = guns_inv[gun_index]
local tries = 0
while
tries < 4
and (
ammo_stack == nil
or not ammo_stack.valid_for_read
or not ammo_stack.valid
or gun_stack == nil
or not gun_stack.valid_for_read
or not gun_stack.valid
)
do
gun_index = gun_index - 1
if gun_index < 1 then gun_index = 3 end
ammo_stack = ammo_inv[gun_index]
gun_stack = guns_inv[gun_index]
tries = tries + 1
end
if tries > 3 then return -1 end
if write_to_character then p.character.selected_gun_index = gun_index end
return gun_index
end
function clicked_on_entity(ent, pindex)
local p = game.get_player(pindex)
if ent == nil then
--No entity clicked
p.selected = nil
return
elseif not ent.valid then
--Invalid entity clicked
p.print("Invalid entity clicked", { volume_modifier = 0 })
if p.opened ~= nil and p.opened.object_name == "LuaEntity" and p.opened.valid then
p.print("Opened " .. p.opened.name, { volume_modifier = 0 })
ent = p.opened
return
else
p.selected = nil
return
end
end
if p.character and p.character.unit_number == ent.unit_number then
--Self click
return
end
p.selected = ent
if EntityUI.maybe_open_entity(pindex, ent) then
-- UI opened successfully
elseif ent.operable then
if ent then Speech.speak(pindex, { "fa.no-menu-for", Localising.get_localised_name_with_fallback(ent) }) end
elseif ent.type == "resource" and ent.name ~= "crude-oil" and ent.name ~= "uranium-ore" then
if ent then
Speech.speak(pindex, { "fa.no-menu-for-mineable", Localising.get_localised_name_with_fallback(ent) })
end
else
if ent then Speech.speak(pindex, { "fa.no-menu-for", Localising.get_localised_name_with_fallback(ent) }) end
end
end
--[[Manages inventory transfers that are bigger than one stack.
* Has checks and speech output!
]]
--When the item in hand changes
EventManager.on_event(
defines.events.on_player_cursor_stack_changed,
---@param event EventData.on_player_cursor_stack_changed
---@param pindex integer
function(event, pindex)
-- Skip if suppressed (e.g., during rail building hand swaps)
if not HandMonitor.is_enabled(pindex) then return end
CursorChanges.on_cursor_stack_changed(event, pindex, read_hand)
VirtualTrainDriving.on_cursor_stack_changed(event)
-- Close UIs that are bound to hand contents
UiRouter.on_hand_contents_changed(pindex)
end
)
EventManager.on_event(
defines.events.on_player_mined_item,
---@param event EventData.on_player_mined_item
---@param pindex integer
function(event, pindex)
--Play item pickup sound
sounds.play_picked_up_item(pindex)
sounds.play_close_inventory(pindex)
end
)
function ensure_storage_structures_are_up_to_date()
storage.forces = storage.forces or {}
storage.players = storage.players or {}
for pindex, player in pairs(game.players) do
PlayerInit.initialize(player)
end
storage.entity_types = {}
entity_types = storage.entity_types
local types = {}
for _, ent in pairs(prototypes.entity) do
if
types[ent.type] == nil
and ent.weight == nil
and (
ent.burner_prototype ~= nil
or ent.electric_energy_source_prototype ~= nil
or ent.automated_ammo_count ~= nil
)
then
types[ent.type] = true
end
end
for i, type in pairs(types) do
table.insert(entity_types, i)
end
table.insert(entity_types, "container")
storage.production_types = {}
production_types = storage.production_types
-- TODO: reimplement production types. Seems only to be the warnings menu
-- using it.
storage.building_types = {}
building_types = storage.building_types
local ents = prototypes.entity
local types = {}
for i, ent in pairs(ents) do
if ent.is_building then types[ent.type] = true end
end
types["transport-belt"] = nil
for i, type in pairs(types) do
table.insert(building_types, i)
end
table.insert(building_types, "character")
end
EventManager.on_load(function()
entity_types = storage.entity_types
production_types = storage.production_types
building_types = storage.building_types
end)
EventManager.on_configuration_changed(ensure_storage_structures_are_up_to_date)
EventManager.on_init(function()
---@type any
local freeplay = remote.interfaces["freeplay"]
if freeplay and freeplay["set_skip_intro"] then remote.call("freeplay", "set_skip_intro", true) end
ensure_storage_structures_are_up_to_date()
TestFramework.on_init()
AudioCues.on_init()
end)
EventManager.on_event(
defines.events.on_cutscene_finished,
---@param event EventData.on_cutscene_finished
---@param pindex integer
function(event, pindex)
--Speech.speak(pindex, "Press TAB to continue")
end
)
EventManager.on_event(
defines.events.on_cutscene_started,
---@param event EventData.on_cutscene_started
---@param pindex integer
function(event, pindex)
--Speech.speak(pindex, "Press TAB to continue")
end
)
EventManager.on_event(
defines.events.on_player_created,
---@param event EventData.on_player_created
function(event)
PlayerInit.initialize(game.players[event.player_index])
--if not game.is_multiplayer() then Speech.speak(pindex, "Press 'TAB' to continue") end
end
)
EventManager.on_event(
defines.events.on_gui_closed,
---@param event EventData.on_gui_closed
function(event, pindex)
local router = UiRouter.get_router(pindex)
print(serpent.line(event, { nocode = true }))
--Other resets - now executed unconditionally
if event.element ~= nil then event.element.destroy() end
router:close_ui()
end
)
function fix_walk(pindex)
local player = game.get_player(pindex)
if not player.character then return end
-- Always use normal walking speed
player.character_running_speed_modifier = 0 -- 100% + 0 = 100%
end
EventManager.on_event(
defines.events.on_gui_opened,
---@param event EventData.on_gui_opened
---@param pindex integer
function(event, pindex)
local router = UiRouter.get_router(pindex)
local p = game.get_player(pindex)
end
)
EventManager.on_event(
defines.events.on_object_destroyed,
---@param event EventData.on_object_destroyed
function(event) --DOES NOT HAVE THE KEY PLAYER_INDEX
ScannerEntrypoint.on_entity_destroyed(event)
-- Close UIs that are bound to this entity
UiRouter.on_entity_destroyed(event.registration_number)
end
)
--If a filter inserter is selected, the item in hand is set as its output filter item.
function set_inserter_filter_by_hand(pindex, ent)
local stack = game.get_player(pindex).cursor_stack
if ent.filter_slot_count == 0 then return "This inserter has no filters to set" end
if stack == nil or stack.valid_for_read == false then
--Delete last filter
for i = ent.filter_slot_count, 1, -1 do
local filt = Filters.get_filter_prototype(ent, i)
if filt ~= nil then
Filters.set_filter(ent, i, nil)
return "Last filter cleared"
end
end
return "All filters cleared"
else
--Add item in hand as next filter
for i = 1, ent.filter_slot_count, 1 do
local filt = Filters.get_filter_prototype(ent, i)
if filt == nil then
Filters.set_filter(ent, i, stack.name)
if Filters.get_filter_prototype(ent, i) == stack.name then
return "Added filter"
else
return "Filter setting failed"
end
end
end
return "All filters full"
end
end
--Notifies battle sonifier when structures are damaged
--Character/vehicle damage sounds are handled by the tick-based health-bar sonifier
EventManager.on_event(
defines.events.on_entity_damaged,
---@param event EventData.on_entity_damaged
function(event)
local ent = event.entity
local tick = event.tick
if ent == nil or not ent.valid then
return
elseif ent.name == "character" then
-- Character damage is handled by tick-based health-bar sonifier
return
elseif Consts.VEHICLE_TYPES[ent.type] then
-- Vehicle damage is handled by tick-based health-bar sonifier
return
elseif ent.get_health_ratio() == 1.0 then
--Ignore alerts if an entity has full health despite being damaged
return
elseif tick < 3600 and tick > 600 then
--No alerts for the first 10th to 60th seconds (because of the alert spam from spaceship fire damage)
return
end
BattleNotice.notify(ent.force)
end
)
--Notifies battle sonifier when structures are destroyed
EventManager.on_event(
defines.events.on_entity_died,
---@param event EventData.on_entity_died
function(event)
local ent = event.entity
if ent == nil or ent.name == "character" then return end
BattleNotice.notify(ent.force)
end
)
--Notify all players when a player character dies
EventManager.on_event(
defines.events.on_player_died,
---@param event EventData.on_player_died
---@param pindex integer
function(event, pindex)
local p = game.get_player(pindex)
local causer = event.cause
local bodies = p.surface.find_entities_filtered({ name = "character-corpse" })
local latest_body = nil
local latest_death_tick = 0
local name = p.name
if name == nil then name = " " end
--Find the most recent character corpse
for i, body in ipairs(bodies) do
if
body.character_corpse_player_index == pindex and body.character_corpse_tick_of_death > latest_death_tick
then
latest_body = body
latest_death_tick = latest_body.character_corpse_tick_of_death
end
end
--Verify the latest death
if event.tick - latest_death_tick > 120 then latest_body = nil end
--Generate death message
local result = "Player " .. name
if causer == nil or not causer.valid then
result = result .. " died "
elseif causer.name == "character" and causer.player ~= nil and causer.player.valid then
local other_name = causer.player.name
if other_name == nil then other_name = "" end
result = result .. " was killed by player " .. other_name
else
result = result .. " was killed by " .. causer.name
end
if latest_body ~= nil and latest_body.valid then
result = result
.. " at "
.. math.floor(0.5 + latest_body.position.x)
.. ", "
.. math.floor(0.5 + latest_body.position.y)
.. "."
end
--Notify all players
for pindex, player in pairs(players) do
storage.players[pindex].last_damage_alert_tick = event.tick
Speech.speak(pindex, result)
game.get_player(pindex).print(result) --**laterdo unique sound, for now use console sound
end
end
)
EventManager.on_event(
defines.events.on_player_display_resolution_changed,
---@param event EventData.on_player_display_resolution_changed
---@param pindex integer
function(event, pindex)
local new_res = game.get_player(pindex).display_resolution
if players and storage.players[pindex] then storage.players[pindex].display_resolution = new_res end
game
.get_player(pindex)
.print("Display resolution changed: " .. new_res.width .. " x " .. new_res.height, { volume_modifier = 0 })
end
)
EventManager.on_event(
defines.events.on_player_display_scale_changed,
---@param event EventData.on_player_display_scale_changed
---@param pindex integer
function(event, pindex)
local new_sc = game.get_player(pindex).display_scale
if players and storage.players[pindex] then storage.players[pindex].display_resolution = new_sc end
game.get_player(pindex).print("Display scale changed: " .. new_sc, { volume_modifier = 0 })
end
)
EventManager.on_event(defines.events.on_string_translated, Localising.handler)
EventManager.on_event(
defines.events.on_player_respawned,
---@param event EventData.on_player_respawned
---@param pindex integer
function(event, pindex)
local vp = Viewpoint.get_viewpoint(pindex)
local position = game.get_player(pindex).position
vp:set_cursor_pos({ x = position.x, y = position.y })
MovementHistory.reset_and_increment_generation(pindex)
end
)
EventManager.on_event(
defines.events.on_player_main_inventory_changed,
---@param event EventData.on_player_main_inventory_changed
---@param pindex integer
function(event, pindex)
-- Refresh search cache if UI is open and search is active
UiRouter.on_inventory_changed(pindex)
end
)
--If the player has unexpected lateral movement while smooth running in a cardinal direction, like from bumping into an entity or being at the edge of water, play a sound.
function all_ents_are_walkable(pos)
local ents = game.surfaces[1].find_entities_filtered({
position = FaUtils.center_of_tile(pos),
radius = 0.4,
invert = true,
type = Consts.ENT_TYPES_YOU_CAN_WALK_OVER,
})
for i, ent in ipairs(ents) do
return false