-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConstructionSystem.cs
More file actions
1661 lines (1509 loc) · 75.5 KB
/
Copy pathConstructionSystem.cs
File metadata and controls
1661 lines (1509 loc) · 75.5 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 Nova.Core;
using Nova.Simulation.CommandsV1;
using Nova.Simulation.Definitions;
using Nova.Simulation.Economy;
using Nova.Simulation.Pathfinding;
using Nova.Simulation.Snapshots;
using Nova.Simulation.State;
namespace Nova.Simulation.Construction
{
/// <summary>
/// Canonical construction system of the MS-1 production/construction
/// slice (docs/tech/SimulationCore.md section 2, phases 4 and 5):
/// building placement with state-dependent validation, construction
/// sites progressed by an assigned Builder, completion into building-role
/// entities, cancel/sell refunds, repair orders and the per-slot T2
/// unlock. Deterministic, pure integer/fixed-point, zero engine
/// dependencies. Replaces the unregistered prototype scaffolding
/// (pre-G1 reset; the retired ConstructionGrid is folded into this
/// system as a derived occupancy cache).
/// <para>
/// Tick order: the system covers phase 4 (and owns the phase-5 T2 flag)
/// and is registered AFTER the economy (phases 2/3) and BEFORE
/// pathfinding/movement (phase 6). Consequences, stated explicitly:
/// the low-power multiplier a site or repair reads inside one tick is
/// the balance recomputed by the economy in that same tick, and a
/// building completing in tick T feeds its power into the economy
/// recompute of tick T+1 (economy runs before construction within a
/// tick).
/// </para>
/// <para>
/// Placement (PlaceBuilding): the full cost is charged up front via
/// <see cref="PlayerEconomyState.TrySpendCredits"/> (a refusal rejects
/// the command with RejectedInsufficientResources before anything
/// mutates). The state-dependent validation order is fixed and
/// deterministic: unknown/foreign definition; footprint outside the
/// 128x128 grid or occupied cells; then D-104 terrain, influence,
/// building-clearance and Aetherium-field geometry (all
/// RejectedInvalidTarget); then missing prerequisite roles, the power rule
/// and site capacity (RejectedPrerequisitesNotMet).
/// The power rule: a building with PowerRequired > 0 may only be
/// placed while the owner's last committed balance
/// (previous tick's phase-2 recompute) covers the additional draw:
/// PowerProvided - PowerRequired >= PowerRequired of the new
/// building. The Refinery carries NO prerequisite since D-077 (the
/// classic loop start — quality/content/mvp-v1.json
/// startStatePerPlayer): placed through the command path it is gated by
/// funds, D-104 geometry and the power rule. D-103 represents every other
/// prerequisite as a fail-closed all-of mask over completed own roles (for
/// example Barracks needs HQ + Power, VehicleFactory needs Refinery +
/// Barracks, and Radar needs Power + Barracks).
/// <see cref="PlaceCompletedBuilding"/> bypasses gameplay placement
/// validation entirely, including D-104 geometry — it is the direct write
/// deterministic match setup uses.
/// </para>
/// <para>
/// Same-tick power stacking (documented, same precedent as the combat
/// duel asymmetry): the power rule reads the owner's last COMMITTED
/// balance (previous tick's phase-2 recompute), so several power-drawing
/// placements applied in the same tick can collectively oversubscribe
/// the grid — each one validates against the same stale balance. The
/// overshoot is deterministic and self-punishing via the low-power
/// multiplier from the next recompute on; a per-tick placement limit is
/// a registered Q-040 candidate.
/// </para>
/// <para>
/// Footprint sweep timing (documented, Q-040 candidate): the footprint
/// of a combat-destroyed placement is freed by this system's sweep in
/// the NEXT tick (phase 8 combat runs after phase 4), so a PlaceBuilding
/// applied in the tick immediately after the destruction can still find
/// the cell occupied — deterministic, and it resolves itself one tick
/// later.
/// </para>
/// <para>
/// Sites: a site is a live entity carrying its DEFINITION role (since
/// 16.3, #44 — the generic <see cref="UnitRole.Unit"/> slot was armed by
/// the weapon-table fallback, so every site shot). Combat also consults
/// <see cref="IsActiveSite"/> explicitly: even a DefensePlatform site is
/// neither an attacker nor a target before completion. The entity sits
/// at the footprint center with 1 HP of its definition's
/// MaxHealth — construction HP interpolation is deliberately NOT
/// modeled (provisional, Q-040 candidate). The readers that resolved a
/// site by its old generic role are compensated at the source: the
/// economy's power recompute skips sites through the bound
/// <see cref="IsActiveSite"/> lookup, and the view layer maps sites back
/// to the site look until completion. Builder assignment: the
/// PlaceBuilding payload names no builder, so the site auto-assigns the
/// own Builder with the lowest entity index (ascending-index scan,
/// deterministic); when the assigned builder dies the next tick
/// re-assigns the same way, and with no own Builder alive the site
/// pauses. A tick of progress happens only while the assigned builder
/// stands in reach — its grid cell within Chebyshev distance <= 1 of
/// the 3x3 footprint rectangle (same documented reach rule as the
/// economy). Progress accumulates in exact Q16.16:
/// <see cref="PlayerEconomyState.ProductionSpeedMultiplierQ16"/> raw per
/// progressed tick (1.0 at full power, exactly 0.5 under low power —
/// no rounding, 0.5 is exact in Q16.16, so low power means exactly one
/// tick of progress per two ticks). Completion restores full HP (the
/// role is already the definition's) and — for a ResearchLab — sets the
/// owner's T2 unlock (phase 5;
/// mvp-v1.json technology.researchLabCompletionUnlocksTier2; there are
/// no research upgrades, no research queue and no tier 3 in MS-1).
/// A site missing from the entity store is swept without refund; active
/// sites themselves are excluded as combat targets since 16.3 (#44).
/// </para>
/// <para>
/// Cancel/sell/repair (documented provisional economy rules, Q-040
/// candidates): CancelConstruction forfeits all progress and refunds
/// 75% of the cost (floor); Sell on a COMPLETED building refunds 50%
/// (floor) and despawns it; a running production queue on a sold or
/// destroyed building is lost without refund (production domain).
/// Repair assigns a Builder a standing repair order on an own completed
/// damaged building. In reach (same Chebyshev rule) the target gains
/// <see cref="RepairRateHpPerTick"/> HP per tick, or exactly
/// <see cref="LowPowerRepairRateHpPerTick"/> under low power, and pays an
/// exact cumulative integer share of 30% of its new price. At most one
/// reachable Builder may repair a target per tick; out-of-reach orders are
/// HELD, never dropped, and Stop clears them.
/// </para>
/// <para>
/// State (snapshot block <see cref="SnapshotBlockIds.Construction"/>,
/// v1): the T2 unlock bitmask, every site (definition, origin, site
/// entity, assigned builder, fixed-point progress), every completed
/// placement (definition, origin, entity) and every standing repair
/// order. The per-slot T2 flag lives here (not in the economy block)
/// because the ResearchLab completion that sets it is a construction
/// event — documented placement decision of this slice. The 128x128
/// occupancy grid is a DERIVED cache rebuilt from the placements on
/// restore (SimulationCore.md section 3: derived caches may be absent
/// when a test proves an identical rebuild); hit points stay with the
/// entities (entity store block) — exactly one home per value.
/// </para>
/// <para>
/// Footprints are impassable terrain (sprint Truppenführung): when the
/// host wires the pathfinding <see cref="CostField"/> (optional
/// constructor argument — the canonical hosts do), every footprint
/// change is mirrored into it as <see cref="CostField.ImpassableCost"/>/
/// <see cref="CostField.OpenCost"/> writes, and placing a footprint onto
/// mobile units pushes them onto the nearest free cell (restore skips
/// the push-out: the entity store restores afterwards, so the snapshot's
/// own units already satisfy the invariant).
/// </para>
/// </summary>
public sealed class ConstructionSystem : IStatefulSimSystem
{
/// <summary>Serialization version of the construction snapshot block.</summary>
public const byte StateVersion = 1;
/// <summary>MS-1 construction grid edge length in cells (SimulationCore.md section 10).</summary>
public const int GridSize = 128;
/// <summary>Format capacity for concurrent construction sites.</summary>
public const int MaxSites = 64;
/// <summary>Format capacity for completed building placements.</summary>
public const int MaxBuildings = 256;
/// <summary>Format capacity for standing repair orders.</summary>
public const int MaxRepairOrders = 64;
/// <summary>Maximum Chebyshev ring of the push-out cell search around a displaced unit.</summary>
public const int PushOutMaxRing = 8;
/// <summary>Refund percentage of CancelConstruction (provisional, Q-040 candidate; integer floor).</summary>
public const int CancelRefundPercent = 75;
/// <summary>Refund percentage of Sell on a completed building (provisional, Q-040 candidate; integer floor).</summary>
public const int SellRefundPercent = 50;
/// <summary>Provisional repair rate in HP per tick per repairing Builder (Q-040 candidate).</summary>
public const int RepairRateHpPerTick = 10;
/// <summary>Full rebuild-equivalent repair price as a percentage of the building's new price (D-104).</summary>
public const int RepairCostPercent = 30;
/// <summary>Maximum footprint-aware Chebyshev distance from an own construction anchor (D-104).</summary>
public const int BuildInfluenceRadiusCells = 8;
/// <summary>Minimum footprint-aware Chebyshev distance between construction footprints (D-104).</summary>
public const int MinimumBuildingDistanceCells = 2;
/// <summary>Allowed field-distance interval for a Refinery footprint (D-104).</summary>
public const int RefineryMinimumFieldDistanceCells = 1;
public const int RefineryMaximumFieldDistanceCells = 3;
/// <summary>Minimum field distance for every non-Refinery building footprint (D-104).</summary>
public const int MinimumNonRefineryFieldDistanceCells = 2;
/// <summary>Repair rate in HP per tick while the owner's grid is in LOW POWER (C4, Sprint 16.6).</summary>
public const int LowPowerRepairRateHpPerTick = 5;
private struct SiteState
{
public bool IsActive;
public ushort BuildingDefId;
public ushort OriginX;
public ushort OriginY;
public uint RawEntityId;
public uint AssignedBuilderRaw; // 0 = none assigned
public int ProgressRaw; // Q16.16 ticks progressed
}
private struct PlacementState
{
public bool IsActive;
public ushort BuildingDefId;
public ushort OriginX;
public ushort OriginY;
public uint RawEntityId;
}
private struct RepairOrderState
{
public bool IsActive;
public uint BuilderRaw;
public uint TargetRaw;
}
private readonly EntityManager _entityManager;
private readonly EconomySystem _economy;
private readonly SiteState[] _sites;
private readonly PlacementState[] _buildings;
private readonly RepairOrderState[] _repairs;
private readonly bool[] _t2Unlocked;
private INovaLogger _logger = NullNovaLogger.Instance;
// Derived occupancy cache (rebuilt from the placements on restore).
private readonly byte[] _occupied;
// Pathfinding cost field the footprints are mirrored into (optional:
// hosts without movement — pure economy/construction test rigs —
// leave it null and footprints simply do not block pathing there).
private readonly CostField _costField;
public string Name => "ConstructionSystem";
public ushort StateBlockId => SnapshotBlockIds.Construction;
public ConstructionSystem(EntityManager entityManager, EconomySystem economy, CostField costField = null)
{
_entityManager = entityManager ?? throw new ArgumentNullException(nameof(entityManager));
_economy = economy ?? throw new ArgumentNullException(nameof(economy));
_sites = new SiteState[MaxSites];
_buildings = new PlacementState[MaxBuildings];
_repairs = new RepairOrderState[MaxRepairOrders];
_t2Unlocked = new bool[EconomySystem.MaxPlayers];
_occupied = new byte[GridSize * GridSize];
_costField = costField;
// 16.3 (#44): a site carries its definition role, so the power
// and capacity scans can no longer skip sites by role. Both use
// this authoritative register; binding here means no host can
// forget the dependency.
_economy.BindSiteLookup(IsActiveSite);
}
public void Initialize(SimulationKernel kernel)
{
_logger = kernel?.Logger ?? NullNovaLogger.Instance;
_logger.LogInfo(
$"[{Name}] Initialized canonical construction ({GridSize}x{GridSize} grid, {MaxSites} sites, {MaxBuildings} placements).");
}
public void Shutdown()
{
}
// ------------------------------------------------------------------
// Read-only queries
// ------------------------------------------------------------------
/// <summary>True when the slot completed a ResearchLab (phase-5 T2 unlock; mvp-v1.json technology model).</summary>
public bool IsT2Unlocked(byte playerSlot)
{
return playerSlot < EconomySystem.MaxPlayers && _t2Unlocked[playerSlot];
}
/// <summary>True when the grid cell is inside the map and not covered by any placement footprint.</summary>
public bool IsCellFree(int x, int y)
{
if (x < 0 || y < 0 || x >= GridSize || y >= GridSize) return false;
return _occupied[y * GridSize + x] == 0;
}
/// <summary>Number of active construction sites.</summary>
public int SiteCount
{
get
{
int count = 0;
for (int i = 0; i < MaxSites; i++) if (_sites[i].IsActive) count++;
return count;
}
}
/// <summary>Number of completed building placements.</summary>
public int BuildingCount
{
get
{
int count = 0;
for (int i = 0; i < MaxBuildings; i++) if (_buildings[i].IsActive) count++;
return count;
}
}
/// <summary>Read-only snapshot of one site's state for tests and diagnostics.</summary>
public bool TryGetSite(uint rawEntityId, out ushort buildingDefId, out int progressRaw, out uint assignedBuilderRaw)
{
int index = IndexOfSite(rawEntityId);
if (index >= 0)
{
buildingDefId = _sites[index].BuildingDefId;
progressRaw = _sites[index].ProgressRaw;
assignedBuilderRaw = _sites[index].AssignedBuilderRaw;
return true;
}
buildingDefId = 0;
progressRaw = 0;
assignedBuilderRaw = 0;
return false;
}
/// <summary>True when the entity is a COMPLETED building placement tracked by this system (never a site).</summary>
public bool IsCompletedPlacement(uint rawEntityId)
{
return IndexOfBuilding(rawEntityId) >= 0;
}
/// <summary>
/// True while the entity is an unfinished site (16.3, #44: sites now
/// carry their definition role, so role alone no longer tells a site
/// apart). Bound into the economy's power and capacity scans via
/// <see cref="EconomySystem.BindSiteLookup"/>; also the read the
/// presentation layer needs to keep the site look until completion.
/// </summary>
public bool IsActiveSite(EntityId id)
{
return IndexOfSite(UnitCommandStateView.ToRawEntityId(id)) >= 0;
}
/// <summary>
/// Missing completed own building roles for an all-of prerequisite.
/// Unknown bits stay missing (fail closed).
/// </summary>
public UnitRoleMask GetMissingPrerequisiteRoles(byte playerSlot, UnitRoleMask requiredRoles)
{
if (requiredRoles == UnitRoleMask.None) return UnitRoleMask.None;
UnitRoleMask completedRoles = UnitRoleMask.None;
for (int i = 0; i < MaxBuildings; i++)
{
if (!_buildings[i].IsActive) continue;
if (!SimDefinitions.TryGetBuilding(_buildings[i].BuildingDefId, out SimBuildingDefinition def)) continue;
EntityId id = UnitCommandStateView.ToEntityId(_buildings[i].RawEntityId);
if (!_entityManager.TryGetUnit(id, out UnitState unit) || unit.PlayerId != playerSlot) continue;
completedRoles |= RoleMask(def.Role);
}
return requiredRoles & ~completedRoles;
}
/// <summary>True when the slot owns every COMPLETED building role in the all-of mask.</summary>
public bool HasFinishedBuildings(byte playerSlot, UnitRoleMask requiredRoles)
{
return GetMissingPrerequisiteRoles(playerSlot, requiredRoles) == UnitRoleMask.None;
}
/// <summary>True when the slot owns a COMPLETED building of the given role (prerequisite scans).</summary>
public bool HasFinishedBuilding(byte playerSlot, UnitRole role)
{
UnitRoleMask roleMask = RoleMask(role);
return roleMask != UnitRoleMask.None && HasFinishedBuildings(playerSlot, roleMask);
}
private static UnitRoleMask RoleMask(UnitRole role)
{
int bit = (int)role;
return bit >= 0 && bit < 32
? (UnitRoleMask)(1u << bit)
: UnitRoleMask.None;
}
// ------------------------------------------------------------------
// State-dependent validation (no mutation; the command view calls
// these at the target tick in the documented fixed order)
// ------------------------------------------------------------------
/// <summary>
/// Full state-dependent placement validation in fixed order: unknown
/// definition, foreign-faction definition, out-of-map footprint and
/// occupied cells; then terrain, build influence, one-cell building
/// ring and field spacing (RejectedInvalidTarget); then prerequisite
/// roles, power rule and site capacity (RejectedPrerequisitesNotMet).
/// Cost is the executor's separate check
/// (RejectedInsufficientResources) and runs BEFORE this.
/// </summary>
public CommandResultCode ValidatePlacement(byte playerSlot, ushort buildingDefId, int originX, int originY)
{
if (!SimDefinitions.TryGetBuilding(buildingDefId, out SimBuildingDefinition def))
{
return CommandResultCode.RejectedInvalidTarget;
}
if (def.Faction != _economy.GetSlotFaction(playerSlot))
{
// Definition ids are faction-resolved: a slot may only place
// its own faction's rows. A foreign id is a known id naming
// content the slot cannot build — an invalid target, exactly
// like an unknown one.
return CommandResultCode.RejectedInvalidTarget;
}
if (!FootprintInsideMap(originX, originY) || !FootprintFree(originX, originY))
{
return CommandResultCode.RejectedInvalidTarget;
}
if (!FootprintIsWalkable(originX, originY)
|| !IsInsideBuildInfluence(playerSlot, originX, originY)
|| !HasMinimumBuildingSpacing(originX, originY)
|| !HasValidFieldSpacing(def.Role, originX, originY))
{
return CommandResultCode.RejectedInvalidTarget;
}
if (!HasFinishedBuildings(playerSlot, def.PrerequisiteRoles))
{
return CommandResultCode.RejectedPrerequisitesNotMet;
}
ref readonly PlayerEconomyState eco = ref _economy.GetPlayerEconomy(playerSlot);
if (def.PowerRequired > 0 && eco.PowerProvided - eco.PowerRequired < def.PowerRequired)
{
return CommandResultCode.RejectedPrerequisitesNotMet;
}
if (FreeSiteIndex() < 0)
{
return CommandResultCode.RejectedPrerequisitesNotMet;
}
return CommandResultCode.Applied;
}
/// <summary>CancelConstruction legality: the entity must be an active site owned by the slot.</summary>
public CommandResultCode ValidateCancel(byte playerSlot, uint rawEntityId)
{
int index = IndexOfSite(rawEntityId);
if (index < 0) return CommandResultCode.RejectedInvalidTarget;
return OwnsEntity(playerSlot, rawEntityId)
? CommandResultCode.Applied
: CommandResultCode.RejectedInvalidTarget;
}
/// <summary>Sell legality: the entity must be a COMPLETED building placement owned by the slot.</summary>
public CommandResultCode ValidateSell(byte playerSlot, uint rawEntityId)
{
int index = IndexOfBuilding(rawEntityId);
if (index < 0) return CommandResultCode.RejectedInvalidTarget;
return OwnsEntity(playerSlot, rawEntityId)
? CommandResultCode.Applied
: CommandResultCode.RejectedInvalidTarget;
}
/// <summary>
/// Repair legality in fixed order: every actor must be a live Builder,
/// the target must be an own completed placement that is damaged, and
/// the repair-order capacity must absorb the new orders.
/// </summary>
public CommandResultCode ValidateRepair(byte playerSlot, uint[] actorRaws, uint targetRaw)
{
for (int i = 0; i < actorRaws.Length; i++)
{
EntityId id = UnitCommandStateView.ToEntityId(actorRaws[i]);
if (!_entityManager.TryGetUnit(id, out UnitState unit) || unit.Role != UnitRole.Builder)
{
return CommandResultCode.RejectedInvalidTarget;
}
}
int targetIndex = IndexOfBuilding(targetRaw);
if (targetIndex < 0 || !OwnsEntity(playerSlot, targetRaw))
{
return CommandResultCode.RejectedInvalidTarget;
}
EntityId targetId = UnitCommandStateView.ToEntityId(targetRaw);
ref readonly UnitState target = ref _entityManager.GetUnitRef(targetId);
if (target.CurrentHealth >= target.MaxHealth)
{
return CommandResultCode.RejectedInvalidTarget; // nothing to repair
}
int newOrders = 0;
for (int i = 0; i < actorRaws.Length; i++)
{
if (IndexOfRepairByBuilder(actorRaws[i]) < 0) newOrders++;
}
int active = 0;
for (int i = 0; i < MaxRepairOrders; i++) if (_repairs[i].IsActive) active++;
if (active + newOrders > MaxRepairOrders)
{
return CommandResultCode.RejectedPrerequisitesNotMet;
}
return CommandResultCode.Applied;
}
// ------------------------------------------------------------------
// Application (command view Apply path and programmatic match
// setup / AI; every mutating entry point re-validates or documents
// its bypass)
// ------------------------------------------------------------------
/// <summary>
/// Programmatic placement (command Apply path, AI): validates exactly
/// as <see cref="ValidatePlacement"/> plus the credit spend, then
/// charges the full cost, occupies the footprint, spawns the site
/// entity (definition role, 1 HP) and auto-assigns the lowest-index
/// own Builder. Returns false without mutating when any check fails.
/// </summary>
public bool TryPlaceBuilding(byte playerSlot, ushort buildingDefId, int originX, int originY)
{
if (ValidatePlacement(playerSlot, buildingDefId, originX, originY) != CommandResultCode.Applied)
{
return false;
}
SimDefinitions.TryGetBuilding(buildingDefId, out SimBuildingDefinition def);
ref PlayerEconomyState eco = ref _economy.GetPlayerEconomy(playerSlot);
if (!eco.TrySpendCredits(def.CostAE))
{
return false;
}
CreateSite(playerSlot, in def, originX, originY);
return true;
}
/// <summary>
/// Match-setup placement of a COMPLETED building: bypasses cost and all
/// gameplay placement validation by contract, including D-104 terrain,
/// influence and spacing (callers are deterministic host content
/// wiring and explicit test setup). Applies the same completion effects as a
/// finished site: building-role entity at full HP, footprint occupied,
/// ResearchLab sets the T2 unlock. Returns EntityId.Invalid when the
/// definition is unknown, the footprint is blocked or the placement
/// capacity is exhausted.
/// </summary>
public EntityId PlaceCompletedBuilding(byte playerSlot, ushort buildingDefId, int originX, int originY)
{
if (!SimDefinitions.TryGetBuilding(buildingDefId, out SimBuildingDefinition def)) return EntityId.Invalid;
if (!FootprintInsideMap(originX, originY) || !FootprintFree(originX, originY)) return EntityId.Invalid;
int slot = FreeBuildingIndex();
if (slot < 0) return EntityId.Invalid;
EntityId id = SpawnBuildingEntity(playerSlot, in def, originX, originY, completed: true);
OccupyFootprint(originX, originY, pushOutUnits: true);
_buildings[slot] = new PlacementState
{
IsActive = true,
BuildingDefId = buildingDefId,
OriginX = (ushort)originX,
OriginY = (ushort)originY,
RawEntityId = UnitCommandStateView.ToRawEntityId(id),
};
if (def.Role == UnitRole.ResearchLab && playerSlot < EconomySystem.MaxPlayers)
{
_t2Unlocked[playerSlot] = true;
}
return id;
}
/// <summary>
/// Cancels a site: progress is forfeited, 75% of the cost is refunded
/// (floor), the site entity despawns and the footprint is freed.
/// Returns false when the entity is not an active site.
/// </summary>
public bool CancelConstruction(uint rawEntityId)
{
int index = IndexOfSite(rawEntityId);
if (index < 0) return false;
ref SiteState site = ref _sites[index];
SimDefinitions.TryGetBuilding(site.BuildingDefId, out SimBuildingDefinition def);
EntityId id = UnitCommandStateView.ToEntityId(rawEntityId);
if (_entityManager.TryGetUnit(id, out UnitState unit))
{
// 16.4: refunds obey the derived ceiling too — overflow is forfeit.
_economy.DepositCapped(unit.PlayerId, (long)def.CostAE * CancelRefundPercent / 100);
}
_entityManager.DespawnUnit(id);
FreeFootprint(site.OriginX, site.OriginY);
site.IsActive = false;
CompactSites();
return true;
}
/// <summary>
/// Sells a COMPLETED building: refunds 50% of the cost (floor),
/// despawns the entity and frees the footprint. A production queue on
/// the building is lost without refund (production domain sweep).
/// Returns false when the entity is not a completed placement.
/// </summary>
public bool SellBuilding(uint rawEntityId)
{
int index = IndexOfBuilding(rawEntityId);
if (index < 0) return false;
ref PlacementState placement = ref _buildings[index];
SimDefinitions.TryGetBuilding(placement.BuildingDefId, out SimBuildingDefinition def);
EntityId id = UnitCommandStateView.ToEntityId(rawEntityId);
if (_entityManager.TryGetUnit(id, out UnitState unit))
{
// 16.4: refunds obey the derived ceiling too — overflow is forfeit.
_economy.DepositCapped(unit.PlayerId, (long)def.CostAE * SellRefundPercent / 100);
}
_entityManager.DespawnUnit(id);
FreeFootprint(placement.OriginX, placement.OriginY);
placement.IsActive = false;
CompactBuildings();
return true;
}
/// <summary>Assigns (or overwrites) a Builder's standing repair order. Assumes validated input.</summary>
public void AssignRepairOrder(uint builderRaw, uint targetRaw)
{
int index = IndexOfRepairByBuilder(builderRaw);
if (index >= 0)
{
_repairs[index].TargetRaw = targetRaw;
return;
}
index = FreeRepairIndex();
if (index < 0) return; // validated callers never exceed capacity
_repairs[index] = new RepairOrderState { IsActive = true, BuilderRaw = builderRaw, TargetRaw = targetRaw };
}
/// <summary>Clears a Builder's standing repair order (Stop command); a no-op when none exists.</summary>
public void ClearRepairOrder(uint builderRaw)
{
int index = IndexOfRepairByBuilder(builderRaw);
if (index >= 0)
{
_repairs[index].IsActive = false;
CompactRepairOrders();
}
}
// ------------------------------------------------------------------
// Tick (phase 4, after the economy, before movement)
// ------------------------------------------------------------------
/// <summary>
/// Phase 4: sweeps placements whose entity died (sites abort without
/// refund, completed placements free their footprint), then progresses
/// every site with an in-reach Builder by the owner's exact Q16.16
/// speed multiplier, then processes standing repair orders — all in
/// strict ascending table order.
/// </summary>
public void ExecuteTick(Tick tick)
{
SweepDeadPlacements();
ProgressSites();
ProcessRepairOrders();
}
private void SweepDeadPlacements()
{
for (int i = 0; i < MaxSites; i++)
{
if (!_sites[i].IsActive) continue;
if (!_entityManager.IsValid(UnitCommandStateView.ToEntityId(_sites[i].RawEntityId)))
{
FreeFootprint(_sites[i].OriginX, _sites[i].OriginY);
_sites[i].IsActive = false; // destroyed site: aborted, no refund
}
}
for (int i = 0; i < MaxBuildings; i++)
{
if (!_buildings[i].IsActive) continue;
if (!_entityManager.IsValid(UnitCommandStateView.ToEntityId(_buildings[i].RawEntityId)))
{
FreeFootprint(_buildings[i].OriginX, _buildings[i].OriginY);
_buildings[i].IsActive = false;
}
}
CompactSites();
CompactBuildings();
}
private void ProgressSites()
{
for (int i = 0; i < MaxSites; i++)
{
ref SiteState site = ref _sites[i];
if (!site.IsActive) continue;
EntityId siteId = UnitCommandStateView.ToEntityId(site.RawEntityId);
if (!_entityManager.TryGetUnit(siteId, out UnitState siteUnit)) continue; // swept next tick
SimDefinitions.TryGetBuilding(site.BuildingDefId, out SimBuildingDefinition def);
// Builder (re-)assignment: the assigned builder must be alive,
// still carry the Builder role and still belong to the site
// owner (P2-2 defense-in-depth against tampered snapshots and
// stale assignments); a dead, role-changed or foreign builder
// is replaced by the lowest-index own Builder.
if (site.AssignedBuilderRaw != 0)
{
EntityId assignedId = UnitCommandStateView.ToEntityId(site.AssignedBuilderRaw);
bool usable = _entityManager.TryGetUnit(assignedId, out UnitState assigned)
&& assigned.Role == UnitRole.Builder
&& assigned.PlayerId == siteUnit.PlayerId;
if (!usable)
{
site.AssignedBuilderRaw = 0;
}
}
if (site.AssignedBuilderRaw == 0)
{
site.AssignedBuilderRaw = FindLowestIndexBuilder(siteUnit.PlayerId);
}
if (site.AssignedBuilderRaw == 0) continue; // no own Builder: paused
EntityId builderId = UnitCommandStateView.ToEntityId(site.AssignedBuilderRaw);
ref readonly UnitState builder = ref _entityManager.GetUnitRef(builderId);
if (!IsInReachOfFootprint(in builder, site.OriginX, site.OriginY)) continue; // held, not dropped
ref readonly PlayerEconomyState eco = ref _economy.GetPlayerEconomy(siteUnit.PlayerId);
site.ProgressRaw += eco.ProductionSpeedMultiplierQ16.RawValue;
if (site.ProgressRaw >= (def.BuildTicks << 16))
{
CompleteSite(i, in def, siteUnit.PlayerId);
}
}
CompactSites();
}
private void CompleteSite(int siteIndex, in SimBuildingDefinition def, byte ownerSlot)
{
uint rawEntityId = _sites[siteIndex].RawEntityId;
ushort originX = _sites[siteIndex].OriginX;
ushort originY = _sites[siteIndex].OriginY;
_sites[siteIndex].IsActive = false;
EntityId id = UnitCommandStateView.ToEntityId(rawEntityId);
ref UnitState unit = ref _entityManager.GetUnitRef(id);
// New sites already carry the definition role (16.3), while an
// active site restored from a pre-16.3 snapshot can still carry
// UnitRole.Unit. Normalize idempotently at completion so the old
// snapshot becomes a valid powered/producing building.
unit.Role = def.Role;
unit.CurrentHealth = def.MaxHealth;
int slot = FreeBuildingIndex();
if (slot >= 0)
{
_buildings[slot] = new PlacementState
{
IsActive = true,
BuildingDefId = def.DefinitionId,
OriginX = originX,
OriginY = originY,
RawEntityId = rawEntityId,
};
}
if (def.Role == UnitRole.ResearchLab && ownerSlot < EconomySystem.MaxPlayers)
{
_t2Unlocked[ownerSlot] = true; // phase 5: T2 unlock (mvp-v1.json technology model)
}
if (def.Role == UnitRole.Refinery)
{
GrantFoundingHarvester(ownerSlot, originX, originY);
}
}
/// <summary>
/// A finished Refinery hands out a Harvester for free — once per
/// living Harvester, not per Refinery.
/// <para>
/// Without it the opening can dead-end: the Harvester costs 700 AE and
/// the Refinery is its only producer, so a player who spends down below
/// 700 before the Refinery finishes has no way left to earn anything.
/// Nothing in the simulation recovers from that — the run is over
/// without an opponent doing a thing. The grant is the cheapest fix
/// that keeps the economy reachable from every spend order.
/// </para>
/// <para>
/// Sprint 16.1 (#43) changed two things. First, the LATCH: the grant
/// fires only while the owner has NO living Harvester — derived by an
/// ascending-index scan over the unit store, never stored (a counter
/// field would break the economy block's fixed per-slot layout). A
/// second Refinery or a rebuild grants nothing while any own Harvester
/// lives; losing every Harvester re-arms the grant, which is exactly
/// the dead-end insurance it exists for. Second, the ORDER: the
/// granted Harvester is born with a standing harvest order on the
/// nearest field with reserve left (measured from the footprint
/// centre), so the loop starts on its own — the economy holds the
/// order and the client/AI escort drives the legs. Same class of
/// direct state write as the push-out's <c>SetTarget</c>: no command
/// record, no new command kind.
/// </para>
/// <para>
/// Deterministic by construction: it runs inside the construction phase
/// in ascending site order, picks its cell with the same ring search as
/// the push-out, and keeps no state of its own — the spawn either
/// happens now or not at all. Nothing here survives a tick boundary, so
/// the snapshot layout is untouched. Every failure path logs instead of
/// returning silently (the pre-16.1 behaviour that made a full entity
/// store or a walled-in Refinery indistinguishable from success).
/// </para>
/// </summary>
private void GrantFoundingHarvester(byte ownerSlot, int originX, int originY)
{
if (HasLivingHarvester(ownerSlot))
{
_logger.LogInfo(
$"[{Name}] Refinery completed for slot {ownerSlot}: founding Harvester grant latched off (an own Harvester is alive).");
return;
}
if (_entityManager.ActiveCount >= _entityManager.Capacity)
{
_logger.LogWarn(
$"[{Name}] Founding Harvester grant for slot {ownerSlot} FAILED: entity store is full ({_entityManager.Capacity}).");
return;
}
if (!SimDefinitions.TryGetUnit(
_economy.GetSlotFaction(ownerSlot), UnitRole.Harvester,
out SimUnitDefinition harvester))
{
_logger.LogWarn(
$"[{Name}] Founding Harvester grant for slot {ownerSlot} FAILED: no Harvester definition for faction {_economy.GetSlotFaction(ownerSlot)}.");
return;
}
// Search outward from the footprint centre; ring 0 is the centre
// cell itself, which the footprint just occupied, so the first hit
// is always outside the building.
int centre = SimDefinitions.BuildingFootprintCells / 2;
if (!TryFindPushOutCell(originX + centre, originY + centre, out int cellX, out int cellY))
{
_logger.LogWarn(
$"[{Name}] Founding Harvester grant for slot {ownerSlot} FAILED: no free cell within {PushOutMaxRing} rings of the Refinery — the player buys the Harvester the normal way.");
return;
}
EntityId id = _entityManager.SpawnUnit(
ownerSlot,
new Transform2D(SimFixed.FromInt(cellX), SimFixed.FromInt(cellY)),
harvester.MoveSpeed,
maxHealth: harvester.MaxHealth,
role: harvester.Role);
if (_economy.TryFindNearestField(originX + centre, originY + centre, out ushort fieldId))
{
_entityManager.GetUnitRef(id).HarvestFieldId = fieldId;
}
else
{
_logger.LogInfo(
$"[{Name}] Founding Harvester spawned for slot {ownerSlot} WITHOUT a field order: no field with reserve is registered.");
}
}
/// <summary>True while any own living Harvester exists (ascending-index scan, same pattern as <see cref="FindLowestIndexBuilder"/>).</summary>
private bool HasLivingHarvester(byte playerSlot)
{
UnitState[] units = _entityManager.RawUnits;
int capacity = _entityManager.Capacity;
for (int i = 0; i < capacity; i++)
{
ref readonly UnitState unit = ref units[i];
if (unit.IsActive && unit.Role == UnitRole.Harvester && unit.PlayerId == playerSlot)
{
return true;
}
}
return false;
}
private void ProcessRepairOrders()
{
Span<uint> claimedTargets = stackalloc uint[MaxRepairOrders];
Span<byte> winningOrders = stackalloc byte[MaxRepairOrders];
winningOrders.Clear();
int claimedTargetCount = 0;
// Select winners from the tick-start state before any target is
// healed. This preserves later same-target orders even when the
// winner reaches full health, while still clearing targets that
// were already full when the tick began.
for (int i = 0; i < MaxRepairOrders; i++)
{
ref RepairOrderState order = ref _repairs[i];
if (!order.IsActive) continue;
EntityId builderId = UnitCommandStateView.ToEntityId(order.BuilderRaw);
EntityId targetId = UnitCommandStateView.ToEntityId(order.TargetRaw);
if (!_entityManager.TryGetUnit(builderId, out UnitState builder)
|| builder.Role != UnitRole.Builder
|| !_entityManager.TryGetUnit(targetId, out UnitState target))
{
order.IsActive = false;
continue;
}
int placementIndex = IndexOfBuilding(order.TargetRaw);
if (placementIndex < 0)
{
order.IsActive = false; // target is not (or no longer) a completed placement
continue;
}
if (!SimDefinitions.TryGetBuilding(
_buildings[placementIndex].BuildingDefId,
out _))
{
order.IsActive = false;
continue;
}
if (target.CurrentHealth >= target.MaxHealth)
{
order.IsActive = false; // fully repaired at tick start: the order resolves
continue;
}
if (!IsInReachOfFootprint(in builder, _buildings[placementIndex].OriginX, _buildings[placementIndex].OriginY))
{
continue; // held, not dropped
}
// Once a damaged target has been claimed this tick, later
// reachable orders remain standing without paying or healing.
// The claim also survives an insufficient-credit refusal so
// order-table multiplicity can never multiply repair work.
bool alreadyClaimed = false;
for (int claimed = 0; claimed < claimedTargetCount; claimed++)
{
if (claimedTargets[claimed] == order.TargetRaw)
{
alreadyClaimed = true;
break;
}
}
if (alreadyClaimed)
{
continue;
}
claimedTargets[claimedTargetCount++] = order.TargetRaw;
winningOrders[i] = 1;
}
for (int i = 0; i < MaxRepairOrders; i++)
{
if (winningOrders[i] == 0) continue;
ref RepairOrderState order = ref _repairs[i];
EntityId targetId = UnitCommandStateView.ToEntityId(order.TargetRaw);
int placementIndex = IndexOfBuilding(order.TargetRaw);
ref UnitState target = ref _entityManager.GetUnitRef(targetId);
SimDefinitions.TryGetBuilding(
_buildings[placementIndex].BuildingDefId,
out SimBuildingDefinition def);
ref PlayerEconomyState repairEco = ref _economy.GetPlayerEconomy(target.PlayerId);
int rate = repairEco.IsLowPower
? LowPowerRepairRateHpPerTick
: RepairRateHpPerTick;
int healthBefore = Math.Max(0, target.CurrentHealth);
int healthAfter = Math.Min(target.MaxHealth, healthBefore + rate);
long fullRepairCost = (long)def.CostAE * RepairCostPercent / 100;
long paidBefore = RepairCostAtHealth(fullRepairCost, healthBefore, target.MaxHealth);
long paidAfter = RepairCostAtHealth(fullRepairCost, healthAfter, target.MaxHealth);
long tickCost = paidAfter - paidBefore;
if (tickCost > 0 && !repairEco.TrySpendCredits(tickCost))
{
continue; // atomic refusal: no debit and no healing
}
target.CurrentHealth = healthAfter;
if (healthAfter >= target.MaxHealth)
{
order.IsActive = false;
}
}
CompactRepairOrders();
}
private static long RepairCostAtHealth(long fullRepairCost, int health, int maxHealth)
{
if (fullRepairCost <= 0 || health <= 0 || maxHealth <= 0) return 0;
if (health >= maxHealth) return fullRepairCost;
return fullRepairCost * health / maxHealth;
}
// ------------------------------------------------------------------
// Internals
// ------------------------------------------------------------------
private void CreateSite(byte playerSlot, in SimBuildingDefinition def, int originX, int originY)
{
EntityId id = SpawnBuildingEntity(playerSlot, in def, originX, originY, completed: false);
OccupyFootprint(originX, originY, pushOutUnits: true);