-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSkirmishAiSystem.cs
More file actions
2032 lines (1885 loc) · 101 KB
/
Copy pathSkirmishAiSystem.cs
File metadata and controls
2032 lines (1885 loc) · 101 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
using System;
using System.Collections.Generic;
using Nova.AI.Data;
using Nova.Core;
using Nova.Simulation;
using Nova.Simulation.CommandsV1;
using Nova.Simulation.Combat;
using Nova.Simulation.Construction;
using Nova.Simulation.Definitions;
using Nova.Simulation.Economy;
using Nova.Simulation.Pathfinding;
using Nova.Simulation.Production;
using Nova.Simulation.State;
using Nova.Simulation.Victory;
using Nova.Simulation.Vision;
namespace Nova.AI
{
/// <summary>
/// Deterministic MS-1 skirmish opponent (docs/tech/AIArchitecture.md).
/// Plays one slot of the canonical two-slot match — build order, economy,
/// army and attacks — over the SAME command path a human uses: every
/// action is a schema-v1 <see cref="CommandIntent"/> handed to the AI
/// peer's own slot-bound <see cref="CommandIngress"/> (session authority
/// assigns slot, sequence and target tick; <see cref="AiPeerCommandTransport"/>
/// forwards the sealed records into the host intake). No direct calls into
/// construction/production/economy mutation APIs — the executor's
/// state-dependent validation judges every AI order exactly like a UI
/// order (Commands.md section 4).
/// <para>
/// READ BOUNDARY (AIArchitecture.md sections 1 and 6): enemy entities are
/// observed ONLY through <see cref="FogOfWarSystem.GetVisibleEntities"/>
/// — the team's committed view, the single legal sight for targeting.
/// Own-slot data (credits, power, production queues, placements, own unit
/// orders) is read from the canonical systems; a human player has the same
/// own-slot information, so no hidden state leaks into a decision. Static
/// map geometry (registered Aetherium fields, and with them the enemy
/// start area — the demo map seats every base beside its field) is known
/// map knowledge, never fog-hidden entity data. The strict
/// AIArchitecture.md split (a TeamWorldView type and a versioned
/// AiSidecar) does not exist in this slice yet; reading the committed own
/// state directly is the documented G1 simplification, and the system is
/// STATELESS (every decision is a pure function of the tick and the
/// committed state — no timers, no memory), so there is no AI state to
/// serialize and plain <see cref="ISimSystem"/> satisfies the kernel
/// registration checklist. Save/restore therefore reproduces the same
/// later intents without any sidecar block.
/// </para>
/// <para>
/// DECISION LOOP (fixed cadence <see cref="DecisionTickInterval"/> = 20
/// ticks = 2.0 s, ascending-index scans only, no PRNG): (1) build order —
/// Refinery first (no prerequisite since D-077), then the Power plant
/// required by D-103, then Barracks, one site at a time; Power also
/// preempts whenever the committed margin would drop below the profile
/// reserve, the spot picked by a deterministic
/// search validated through <see cref="ConstructionSystem.ValidatePlacement"/>
/// — the identical rules the command executor applies; (2) the Builder is
/// moved next to an unfinished site when it is out of the documented
/// Chebyshev reach <= 1 (ConstructionSystem remarks), and a replacement
/// Builder is queued at the HQ when none is alive; (3) once the Refinery
/// stands, harvesters are queued up to
/// <see cref="AiFactionProfile.TargetHarvesterCount"/>, every idle own
/// harvester receives a Harvest intent on the nearest field THAT STILL
/// HOLDS RESERVE (an exhausted one is skipped — without that test the step
/// re-issues an order the economy clears again on the same tick, forever;
/// issue #85), and harvesters held out of reach are WALKED into the
/// economy's reach rule with
/// explicit Move intents (gather leg toward a field-and-footprint
/// dual-reach cell, return leg toward the footprint — this slice does not
/// use the Refinery's rally point at all, it micro-manages like a human;
/// a rally point WOULD be accepted, see the note at the economy step);
/// (4) once the
/// Barracks stands, infantry is queued up to
/// <see cref="AiFactionProfile.TargetArmySize"/> as funds allow;
/// (5) the army resolves a POSTURE (does it act at all, which target,
/// which destination), then ONE GOAL PER UNIT out of the fixed priority
/// list in <see cref="GoalKind"/> — <c>Retreat</c>, <c>DefendHome</c>,
/// <c>Attack</c>, <c>Hold</c>, <c>Advance</c> — whose effect is the unit's
/// orders, then
/// submission that groups units sharing an order into a single intent: at
/// <see cref="AiFactionProfile.AttackSquadThreshold"/> living combat units
/// the army is sent toward the enemy start area, and the best scored
/// visible enemy receives an EXPLICIT AttackTarget intent from every unit.
/// There is no attack-move (GB-002), but D-087 DID add auto-acquisition to
/// <see cref="CombatSystem"/>: an idle armed unit picks the nearest
/// visible hostile in range by itself. Explicit orders are never
/// retargeted, so an AI order always wins over the automatic pick — and
/// therefore has to be at least as good as it. The enemy HQ is preferred
/// once visible (D-077: its loss defeats the slot).
/// </para>
/// <para>
/// Rejection tolerance: affordability, the power rule and placement
/// legality are pre-checked against the same rules the executor uses, and
/// redundant re-issues are suppressed by comparing the standing order
/// (move target, attack target, harvest field) before
/// submitting. Anything still rejected (e.g. backpressure) is simply
/// retried on the next cadence — the stateless loop never spams.
/// Determinism: intents submitted while the kernel executes tick T are
/// sealed into the batch of T+1 (the host advances the AI peer clock
/// before stepping); the one-tick input delay is the canonical one every
/// command pays (MatchSession.InputDelayTicks = 1, part of the match
/// fingerprint).
/// </para>
/// <para>
/// Zero engine dependencies (no UnityEngine types).
/// </para>
/// </summary>
public sealed class SkirmishAiSystem : ISimSystem
{
// THE NUMBERS LIVE IN Nova.AI.Data. What used to be four const fields
// here are profile values now — behaviour in C#, numbers in one place
// (AIArchitecture.md section 3). The shipped profile carries exactly
// the constants that stood here, so this move changes nothing; the
// proof is the unchanged end-state pin in SkirmishAiTests, not the
// four determinism baselines — those never run this system.
/// <summary>Decision cadence in ticks: 20 ticks = 2.0 s on the canonical 10 Hz clock.</summary>
public ushort DecisionTickInterval => _profile.Profile.DecisionTickInterval;
/// <summary>Largest Chebyshev ring around the placement anchor the spot search tries (documented AI choice, not a rule).</summary>
private int PlacementSearchRadius => _profile.Profile.PlacementSearchRadius;
/// <summary>Infantry queued per decision tick while below the army cap (smooths spending over the cadence).</summary>
private int InfantryQueueBatch => _profile.Profile.InfantryQueueBatch;
/// <summary>Harvesters queued per decision tick while below the harvester target.</summary>
private int HarvesterQueueBatch => _profile.Profile.HarvesterQueueBatch;
/// <summary>One own construction site seen in the ascending scan (the site entity sits at the footprint center cell).</summary>
private struct SiteInfo
{
public int CellX;
public int CellY;
public uint AssignedBuilderRaw;
}
private readonly byte _aiPlayerId;
private readonly AiFactionProfile _profile;
private readonly CommandIngress _ingress;
private readonly EntityManager _entityManager;
private readonly EconomySystem _economy;
private readonly ConstructionSystem _construction;
private readonly ProductionSystem _production;
private readonly FogOfWarSystem _fogOfWar;
private readonly VictorySystem _victory;
/// <summary>
/// Watches the decisions; null in the shipped game. Read-only from the
/// AI's side — an observer cannot change what is decided, and nothing it
/// is told is kept here.
/// </summary>
private readonly IAiGoalObserver _goalObserver;
/// <summary>
/// Goals forced from outside; null in the shipped game. An INPUT to the
/// decision, like the profile — never a memory of one.
/// </summary>
private readonly IAiGoalOverride _goalOverride;
public string Name => $"SkirmishAi_{_profile.FactionName}_P{_aiPlayerId}";
public byte AiPlayerId => _aiPlayerId;
/// <summary>
/// <paramref name="ingress"/> is the AI peer's OWN slot-bound ingress
/// (its session's local slot is <paramref name="aiPlayerId"/>), never
/// the human host ingress — that is what keeps the AI on the canonical
/// intent path with an authority-assigned slot, sequence and target
/// tick.
/// <para>
/// THE LAST TWO ARGUMENTS ARE OPTIONAL AND THE GAME PASSES NEITHER.
/// <paramref name="goalObserver"/> is told which goal each unit was
/// given, <paramref name="goalOverride"/> may name a goal for single
/// units before the decision is taken; both belong to the lab's admin
/// panel. They are constructor arguments rather than settable properties
/// so that neither can be swapped mid-match: the AI reads two references
/// that were fixed before the first tick, which is what lets the run
/// stay reproducible from its inputs.
/// </para>
/// </summary>
public SkirmishAiSystem(
byte aiPlayerId,
AiFactionProfile profile,
CommandIngress ingress,
EntityManager entityManager,
EconomySystem economy,
ConstructionSystem construction,
ProductionSystem production,
FogOfWarSystem fogOfWar,
VictorySystem victory,
IAiGoalObserver goalObserver = null,
IAiGoalOverride goalOverride = null)
{
_goalObserver = goalObserver;
_goalOverride = goalOverride;
_aiPlayerId = aiPlayerId;
_profile = profile;
_ingress = ingress ?? throw new ArgumentNullException(nameof(ingress));
_entityManager = entityManager ?? throw new ArgumentNullException(nameof(entityManager));
_economy = economy ?? throw new ArgumentNullException(nameof(economy));
_construction = construction ?? throw new ArgumentNullException(nameof(construction));
_production = production ?? throw new ArgumentNullException(nameof(production));
_fogOfWar = fogOfWar ?? throw new ArgumentNullException(nameof(fogOfWar));
_victory = victory ?? throw new ArgumentNullException(nameof(victory));
}
public void Initialize(SimulationKernel kernel)
{
kernel?.Logger.LogInfo(
$"[{Name}] Initialized MS-1 skirmish AI for slot {_aiPlayerId} " +
$"(intent path via the peer ingress, cadence {DecisionTickInterval} ticks).");
}
/// <summary>
/// The fixed-cadence decision loop. Registered after Combat and before
/// Victory, so decisions read the post-combat state of the executing
/// tick; a decided match ends every further order.
/// </summary>
public void ExecuteTick(Tick tick)
{
if (tick.Value % DecisionTickInterval != 0) return;
if (_victory.IsDecided) return;
Decide(tick.Value);
}
public void Shutdown()
{
}
// ------------------------------------------------------------------
// The decision loop (pure function of the committed state)
// ------------------------------------------------------------------
private void Decide(uint tick)
{
FactionId faction = _economy.GetSlotFaction(_aiPlayerId);
ref readonly PlayerEconomyState eco = ref _economy.GetPlayerEconomy(_aiPlayerId);
long credits = eco.AetheriumCredits;
int powerMargin = eco.PowerProvided - eco.PowerRequired;
// One ascending-index scan of the entity store collecting every
// fact the decisions below read (deterministic iteration order).
uint hqRaw = 0, refineryRaw = 0, barracksRaw = 0;
int hqCellX = -1, hqCellY = -1, refineryCellX = -1, refineryCellY = -1;
bool powerCompleted = false;
int builders = 0, harvesters = 0, combatCount = 0;
var combatRaws = new List<uint>();
var combatUnits = new List<UnitState>();
var idleHarvesterRaws = new List<uint>();
var harvesterRaws = new List<uint>();
var harvesterUnits = new List<UnitState>();
var sites = new List<SiteInfo>();
UnitState[] units = _entityManager.RawUnits;
int capacity = _entityManager.Capacity;
for (int i = 0; i < capacity; i++)
{
ref readonly UnitState u = ref units[i];
if (!u.IsActive || u.PlayerId != _aiPlayerId) continue;
uint raw = UnitCommandStateView.ToRawEntityId(u.Id);
if (raw == 0) continue;
// 16.3 (#44): a site already carries its definition role.
// Classify through the site register BEFORE building roles so
// an unfinished Refinery/HQ/etc. never becomes a completed
// producer or prerequisite in the planner.
if (_construction.TryGetSite(raw, out _, out _, out uint assignedBuilder))
{
sites.Add(new SiteInfo
{
CellX = GridCellOf(u.Transform.PositionX),
CellY = GridCellOf(u.Transform.PositionY),
AssignedBuilderRaw = assignedBuilder,
});
continue;
}
if (SimDefinitions.IsBuildingRole(u.Role))
{
switch (u.Role)
{
case UnitRole.HQ when hqRaw == 0:
hqRaw = raw;
hqCellX = GridCellOf(u.Transform.PositionX);
hqCellY = GridCellOf(u.Transform.PositionY);
break;
case UnitRole.Refinery when refineryRaw == 0:
refineryRaw = raw;
refineryCellX = GridCellOf(u.Transform.PositionX);
refineryCellY = GridCellOf(u.Transform.PositionY);
break;
case UnitRole.Barracks when barracksRaw == 0:
barracksRaw = raw;
break;
case UnitRole.Power:
powerCompleted = true;
break;
}
continue;
}
switch (u.Role)
{
case UnitRole.Builder:
builders++;
break;
case UnitRole.Harvester:
harvesters++;
harvesterRaws.Add(raw);
harvesterUnits.Add(u);
if (u.HarvestFieldId == 0 && !u.IsReturningCargo)
{
idleHarvesterRaws.Add(raw);
}
break;
default:
if (IsCombatRole(u.Role))
{
combatCount++;
combatRaws.Add(raw);
combatUnits.Add(u);
}
break;
}
}
// A slot without an HQ cannot run the D-077 opening loop (and a
// slot that owns nothing is defeated anyway): stay idle.
if (hqRaw == 0) return;
// ---- (1) Build order: Refinery, required Power plant, then
// Barracks, one site at a time (a single Builder cannot progress
// two sites). Power also preempts whenever the committed margin
// would drop below the profile reserve — "when the margin would
// go negative" with the demo profile's reserve of 0. ----
if (sites.Count == 0)
{
UnitRole next = refineryRaw == 0
? UnitRole.Refinery
: (barracksRaw == 0 ? UnitRole.Barracks : UnitRole.Unit);
if (next != UnitRole.Unit
&& SimDefinitions.TryGetBuilding(faction, next, out SimBuildingDefinition nextDef))
{
UnitRoleMask missingPrerequisites = _construction.GetMissingPrerequisiteRoles(
_aiPlayerId,
nextDef.PrerequisiteRoles);
bool missingRequiredPower = (missingPrerequisites & UnitRoleMask.Power) != 0;
bool needsPowerMargin = nextDef.PowerRequired > 0
&& powerMargin < nextDef.PowerRequired + _profile.TargetPowerMargin;
if (!powerCompleted && (missingRequiredPower || needsPowerMargin))
{
next = UnitRole.Power;
}
TryPlaceBuilding(faction, next, credits, hqCellX, hqCellY);
}
}
// ---- (2) Construction support: the assigned Builder must stand
// in Chebyshev reach <= 1 of the site footprint or the site
// pauses (ConstructionSystem remarks) — walk it there. ----
for (int s = 0; s < sites.Count; s++)
{
SiteInfo site = sites[s];
if (site.AssignedBuilderRaw == 0) continue;
EntityId builderId = UnitCommandStateView.ToEntityId(site.AssignedBuilderRaw);
if (!_entityManager.TryGetUnit(builderId, out UnitState builder)) continue;
int originX = site.CellX - 1;
int originY = site.CellY - 1;
if (IsInReachOfFootprint(
GridCellOf(builder.Transform.PositionX), GridCellOf(builder.Transform.PositionY),
originX, originY))
{
continue;
}
// Deterministic adjacent cell: the first footprint-free
// cell in Chebyshev reach 1 of the site rectangle — a fixed
// side can lie inside a neighbour building, which is
// impassable since the Truppenführung sprint and would
// stall the site forever.
if (!TryFindFootprintAdjacentCell(originX, originY, out int targetX, out int targetY))
{
continue;
}
if (builder.IsMoving && builder.TargetGridPos.IsValid
&& builder.TargetGridPos.X == targetX && builder.TargetGridPos.Y == targetY)
{
continue; // already walking there
}
Submit(new MovePayload(
new[] { site.AssignedBuilderRaw }, SimFixed.FromInt(targetX), SimFixed.FromInt(targetY)));
}
// ---- (3) Replacement Builder at the HQ when none is alive. ----
if (builders == 0
&& SimDefinitions.TryGetUnit(faction, UnitRole.Builder, out SimUnitDefinition builderDef)
&& CountQueuedAt(hqRaw, builderDef.DefinitionId) == 0
&& credits >= builderDef.CostAE)
{
Submit(new QueueUnitPayload(hqRaw, builderDef.DefinitionId, 1));
}
// ---- (4) Economy: keep harvesters queued at the Refinery (the
// D-077 producer), send every idle own harvester to the own field
// and WALK harvesters into reach with explicit Move intents.
// This slice never submits SetRallyPoint; it does what a human
// player does and micros the harvesters into the economy's reach
// rule. That is a behavior choice, NOT a validator limit: the
// rally point would be accepted. ProductionSystem.IsProducerRole
// reads UnitRole.Refinery out of SimDefinitions.AllUnits (both
// factions' Harvester carries producerRole: Refinery since D-077)
// instead of a hardcoded list, precisely so the producer move
// could not strand it. Using the rally point here would change
// behavior and belongs in its own PR. ----
if (refineryRaw != 0)
{
// A field that can still be mined — see TryGetOwnFieldCell for
// what happens without the reserve test (issue #85).
bool haveField = TryGetOwnFieldCell(
hqCellX, hqCellY, mustHaveReserve: true,
out ushort ownFieldId, out int fieldX, out int fieldY);
// NOTHING LEFT TO MINE IS NOT THE SAME AS NOTHING LEFT TO DO,
// and the difference is the whole reason this gate sits inside
// the step instead of on it. Everything that needs a field —
// ordering more harvesters, sending idle ones out, walking them
// to the gather spot — stops. The RETURN leg does not: a
// harvester holding its last load has somewhere to take it, and
// an out-of-reach return order is HELD rather than dropped, so
// closing that distance stays the AI's job. Skipping the whole
// step would have stranded the final loads at the moment the
// map runs dry — a smaller defect than #85, and a new one.
if (haveField
&& SimDefinitions.TryGetUnit(faction, UnitRole.Harvester, out SimUnitDefinition harvesterDef))
{
int have = harvesters + CountQueuedAt(refineryRaw, harvesterDef.DefinitionId);
int batch = Math.Min(HarvesterQueueBatch, _profile.TargetHarvesterCount - have);
if (batch > 0 && credits >= (long)harvesterDef.CostAE * batch)
{
Submit(new QueueUnitPayload(refineryRaw, harvesterDef.DefinitionId, (ushort)batch));
}
}
if (haveField && idleHarvesterRaws.Count > 0)
{
idleHarvesterRaws.Sort();
SubmitEntityList(idleHarvesterRaws,
ids => CommandIntent.Create(new HarvestPayload(ids, ownFieldId)));
}
// Escort targets: the gather leg wants a cell in harvest reach
// of the field (Chebyshev 1 of the field cell) AND in deposit
// reach of the Refinery footprint, so the full auto-cycle
// (gather -> return -> gather, EconomySystem remarks) closes
// in one spot; the return leg wants any cell adjacent to the
// footprint. Deterministic ascending picks.
int refineryOriginX = refineryCellX - 1;
int refineryOriginY = refineryCellY - 1;
int gatherX = 0, gatherY = 0;
if (haveField)
{
if (!TryFindDualReachCell(fieldX, fieldY, refineryOriginX, refineryOriginY,
out gatherX, out gatherY))
{
// The field cell itself always satisfies harvest reach.
gatherX = fieldX;
gatherY = fieldY;
}
}
int returnX, returnY;
bool haveReturnSpot = TryFindFootprintAdjacentCell(refineryOriginX, refineryOriginY,
out returnX, out returnY);
var gatherEscort = new List<uint>();
var returnEscort = new List<uint>();
for (int i = 0; i < harvesterUnits.Count; i++)
{
UnitState harvester = harvesterUnits[i];
int cellX = GridCellOf(harvester.Transform.PositionX);
int cellY = GridCellOf(harvester.Transform.PositionY);
if (harvester.IsReturningCargo)
{
// The return leg resolves only in deposit reach of an
// own Refinery (the economy's documented footprint
// reach rule); walk there when held out of reach.
if (!haveReturnSpot || harvester.CargoAE <= 0) continue;
if (IsInDepositReach(cellX, cellY, refineryCellX, refineryCellY)) continue;
if (AlreadyHeadingTo(in harvester, returnX, returnY)) continue;
returnEscort.Add(harvesterRaws[i]);
}
else
{
// Out-of-reach harvest orders are HELD, never dropped
// (EconomySystem) — closing the distance is the AI's
// job, exactly like a human's move click. With no
// mineable field there is nothing to close a distance
// to, and walking them to the empty one is the loop
// this whole change exists to end.
if (!haveField) continue;
if (IsInFieldReach(cellX, cellY, fieldX, fieldY)) continue;
if (AlreadyHeadingTo(in harvester, gatherX, gatherY)) continue;
gatherEscort.Add(harvesterRaws[i]);
}
}
if (gatherEscort.Count > 0)
{
gatherEscort.Sort();
SubmitEntityList(gatherEscort,
ids => CommandIntent.Create(new MovePayload(ids, SimFixed.FromInt(gatherX), SimFixed.FromInt(gatherY))));
}
if (returnEscort.Count > 0)
{
returnEscort.Sort();
SubmitEntityList(returnEscort,
ids => CommandIntent.Create(new MovePayload(ids, SimFixed.FromInt(returnX), SimFixed.FromInt(returnY))));
}
}
// ---- (5) Army: keep infantry queued up to the cap as funds allow. ----
if (barracksRaw != 0
&& SimDefinitions.TryGetUnit(faction, ProducedCombatRole, out SimUnitDefinition infantryDef))
{
int have = combatCount + CountQueuedAt(barracksRaw, infantryDef.DefinitionId);
int batch = Math.Min(InfantryQueueBatch, _profile.TargetArmySize - have);
if (batch > 0 && credits >= (long)infantryDef.CostAE * batch)
{
Submit(new QueueUnitPayload(barracksRaw, infantryDef.DefinitionId, (ushort)batch));
}
}
// Cells of the visible ARMED enemies, collected once per decision.
// A local list, not a field: the system stays a pure function of
// the committed state, and nothing survives the decision.
//
// IT IS COLLECTED BEFORE THE POSTURE, and it has to be. The posture
// now answers "is the base under attack", which is a question about
// this list — and gathering it inside the per-unit loop below, where
// it used to live, would have meant asking after the answer was
// needed.
//
// TWO RULES SHARE IT, SO TWO RULES OPEN IT. The gate used to read
// RetreatHealthPercent alone; leaving it that way would have let
// retreat-off switch the defence off in silence, and the lab's
// `retreat-off` candidate would then measure something other than
// its name.
List<long> threatCells = null;
List<uint> threatRaws = null;
if (_profile.Profile.RetreatHealthPercent > 0 || _profile.Profile.DefendHomeCells > 0)
{
threatCells = new List<long>();
threatRaws = new List<uint>();
CollectVisibleThreats(threatCells, threatRaws);
}
// ---- (6) Army: resolve one posture for the army, one GOAL per
// unit, then submit the resulting orders grouped. See the three
// steps below; the rules are the ones the previous whole-army
// block applied, plus the defence r8 adds to the catalogue. ----
ArmyPosture posture = ResolveArmyPosture(
faction, barracksRaw, combatCount, combatUnits, hqCellX, hqCellY, threatCells);
if (_goalObserver != null) ReportArmyGoal(tick, in posture);
if (posture.Engages)
{
var assignments = new List<UnitAssignment>(combatUnits.Count);
for (int i = 0; i < combatUnits.Count; i++)
{
UnitState unit = combatUnits[i];
assignments.Add(ResolveUnitAssignment(
combatRaws[i], in unit, in posture, hqCellX, hqCellY, threatCells, threatRaws, tick));
}
SubmitAssignments(assignments, combatUnits);
}
}
// ------------------------------------------------------------------
// Army: posture -> per-unit assignment -> grouped submission
//
// THREE STEPS, because one whole-army order cannot express what the
// army has to do. The previous shape computed a single target and a
// single destination for every living combat unit, which is why
// "this one wounded unit turns back", "reinforcements wait at a
// staging cell" and "aim before the squad threshold is reached"
// could not be written down at all — and why a defence branch that
// switched the WHOLE army's destination every cadence produced 23 %
// more intents and a worse match (behaviour journal V002).
//
// The split is: what the army does (posture, derived from the
// committed state, never stored), what each unit does (assignment),
// and how that reaches the ingress (grouping, so N units sharing an
// order still cost ONE intent). The rules themselves are unchanged
// here: this shape reproduces the canonical match tick for tick.
// ------------------------------------------------------------------
/// <summary>
/// What the army as a whole is doing this decision. Derived fresh
/// every cadence from the committed state — the system stays
/// stateless, so there is nothing here to serialize.
/// </summary>
private struct ArmyPosture
{
/// <summary>
/// False when the army does not act at all: below the squad
/// threshold, or the own slot has no committed team view (only
/// slots below <see cref="FogOfWarSystem.TeamCount"/> do).
/// </summary>
public bool Engages;
/// <summary>The scored target the army shoots at; 0 when nothing enemy is visible.</summary>
public uint TargetRaw;
/// <summary>Where the army walks: the target's cell, else the enemy start area; -1 while the army does not act.</summary>
public int MoveCellX;
/// <summary>See <see cref="MoveCellX"/>.</summary>
public int MoveCellY;
/// <summary>
/// Where reinforcements gather before they march; -1 when waves are
/// off (<see cref="AiProfile.WaveSize"/> 1) or the army does not act.
/// <para>
/// Derived from the own HQ and the ENEMY START AREA, never from the
/// current target cell. That is deliberate: the target moves every
/// cadence, so a staging point derived from it would move too, and
/// every unit waiting there would be re-ordered on every decision.
/// That is precisely the churn that sank <c>DefendBase</c> (journal
/// V002, +23 % intents), and the intents-per-1000-ticks column is
/// the first number to look at here.
/// </para>
/// </summary>
public int StagingCellX;
/// <summary>See <see cref="StagingCellX"/>.</summary>
public int StagingCellY;
/// <summary>
/// True when what waits AT the staging cell is enough for the wave
/// to march — since r6 that is a sum of combat points, and only on
/// the off path (<see cref="AiProfile.WaveStrengthPoints"/> 0) a
/// count of units. Always true while waves are off entirely
/// (<see cref="AiProfile.WaveSize"/> 1), where every unit is its
/// own wave.
/// </summary>
public bool WaveReady;
/// <summary>
/// The own headquarters cell — where a defender walks. Static for
/// the whole match, which is the property the rule is built on: a
/// destination that does not move produces ONE order and not a
/// stream of them.
/// </summary>
public int HomeCellX;
/// <summary>See <see cref="HomeCellX"/>.</summary>
public int HomeCellY;
/// <summary>
/// A visible ARMED enemy stands within
/// <see cref="AiProfile.DefendHomeCells"/> of the headquarters, so
/// the units still waiting in the ring break off (r8). Always false
/// while the rule is off, which is what keeps that path identical.
/// </summary>
public bool HomeThreatened;
// ---- what the verdict above was reached FROM ----
//
// Not inputs to any rule: every one of these is already worked out
// where the gate is asked, and carrying it out of that method is
// what lets an observer say "1.060 of 1.200" instead of "waits".
// Nothing below is read by a decision, which is why adding them
// cannot move a single tick.
/// <summary>Which rule the gate answered with — the unit of measure of <see cref="WaveThreshold"/>.</summary>
public WaveGateMode WaveMode;
/// <summary>Living combat units inside the staging ring; 0 while waves are off.</summary>
public int Gathered;
/// <summary>Living combat units outside the ring — out with an earlier wave.</summary>
public int Committed;
/// <summary>Summed combat points of the gathered units.</summary>
public long GatheredStrength;
/// <summary>What the ring has to hold before the wave marches, already capped by what production can still deliver.</summary>
public long WaveThreshold;
}
/// <summary>
/// One unit's orders for this decision. The two slots are
/// INDEPENDENT on purpose — a unit can be told to shoot at one thing
/// and to stand somewhere else, and either half can be "no explicit
/// order, leave the standing one alone" (<see cref="AttackTargetRaw"/>
/// 0 hands the pick to the D-087 auto-acquisition,
/// <see cref="MoveCellX"/> < 0 leaves the unit where it walks).
/// </summary>
private struct UnitAssignment
{
public uint EntityRaw;
public uint AttackTargetRaw;
public int MoveCellX;
public int MoveCellY;
}
/// <summary>
/// The army's posture: at
/// <see cref="AiFactionProfile.AttackSquadThreshold"/> living combat
/// units the army marches on the enemy start area, and the best
/// visible enemy (integer score, committed view only) becomes the
/// shared target and the destination. No attack-move exists (GB-002),
/// but auto-acquisition does since D-087 — an explicit order simply
/// outranks it and is never retargeted.
/// </summary>
private ArmyPosture ResolveArmyPosture(
FactionId faction, uint barracksRaw, int combatCount, List<UnitState> combatUnits,
int hqCellX, int hqCellY, List<long> threatCells)
{
var posture = new ArmyPosture
{
Engages = combatCount >= _profile.AttackSquadThreshold && _aiPlayerId < _fogOfWar.TeamCount,
MoveCellX = -1,
MoveCellY = -1,
StagingCellX = -1,
StagingCellY = -1,
WaveReady = true,
HomeCellX = hqCellX,
HomeCellY = hqCellY,
HomeThreatened = IsHomeThreatened(hqCellX, hqCellY, threatCells),
};
if (!posture.Engages) return posture;
posture.TargetRaw = FindBestVisibleEnemyByScore(combatUnits, out int targetCellX, out int targetCellY);
if (posture.TargetRaw != 0)
{
posture.MoveCellX = targetCellX;
posture.MoveCellY = targetCellY;
}
else
{
GetEnemyStartAreaCell(hqCellX, hqCellY, out posture.MoveCellX, out posture.MoveCellY);
}
// The staging cell is resolved whenever the army acts, because
// BOTH rules need it: it is where a wave gathers and where a
// wounded unit walks back to. Resolving it is pure arithmetic over
// static map knowledge — with every rule switched off it changes
// nothing, which is what keeps the off path byte-identical.
GetStagingCell(hqCellX, hqCellY, out posture.StagingCellX, out posture.StagingCellY);
// ---- waves, and the off setting that keeps this reproducible ----
//
// waveSize 1 leaves WaveReady at true, so every unit marches and
// the shipped-before behaviour is not "the same result through new
// code" but the same decision it always took. That is what makes
// the comparison run one-sided (finding M001): identical binary,
// one profile value apart.
int waveSize = EffectiveWaveSize();
if (waveSize <= 1) return posture;
posture.WaveMode = WaveGateMode.Count;
int gathered = 0;
int committed = 0;
long gatheredStrength = 0;
for (int i = 0; i < combatUnits.Count; i++)
{
UnitState unit = combatUnits[i];
if (IsCommittedToTheWave(in unit, hqCellX, hqCellY))
{
committed++;
}
else
{
gathered++;
gatheredStrength += CombatStrength.Of(faction, unit.Role, unit.CurrentHealth);
}
}
// ---- the wave marches on STRENGTH, not on a head count ----
//
// A count does not know what a head is worth. Twelve Legion
// recruits weigh 528 points against twelve Alliance riflemen's
// 1.200, and the count calls both "a full wave" — so the Legion
// attacks at 44 % of the strength the same rule gives the Alliance,
// and pays for it in the loss column.
//
// waveStrengthPoints 0 skips this and leaves the count below
// untouched, bit for bit. That off setting is not politeness: a
// rule that lives only in C# reaches BOTH sides of a self-play
// match, and "later decided, more losses" then cannot be told from
// "two stronger armies" (finding M001).
//
// The second half of the condition is a guard, not a rule: a
// produced role worth 0 points would make the reachability cap
// meaningless (nothing production adds could ever close a gap), so
// the count path answers instead of a strength path that cannot.
// No shipped faction hits it — both Barracks build an armed unit.
int wavePoints = _profile.Profile.WaveStrengthPoints;
int producedStrength = wavePoints > 0
? CombatStrength.OfFullHealth(faction, ProducedCombatRole)
: 0;
posture.Gathered = gathered;
posture.Committed = committed;
posture.GatheredStrength = gatheredStrength;
if (wavePoints > 0 && producedStrength > 0)
{
posture.WaveMode = WaveGateMode.Strength;
posture.WaveReady = WaveStrengthGate.IsReady(
wavePoints, gatheredStrength, gathered, committed, producedStrength,
_profile.TargetArmySize, canProduce: barracksRaw != 0,
out posture.WaveThreshold);
return posture;
}
// The wave waits for what production can still deliver, not for a
// fixed twelve.
//
// Every survivor of an earlier wave standing outside the ring is a
// unit the next wave will never get: the army cap counts it, so the
// barracks refills to TargetArmySize MINUS the survivors, and the
// count inside the ring can never reach a wave size equal to the
// cap again. One survivor that walks into an empty enemy start area
// and does not die is enough — measured consequence: eleven units
// stand at the staging cell until the time limit while a single
// unit holds the front alone.
//
// EffectiveWaveSize already refuses a wave production can never
// deliver; this is the same rule one step further, applied to what
// production can deliver RIGHT NOW instead of in principle. The
// floor of 1 keeps the wave launchable when more units are out than
// the cap allows for at home — the rest are already fighting.
int reachable = _profile.TargetArmySize - committed;
if (reachable < 1) reachable = 1;
int threshold = waveSize < reachable ? waveSize : reachable;
posture.WaveThreshold = threshold;
posture.WaveReady = gathered >= threshold;
return posture;
}
/// <summary>
/// The role the Barracks keeps queueing in step (5) — the one unit type
/// production can actually add to a gathering wave, and therefore the
/// one whose full-health strength says what "one more unit" is worth to
/// the wave threshold.
/// <para>
/// TWO PLACES HAVE TO AGREE ON IT, so they read the same constant
/// rather than the same literal twice. A test could only assert the
/// agreement after the fact; sharing the constant means they cannot
/// disagree in the first place, which is the difference between a
/// checked invariant and an enforced one.
/// </para>
/// </summary>
private const UnitRole ProducedCombatRole = UnitRole.BasicInfantry;
/// <summary>
/// The wave size actually used, clamped to the army cap.
/// <para>
/// Without the clamp a profile with <c>waveSize</c> above
/// <see cref="AiFactionProfile.TargetArmySize"/> would wait for a wave
/// production can never deliver, and the army would stand at the
/// staging cell until the time limit. The clamp is not a tuning
/// decision, it is the guard against a profile that cannot work.
/// </para>
/// </summary>
private int EffectiveWaveSize()
{
int waveSize = _profile.Profile.WaveSize;
return waveSize > _profile.TargetArmySize ? _profile.TargetArmySize : waveSize;
}
/// <summary>
/// The staging cell: <see cref="AiProfile.StagingDistanceCells"/> cells
/// from the own HQ along the straight line toward the enemy start area,
/// clamped into the grid. Static map knowledge on both ends, so this
/// cell is the SAME for the whole match — a unit ordered there is not
/// re-ordered on the next cadence.
/// <para>
/// Integer division truncates, which is deterministic and identical on
/// both machines; that is the only property that matters here.
/// </para>
/// </summary>
private void GetStagingCell(int hqCellX, int hqCellY, out int cellX, out int cellY)
{
GetEnemyStartAreaCell(hqCellX, hqCellY, out int enemyX, out int enemyY);
int distance = _profile.Profile.StagingDistanceCells;
int dx = enemyX - hqCellX;
int dy = enemyY - hqCellY;
int span = Math.Max(Math.Abs(dx), Math.Abs(dy));
if (span <= distance)
{
// The enemy start area is nearer than the staging distance:
// there is nothing between base and target to gather at.
cellX = enemyX;
cellY = enemyY;
return;
}
cellX = ClampToGrid(hqCellX + (dx * distance / span));
cellY = ClampToGrid(hqCellY + (dy * distance / span));
}
/// <summary>
/// True when this unit is pulling out: wounded below
/// <see cref="AiProfile.RetreatHealthPercent"/> AND either an armed
/// enemy is within <see cref="AiProfile.RetreatDangerCells"/> or it is
/// already walking home.
/// <para>
/// THE SECOND HALF IS THE DAMPING, and it replaces the health
/// hysteresis the plan sketch asked for. That sketch wanted a unit to
/// re-enter the fight above an exit percentage — which presumes
/// healing, and MS-1 units never heal (<c>Repair</c> validates its
/// target as a completed BUILDING). With an unreachable exit the
/// wounded would pile up at home, keep occupying the army cap, and the
/// wave would never fill again. So the rule is: run home, and once you
/// are home you are an ordinary waiting unit again and leave with the
/// next wave, wounded or not. "Already walking home" is read off the
/// standing order — the AI's only memory, and one that survives
/// save/restore because it is part of the world, not beside it.
/// </para>
/// <para>
/// A retreating unit is pointed at its nearest visible armed enemy —
/// see <see cref="NearestThreatRaw"/>. This paragraph used to claim the
/// opposite (no explicit target, so D-087 keeps shooting at whatever
/// chases it) and the claim was wrong: submitting no attack intent
/// leaves the march target standing, and a standing valid target is
/// exactly what makes the auto-acquisition skip the unit.
/// </para>
/// </summary>
private bool IsRetreating(in UnitState unit, in ArmyPosture posture, List<long> threatCells)
{
int threshold = _profile.Profile.RetreatHealthPercent;
if (threshold <= 0 || threatCells == null || posture.StagingCellX < 0) return false;
if (unit.MaxHealth <= 0) return false;
if ((long)unit.CurrentHealth * 100 / unit.MaxHealth >= threshold) return false;
if (AlreadyHeadingTo(in unit, posture.StagingCellX, posture.StagingCellY)) return true;
int cellX = GridCellOf(unit.Transform.PositionX);
int cellY = GridCellOf(unit.Transform.PositionY);
int danger = _profile.Profile.RetreatDangerCells;
for (int i = 0; i < threatCells.Count; i++)
{
int threatX = (int)(uint)threatCells[i];
int threatY = (int)(threatCells[i] >> 32);
if (Math.Abs(cellX - threatX) <= danger && Math.Abs(cellY - threatY) <= danger) return true;
}
return false;
}
/// <summary>
/// Whether a visible ARMED enemy stands within
/// <see cref="AiProfile.DefendHomeCells"/> of the own headquarters — the
/// whole trigger of <see cref="GoalKind.DefendHome"/> (r8).
/// <para>
/// THREE PROPERTIES, EACH WITH A REASON. <b>Armed</b>, because a
/// harvester at the fence is not an attack, and reacting to anything
/// that moves is exactly what sank <c>DefendBase</c> (journal V002) —
/// <see cref="CollectVisibleThreats"/> filters that way already.
/// <b>Visible</b>, because anything else is a look through the fog.
/// <b>Around the headquarters</b>, not around any building: the entity
/// scan has that cell in hand, the observed and measured case is the one
/// at the headquarters, and "every building" would need a reason as well
/// as a wider scan. If the measurement later shows attacks on the
/// refinery going through the same way, that arrives as its own number.
/// </para>
/// <para>
/// A cheap ANY question, deliberately: which enemy is nearest is the
/// pursuer's business (<see cref="NearestThreatRaw"/>), and the trigger
/// does not need it.
/// </para>
/// </summary>
private bool IsHomeThreatened(int hqCellX, int hqCellY, List<long> threatCells)
{
int radius = _profile.Profile.DefendHomeCells;
if (radius <= 0 || threatCells == null) return false;
for (int i = 0; i < threatCells.Count; i++)
{
int threatX = (int)(uint)threatCells[i];
int threatY = (int)(threatCells[i] >> 32);
if (Math.Abs(hqCellX - threatX) <= radius && Math.Abs(hqCellY - threatY) <= radius) return true;
}
return false;
}
/// <summary>
/// The cells of every ARMED enemy in the team's committed view, packed
/// as <c>(y << 32) | x</c>. Unarmed entities are left out: a
/// harvester at the fence is not a reason to run, and treating it as
/// one is exactly the over-reaction that sank <c>DefendBase</c>
/// (journal V002 — "react to a real threat, not to anything that
/// moves").
/// </summary>
private void CollectVisibleThreats(List<long> cells, List<uint> raws)
{
var visible = new List<EntityId>();
_fogOfWar.GetVisibleEntities(_aiPlayerId, visible);