-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol.lua
More file actions
executable file
·2134 lines (1854 loc) · 78.9 KB
/
control.lua
File metadata and controls
executable file
·2134 lines (1854 loc) · 78.9 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
-- RoboTank control.lua
-- Actions that run while the user is playing the game.
require "lua_util" -- add_vec, etc.
require "factorio_util" -- vehicle_velocity, etc.
-- True when we need to examine the storage data just loaded to
-- upgrade or validate it.
local must_initialize_loaded_storage_data = true;
-- True when, on the next tick, we need to rescan the world to check
-- for consistency with our data structures.
local must_rescan_world = true;
-- How much to log, from among:
--
-- 0: Nothing.
-- 1: Only things that indicate a serious problem. These suggest a
-- bug in the RoboTank mod, but are recoverable.
-- 2: Relatively infrequent things possibly of interest to the user,
-- such as changes to the formation of tanks, tanks complaining
-- about being stuck, loading ammo, etc.
-- 3: Changes to internal data structures.
-- 4: Details of algorithms.
--
-- The initial value here is overwritten by a configuration setting
-- during initialization, but takes effect until that happens.
local diagnostic_verbosity = 1;
-- Debug option to log all damage taken.
local log_all_damage = false;
-- Ticks between ammo checks. Set during initialization.
local ammo_check_period_ticks = 0;
--[[
Handling of Surfaces
--------------------
Entities can be on different surfaces. The intent is that only
entities on the same surface interact.
For efficiency, one might be tempted to partition all data by surface.
However, that runs into potential trouble when entities move between
surfaces. When player characters move, there is an event
(`on_player_changed_surface`), but it's not clear to me that the event
always fires when mods do the moving. Furthermore, mods can move
vehicles between surfaces, and there is no event for that. Thus, I do
not see a clear, reliable strategy for maintaining a partitioning by
surface.
Consequently, this mod keeps all the data in one structure, but checks
the surface in a few places:
* When selecting the commander vehicle for a player, the commander
vehicle must be on the same surface as the player. (Based on the
API docs, the player always has a surface, even if they do not have
a character.) When the player changes surfaces, the commander is
adjusted.
* When a RoboTank is considering running its driving algorithm, it
skips doing so if the commander is on a different surface.
* When a RoboTank is performing collision avoidance, it ignores
objects on different surfaces.
--]]
-- Structure of 'storage' is {
-- -- Data version number, bumped when I make a change that requires
-- -- special handling.
-- data_version = 6;
--
-- -- Map from force to its controllers. Each force's controllers
-- -- are a map from unit_number to its entity_controller object.
-- --
-- -- When a value of this map is stored in a local variable, we use
-- -- the name 'force_controllers'.
-- force_to_controllers = {};
--
-- -- Map from player_index to controllers associated with that
-- -- player. player_index is LuaPlayer.index. For a given player,
-- -- its controllers are a subset of those associated with that
-- -- player's force.
-- --
-- -- When a value of this map is stored in a local variable, we use
-- -- the name 'pi_controllers' to distinguish it from
-- -- 'force_controllers'.
-- player_index_to_controllers = {};
--
-- -- Map from player_index to its commander vehicle controller, if
-- -- there is such a commander. The commander is always on the same
-- -- surface as the player.
-- player_index_to_commander_controller = {};
-- };
-- Control state for an entity that is relevant to this mod. All
-- vehicles and player character entities have controller objects,
-- although we only "control" robotanks.
local function new_entity_controller(e)
return {
-- Reference to the Factorio entity we are controlling. This is
-- either a vehicle (type=="car"), which itself might be a robotank
-- (name=="robotank"), or a player character (name=="character").
entity = e,
-- Copy of the unit number. Normally this is redundant, but if I
-- discover that the entity is invalid (which should not happen), I
-- want a way to identify which entity it was.
unit_number = e.unit_number,
-- Associated turret entity that does the shooting. It is always
-- non-nil once 'add_entity' does its job for any robotank
-- vehicle, and nil for any other kind of entity.
turret = nil,
-- If this is a robotank that has a commander, this is an {x,y}
-- position that this robotank should go to in its formation,
-- relative to the commander, when the commander is facing East.
formation_position = nil;
-- When not nil, this records the tick number when the vehicle
-- became stuck, prevented from going the way it wants to by
-- some obstacles. If we are stuck long enough, the vehicle
-- will try to reverse out.
stuck_since = nil,
-- If stuck_since is not nil, then this records the vehicle
-- orientation at the time we became stuck. This is used to
-- avoid cases where the vehicle decides it is stuck even
-- though it is in the midst of turning.
stuck_orientation = nil;
-- When not nil, the vehicle has decided to reverse out of its
-- current position until the indicated tick count. When that
-- tick passes, the vehicle will first brake until it is stopped,
-- then clear the field and resume normal driving.
reversing_until = nil,
-- When this is non-nil, it is the number of ticks for which we
-- want to keep turning, after which we will straighten the wheel.
-- This is useful because, for speed, the driving algorithm does
-- not run on every tick, but we still want to be able to turn
-- for as little as one tick. One reason why is, in a tightly
-- packed formation of tanks, crude steering leads to unnecessary
-- mutual interference as the tanks drift into each other.
small_turn_ticks = nil,
-- When non-nil, we are accelerating for this many ticks, then
-- will coast.
short_acceleration_ticks = nil,
};
end;
-- Map from unit number to array of other entity controllers (on the
-- same force) that are near enough to this one to be relevant for
-- collision avoidance. When the entry for a given unit number is nil,
-- it needs to be recomputed.
--
-- This data is *not* stored in 'storage' because it would take a lot of
-- space in the save file. The data is inherently quadratic in size,
-- and the way Factorio serializes mod data adds another factor, such
-- that the serialized size is cubic in the number of tanks. That in
-- turn causes the Lua interpreter to choke on the data when the save
-- file is loaded ("function or expression too complex") when there are
-- on the order of 40 tanks on the map.
--
-- Fortunately, it is easy to recompute after a load.
local unit_number_to_nearby_controllers = {};
-- Map from hidden turret entity name to true.
local robotank_turret_entity_name_set = {
["robotank-gun-turret"] = true,
["robotank-cannon-turret"] = true,
};
-- Map from ammo_category to hidden turret entity name that can fire
-- that kind of ammo.
--
-- Eventually I'd like to expand this to handle more ammo types.
local ammo_category_to_turret_name = {
["bullet"] = "robotank-gun-turret",
["cannon-shell"] = "robotank-cannon-turret",
};
-- Forward declarations of functions.
local remove_invalid_entities;
local remove_entity_controller;
local find_unassociated_entities;
-- Log 'str' if we are at verbosity 'v' or higher.
local function diag(v, str)
if (v <= diagnostic_verbosity) then
log(str);
end;
end;
-- Re-read the configuration settings.
local function read_configuration_settings()
diag(3, "read_configuration_settings started");
ammo_check_period_ticks = settings.global["robotank-ammo-check-period-ticks"].value;
diagnostic_verbosity = settings.global["robotank-diagnostic-verbosity"].value;
diag(3, "read_configuration_settings finished");
end;
-- Do it once on startup, then afterward in response to the
-- on_runtime_mod_setting_changed event.
read_configuration_settings();
script.on_event(defines.events.on_runtime_mod_setting_changed, read_configuration_settings);
-- Return the (string) name of the force associated with 'e'.
local function force_of_entity(e)
return string_or_name_of(e.force);
end;
-- Get the player index associated with entity 'e', or -1 if this
-- entity is not associated with a player.
local function player_index_of_entity(e)
if (e.type == 'car') then
-- Vehicle.
--
-- Normally vehicles always have a last_user, but with mods it is
-- evidently possible for last_user to be nil:
-- https://mods.factorio.com/mod/RoboTank/discussion/5cb114b4a07570000cfc3762
if (e.last_user == nil) then
return -1;
else
return e.last_user.index;
end;
elseif (e.type == 'character') then
-- Character.
if (e.player ~= nil) then
return e.player.index;
else
return -1;
end;
else
return -1;
end;
end;
-- Check that our data invariants hold. If not, log a message at
-- level 1 and return false.
local function check_invariants()
-- Check that everything in 'player_index_to_controllers' is also
-- in 'force_to_controllers'.
for player_index, pi_controllers in pairs(storage.player_index_to_controllers) do
for unit_number, controller in pairs(pi_controllers) do
local entity = controller.entity;
if (not entity.valid) then
diag(1, "WARNING: Entity with unit number " .. unit_number ..
" in pi_controllers for player index " .. player_index ..
" is invalid.");
return false;
end;
local entity_pi = player_index_of_entity(entity);
if (player_index ~= entity_pi) then
diag(1, "WARNING: Entity " .. entity.unit_number ..
" has player index " .. entity_pi ..
" but was found in the table for PI " .. player_index ..
".");
return false;
end;
local force = force_of_entity(entity);
if (storage.force_to_controllers[force][unit_number] ~= controller) then
diag(1, "WARNING: Controller for entity " .. entity.unit_number ..
", with force " .. force ..
", was not found in its force table.");
return false;
end;
end;
end;
-- Check the maps in the opposite direction.
for force, force_controllers in pairs(storage.force_to_controllers) do
for unit_number, controller in pairs(force_controllers) do
local entity = controller.entity;
if (not entity.valid) then
diag(1, "WARNING: Entity with unit number " .. unit_number ..
" in force_controllers for force \"" .. force ..
"\" is invalid.");
return false;
end;
local entity_force = force_of_entity(entity);
if (force ~= entity_force) then
diag(1, "WARNING: Entity " .. entity.unit_number ..
" has force \"" .. entity_force ..
"\" but was found in the table for \"" .. force .. "\".");
return false;
end;
-- One concern I have here is the association between vehicles
-- and players. The GUI information panel for a vehicle labels
-- the "Last user", but (at least in Factorio 0.17.14)
-- it does not change when another player uses it. Instead, the
-- association seems to never change after placement. If Factorio
-- changes that behavior, then my invariants will break, and this
-- code will have to repair them.
local player_index = player_index_of_entity(entity);
if (player_index < 0) then
diag(1, "WARNING: Entity " .. entity.unit_number ..
" does not have a player index.");
return false;
end;
if (storage.player_index_to_controllers[player_index][unit_number] ~= controller) then
diag(1, "WARNING: Controller for entity " .. entity.unit_number ..
", with player index " .. player_index ..
", was not found in its PI table.");
return false;
end;
end;
end;
return true;
end;
-- Clear the storage data structures and rebuild them from the world.
-- This is done in response to discovering a broken invariant as a
-- method of fault tolerance.
local function reset_storage_data()
diag(1, "RoboTank: resetting storage data");
must_rescan_world = false;
-- Clear the data structures so we can rebuild them.
storage.force_to_controllers = {};
storage.player_index_to_controllers = {};
storage.player_index_to_commander_controller = {};
-- This will re-add all the entities we keep track of.
find_unassociated_entities();
end;
local function check_or_fix_invariants()
if (not check_invariants()) then
reset_storage_data();
if (not check_invariants()) then
error("Invariants are still broken even after attempting repair.");
end;
end;
end;
-- Return an array of turret entity names.
local function robotank_turret_entity_name_array()
return table_keys_array(robotank_turret_entity_name_set);
end;
-- True if the given string is the name of a robotank turret entity.
local function is_robotank_turret_entity_name(s)
return robotank_turret_entity_name_set[s] == true
end;
-- Add an entity to our tables and return its controller.
--
-- Some entities cannot have controllers, in which case return nil.
local function add_entity(e)
local force_name = force_of_entity(e);
storage.force_to_controllers[force_name] =
storage.force_to_controllers[force_name] or {};
local player_index = player_index_of_entity(e);
if (player_index < 0) then
diag(3, "Cannot add entity due to lack of player index:" ..
" unit=" .. e.unit_number ..
" type=" .. e.type ..
" name=" .. e.name ..
" pos=(" .. e.position.x .. "," .. e.position.y .. ")" ..
" force=" .. force_name);
return nil;
end;
storage.player_index_to_controllers[player_index] =
storage.player_index_to_controllers[player_index] or {};
local controller = new_entity_controller(e);
storage.force_to_controllers[force_name][e.unit_number] = controller;
storage.player_index_to_controllers[player_index][e.unit_number] = controller;
if (e.name == "robotank") then
-- Is there already an associated turret here?
local p = controller.entity.position;
local candidates = e.surface.find_entities_filtered{
area = {{p.x-0.5, p.y-0.5}, {p.x+0.5, p.y+0.5}},
name = robotank_turret_entity_name_array(),
};
if (#candidates > 0) then
controller.turret = candidates[1];
diag(3, "Found existing turret with unit number " .. controller.turret.unit_number .. ".");
else
controller.turret = e.surface.create_entity{
-- Initially, create it as a gun turret. It may be changed
-- once we load some ammo.
name = "robotank-gun-turret",
position = controller.entity.position,
force = e.force};
if (controller.turret) then
diag(3, "Made new turret: " .. controller.turret.name .. ".");
else
-- This unfortunately is not recoverable because I do not check
-- for a nil turret elsewhere, both for simplicity of logic and
-- speed of execution.
error("Failed to create turret for robotank!");
end;
end;
end;
diag(3, "Added entity: unit=" .. e.unit_number ..
" type=" .. e.type ..
" name=" .. e.name ..
" player_index=" .. player_index_of_entity(e) ..
" pos=(" .. e.position.x .. "," .. e.position.y .. ")" ..
" surface=" .. e.surface.name ..
" force=" .. force_name);
return controller;
end;
-- Search the entire data structure for a controller for 'entity',
-- ignoring its force or player_index.
local function find_entity_controller_slow_search(entity)
for force, force_controllers in pairs(storage.force_to_controllers) do
for unit_number, controller in pairs(force_controllers) do
if (controller.entity == entity) then
return controller;
end;
end;
end;
return nil;
end;
-- Find the controller object associated with the given entity, if any.
local function find_entity_controller(entity)
local player_index = player_index_of_entity(entity);
if (player_index < 0) then
-- This happens when the player dies. Resort to a slow search of
-- the entire data structure to find the controller. We are about
-- to remove the controller, so the invariant about controllers being
-- in the table of their player_index being temporarily broken should
-- not cause a problem.
diag(3, "find_entity_controller: player_index < 0, resorting to slow search");
return find_entity_controller_slow_search(entity);
end;
local pi_controllers = storage.player_index_to_controllers[player_index];
if (pi_controllers) then
return pi_controllers[entity.unit_number];
else
return nil;
end;
end;
-- The mod just started running. Some data may or may not have been
-- loaded from 'storage' (depending on whether the mod was previously
-- part of the game, and what version it was if so). Make sure it is
-- properly initialized.
local function initialize_loaded_storage_data()
diag(3, "Loaded data_version: " .. serpent.line(storage.data_version));
-- I have removed all of the upgrade steps related to versions before
-- Factorio 2.0 since I don't want to spend time testing them. I
-- don't know, and don't really care, what will happen if one tries to
-- load a world containing pre-2.0 RoboTank.
-- The first version that supports Factorio 2.0 has version 6.
storage.data_version = 6;
if (storage.player_index_to_commander_controller == nil) then
diag(3, "player_index_to_commander_controller was nil, setting it to empty.");
storage.player_index_to_commander_controller = {};
else
diag(3, "player_index_to_commander_controller has " ..
table_size(storage.player_index_to_commander_controller) .. " entries.");
end;
if (storage.force_to_controllers == nil) then
diag(3, "force_to_controllers was nil, setting it to empty.");
storage.force_to_controllers = {};
else
diag(3, "force_to_controllers has " ..
table_size(storage.force_to_controllers) .. " entries.");
for force, force_controllers in pairs(storage.force_to_controllers) do
diag(3, " force \"" .. force .. "\" has " ..
table_size(force_controllers) .. " controllers.");
end;
end;
if (storage.player_index_to_controllers == nil) then
diag(3, "player_index_to_controllers was nil, setting it to empty.");
storage.player_index_to_controllers = {};
else
diag(3, "player_index_to_controllers has " ..
table_size(storage.player_index_to_controllers) .. " entries.");
for player_index, pi_controllers in pairs(storage.player_index_to_controllers) do
diag(3, " player_index " .. player_index .. " has " ..
table_size(pi_controllers) .. " controllers.");
end;
end;
-- Deal with loading a map that had players in it when saved
-- but the players are now gone.
remove_invalid_entities();
check_or_fix_invariants();
end;
-- If there is already a controller for 'entity', return it. Otherwise,
-- make a new controller and return that.
--
-- If this entity cannot have a controller, return nil.
local function find_or_create_entity_controller(entity)
local controller = find_entity_controller(entity);
if (controller ~= nil) then
diag(3, "Found existing controller object for unit " .. entity.unit_number);
else
diag(3, "Unit number " .. entity.unit_number ..
" has no controller, making a new one.");
controller = add_entity(entity);
end;
return controller;
end;
-- Called during 'find_unassociated_entities' when one is found.
local function found_an_entity(e, turrets)
--diag(4, "found entity: " .. serpent.block(entity_info(e)));
-- See if we already know about this entity.
local controller = find_or_create_entity_controller(e);
if (controller ~= nil and controller.turret ~= nil) then
-- This turret is now accounted for (it might have existed before,
-- or it might have just been created by 'add_entity').
turrets[controller.turret.unit_number] = nil;
end;
end;
-- Scan the world for entities that should be tracked in my data
-- structures but are not. They are then either added to my tables
-- or deleted from the world.
find_unassociated_entities = function()
for _, surface in pairs(game.surfaces) do
diag(4, "find_unassociated_entities: scanning surface: " .. surface.name);
-- Scan the surface for all of our hidden turrets so that later we
-- can get rid of any not associated with a vehicle.
local turrets = {};
for _, t in ipairs(surface.find_entities_filtered{name=robotank_turret_entity_name_array()}) do
turrets[t.unit_number] = t;
end;
-- Add all vehicles to 'force_to_controllers' table.
for _, v in ipairs(surface.find_entities_filtered{type = "car"}) do
found_an_entity(v, turrets);
end;
-- And player characters, mainly so we can avoid running them over
-- when driving the robotanks.
for _, character in ipairs(surface.find_entities_filtered{name = "character"}) do
found_an_entity(character, turrets);
end;
-- Destroy any unassociated turrets. There should never be any, but
-- this will catch things that might be left behind due to a bug in
-- my code.
for unit_number, t in pairs(turrets) do
diag(1, "WARNING: Should not happen: destroying unassociated turret " .. unit_number);
t.destroy();
end;
end;
end;
-- Find the vehicle controller among `pi_controllers` that is commanding
-- them, if any. It must be on `surface`.
local function find_commander_controller(pi_controllers, surface)
for unit_number, controller in pairs(pi_controllers) do
local v = controller.entity;
-- It is possible for another mod to delete a vehicle without
-- triggering one of the events I am monitoring.
if (not v.valid) then
diag(3, "find_commander_controller: Removing invalid entity " .. unit_number .. ".");
remove_entity_controller(controller);
elseif (v.speed == nil) then
-- The commander must be a vehicle, and hence will have a speed.
-- This entity does not, so skip it.
--
-- This check prevents player characters from being commanders.
-- I would have thought that checking the "car_trunk" inventory
-- would suffice, but in fact the quick bar counts as the "trunk"
-- for a player! (As of Factorio 0.17, that is probably no longer
-- true.)
elseif (v.surface ~= surface) then
-- Not on the right surface.
elseif (v.name == "robotank") then
-- A robotank cannot be a commander.
else
-- It must have the transmitter item in its trunk.
local inv = v.get_inventory(defines.inventory.car_trunk);
if (inv and inv.get_item_count("robotank-transmitter") > 0) then
return controller;
end;
end;
end;
return nil;
end;
-- Get a LuaItemStack from the source inventory that can be added to the
-- destination inventory. If there are more than one, returns one
-- arbitrarily. Otherwise return nil.
local function get_insertable_stack(source, dest)
for slot_num = 1, #source do
local stack = source[slot_num];
if (stack.count > 0) then
if (dest.can_insert(stack)) then
return stack;
end;
end;
end;
return nil;
end;
-- Try to keep the turret stocked up on ammo by taking it from the tank.
local function maybe_load_robotank_turret_ammo(controller)
-- See if the turret needs another ammo magazine.
local turret_inv = controller.turret.get_inventory(defines.inventory.turret_ammo);
if (turret_inv == nil) then
diag(1, "Failed to get turret inventory!");
return;
end;
-- For speed, I only look at the inventory if it is completely empty.
-- That means there is periodically a frame during which the turret
-- ammo is empty, so the turret stops firing and shows the no-ammo icon
-- briefly.
if (turret_inv.is_empty()) then
-- Check the vehicle's ammo slot.
local car_inv = controller.entity.get_inventory(defines.inventory.car_ammo);
if (not car_inv) then
diag(1, "Failed to get car_ammo inventory!");
return;
end;
-- Is there ammo in an ammo slot that fits in the turret?
local ammo_stack = get_insertable_stack(car_inv, turret_inv);
if (not ammo_stack) then
-- No ammo fits in the current turret. Is there ammo
-- compatible with a different robotank turret entity?
for candidate_slot_num = 1, #car_inv do
local candidate_stack = car_inv[candidate_slot_num];
if (candidate_stack.count > 0) then
-- Check that the stack contains ammo. This should be
-- redundant since we are iterating over the ammunition
-- inventory of the vehicle, but I do it for extra safety.
local candidate_proto = prototypes.item[candidate_stack.name];
if (candidate_proto.type == "ammo") then
local ammo_category_name = candidate_proto.ammo_category.name;
diag(4, "Candidate ammo stack:" ..
" name=" .. candidate_stack.name ..
" count=" .. candidate_stack.count ..
" category=" .. ammo_category_name);
-- Look up which of the robotank turret types, if any, is
-- compatible with this category of ammo.
local new_turret_name = ammo_category_to_turret_name[ammo_category_name];
if (new_turret_name ~= nil) then
diag(2, "Changing turret on vehicle " .. controller.entity.unit_number ..
" from " .. controller.turret.name ..
" to " .. new_turret_name ..
" due to loading ammo " .. candidate_stack.name ..
" with category " .. ammo_category_name .. ".");
-- Remove the old turret.
if (not controller.turret.destroy()) then
diag(1, "WARNING: Failed to destroy turret while changing ammo type!");
end;
-- Add the new turret.
controller.turret = controller.entity.surface.create_entity{
name = new_turret_name,
position = controller.entity.position,
force = controller.entity.force};
if (not controller.turret) then
error("Failed to create turret (" .. new_turret_name ..
") for robotank!");
end;
-- Refresh the reference to its inventory.
turret_inv = controller.turret.get_inventory(defines.inventory.turret_ammo);
if (turret_inv == nil) then
-- This will leave us in a state where we have an attached
-- turret but can never fill it or change it...
diag(1, "Failed to get turret inventory after creating " ..
" a new turret with name " .. new_turret_name .. "!");
return;
end;
-- Stop looping over the ammo slots. Set `ammo_stack`
-- so we will skip checking the trunk and go straight to
-- inserting the ammo into the new turret.
ammo_stack = candidate_stack;
break;
end;
end;
end;
end; -- for loop over inventory contents
end;
if (not ammo_stack) then
-- Try the trunk.
car_inv = controller.entity.get_inventory(defines.inventory.car_trunk);
if (not car_inv) then
diag(1, "Failed to get car_trunk inventory!");
return;
end;
ammo_stack = get_insertable_stack(car_inv, turret_inv);
-- Here, if 'ammo_stack' is nil, we do not try changing the turret type.
-- The rationale is that, since a given tank can only fire one kind
-- of ammo as long as it has any, the player ought to explicitly
-- choose one. They do that by loading ammo into a tank ammo
-- slot, as opposed to its trunk, which might get used as extra
-- storage of random stuff (perhaps including other kinds of ammo)
-- while in the field.
end;
if (ammo_stack) then
-- Move the entire stack into the turret.
-- Find an empty slot.
local turret_stack, turret_inv_slot_num = turret_inv.find_empty_stack(src_stack);
if (turret_stack == nil) then
diag(1, "Failed to find an empty slot in the turret!");
else
-- Swap the stacks to effect a lossless, dup-less transfer.
if (ammo_stack.swap_stack(turret_stack)) then
diag(2, "Loaded " .. turret_stack.count ..
" ammo magazines of type " .. turret_stack.name ..
" into turret of unit " .. controller.entity.unit_number .. ".");
else
diag(1, "Failed to add ammo to turret!");
end;
end;
end;
end;
end;
-- Predict how long it will take for particles at p1 and p2,
-- moving with velocities v1 and v2, to come within 'dist'
-- units of each other ("contact"). Also return an angle,
-- in radians, from p2 at the moment of contact to the contact
-- point. If they will not come that close, ticks is nil.
-- If they are already within 'dist', ticks is 0. In either of
-- those cases, the returned angle is the current p2 to p1 angle.
local function predict_approach(p1, v1, p2, v2, dist)
-- Move p1 to the origin.
p2 = subtract_vec(p2, p1);
local mag_sq_p2 = mag_sq(p2);
if (mag_sq_p2 < 0.000001) then
-- Already on top of each other.
return 0, 0;
end;
-- Current angle from p2 to p1.
local angle_p2_to_p1 = math.atan2(-p2.y, -p2.x);
if (mag_sq_p2 < dist*dist) then
-- Already in contact.
return 0, angle_p2_to_p1;
end;
-- Compute movement of p2 relative to p1.
v2 = subtract_vec(v2, v1);
if (mag_sq(v2) < 0.000001) then
-- Not moving relative to each other, will not be in contact.
return nil, angle_p2_to_p1;
end;
-- Rotate the system so the velocity (v) is pointing East (+x),
-- obtaining a new point (p) that is the rotated location of p2.
local v2angle = vector_to_angle(v2);
local v = rotate_vec(v2, -v2angle);
local p = rotate_vec(p2, -v2angle);
if (p.x > 0) then
-- Moving in same direction as displacement, so the
-- separation distance will only increase.
return nil, angle_p2_to_p1;
end;
-- Compute the vertical separation at contact. This is the sine
-- of the contact angle from p1 to p2, in the rotated frame.
local s = math.abs(p.y);
if (s > dist) then
-- No contact.
return nil, angle_p2_to_p1;
end;
-- Call the rotated p1p2 contact angle theta. It is always
-- in the second or third quadrant, since p2 is approaching
-- from the left, hence the angle complement with pi.
local theta = math.pi - math.asin(s / dist);
if (p.y < 0) then
theta = -theta;
end;
-- From that, compute the horizontal separation at contact,
-- which is negative due to theta's quadrant.
local c = math.cos(theta) * dist;
-- Distance from p2 to contact point is current horizontal
-- separation minus that at contact.
local distance_to_contact = -p.x + c;
-- Divide by speed to get ticks.
local ticks = distance_to_contact / v.x;
-- Finally, the p2 to p1 contact angle is 180 opposite to p1p2,
-- then we have to undo the earlier rotation.
local angle = normalize_radians(theta + math.pi + v2angle);
return ticks, angle;
end;
-- Deal with having discovered that a controller related to some unit
-- has an invalid entity. One way this happens is when the Jetpack mod
-- transforms the player character (PC) into a flyable unit. The PC has
-- a controller (for collision avoidance) but becomes invalid as a
-- result of that transformation.
--
-- We log the event and then arrange to refresh the data.
local function found_invalid_entity(
data_name, -- str: name of the data structure
unit_number, -- int: unit we were processing
controller -- controller that has an invalid entity
)
diag(2, data_name .. " for unit " ..
unit_number .. " contains an invalid entity that had " ..
"unit number " .. controller.unit_number);
must_rescan_world = true;
end;
-- Return flags describing what is necessary for 'controller.entity'
-- to avoid colliding with one of the 'force_controllers', which are
-- associated with all entities with the same force. 'controller' is
-- known to be controlling a robotank entity and 'unit_number' is its
-- unit number.
--
-- This function and its callees form the inner loop of this mod,
-- where 70% of time is spent.
local function collision_avoidance(tick, force_controllers, unit_number, controller)
local cannot_turn = false;
local must_brake = false;
local cannot_accelerate = false;
-- Hoist several quantities out of the loops below. This significantly
-- improves speed, in part (I think) because crossing into C++ to get
-- attributes of C++ objects is slow.
local v = controller.entity;
local v_position = v.position;
local v_velocity = vehicle_velocity(v);
local v_orientation = v.orientation;
local v_speed = v.speed;
local v_surface = v.surface;
-- PERFORMANCE TESTING MODE:
-- When I am doing performance testing, I want to disable the nearby
-- controller refresh because it causes the per-tick time to have a
-- lot of noise. I also want all controllers on the same surface to
-- be included so that the set of nearby entities is also eliminated
-- as a source of measurement variability.
--[[
if (unit_number_to_nearby_controllers[unit_number] == nil) then
unit_number_to_nearby_controllers[unit_number] = {};
for _, other in pairs(force_controllers) do
if (other.entity ~= v and other.entity.surface == v_surface) then
table.insert(unit_number_to_nearby_controllers[unit_number], other);
end;
end;
end;
--]]
-- NORMAL MODE:
-- Periodically refresh the list of other entities near enough
-- to this one to be considered by the per-tick collision analysis.
---[[
if (unit_number_to_nearby_controllers[unit_number] == nil or (tick % 60 == 0)) then
unit_number_to_nearby_controllers[unit_number] = {};
for _, other in pairs(force_controllers) do
if (not other.entity.valid) then
found_invalid_entity("Force controllers map", unit_number, other);
elseif (other.entity ~= v and other.entity.surface == v_surface) then
-- The other entity is considered nearby if it is or will be
-- within a certain, relatively large, distance before we next
-- refresh the list of nearby entities.
local approach_ticks, approach_angle = predict_approach(
other.entity.position,
entity_velocity(other.entity),
v_position,
v_velocity,
20);
if (approach_ticks ~= nil and approach_ticks < 60) then
table.insert(unit_number_to_nearby_controllers[unit_number], other);
end;
end;
end;
end;
--]]
-- Scan nearby entities for collision potential.
for _, other in ipairs(unit_number_to_nearby_controllers[unit_number]) do
if (other.entity.valid) then
-- Are we too close to turn?
local other_entity_position = other.entity.position;
local dist_sq = mag_sq_subtract_vec(other_entity_position, v_position);
if (dist_sq < 11.5) then -- about 3.4 squared
cannot_turn = true;
end;
-- At current velocities, how long (how many ticks) until we come
-- within 4 units of the other unit, and in which direction would
-- contact occur?
local approach_ticks, approach_angle = predict_approach(
other_entity_position,
entity_velocity(other.entity),
v_position,
v_velocity,
4);
local approach_orientation = radians_to_orientation(approach_angle);
local abs_orient_diff = absolute_orientation_difference(approach_orientation, v_orientation);
if (approach_ticks ~= nil and abs_orient_diff <= 0.25) then
-- Contact would occur in front, so if it is imminent, then we
-- need to slow down.
if (approach_ticks < v_speed * 1000) then
must_brake = true;
elseif (approach_ticks < (v_speed + 0.02) * 2000) then -- speed+0.02: Presumed effect of acceleration.
cannot_accelerate = true;
end;
end;
--[[
if ((tick % 10 == 0) and (other.entity.type ~= "car" or other.entity.get_driver() == nil)) then
log("" .. controller.entity.unit_number ..
" approaching " .. other.entity.unit_number ..
": dist=" .. math.sqrt(dist_sq) ..
" ticks=" .. serpent.line(approach_ticks) ..
" angle=" .. serpent.line(approach_angle) ..
--" approach_orientation=" .. serpent.line(approach_orientation) ..
" adorient=" .. serpent.line(abs_orient_diff) ..
" speed=" .. v.speed ..
" cannot_turn=" .. serpent.line(cannot_turn) ..
" must_brake=" .. serpent.line(must_brake) ..
" cannot_accelerate=" .. serpent.line(cannot_accelerate));
end;
--]]
else
found_invalid_entity("Nearby controllers list", unit_number, other);
end;
end;
return cannot_turn, must_brake, cannot_accelerate;
end;