Files
Project-M/Assets/_Project/Scripts/Server/Combat/WaveSystem.cs
T
kronic 3109b86d71 Slice 3: Expedition Combat Spine — epoch-seeded zone waves (DR-040)
Reactivate the dormant Expedition region as a procedural combat venue.
v1 loop: walk the gate -> fight an epoch-seeded enemy wave in the
expedition -> clear -> return -> flat Ore reward (once per epoch) ->
escalated retaliation base siege.

- New sim types: ZoneEnemyTag, ZoneEnemyDirector (+ ZoneEnemyPrefab
  buffer), ZoneEnemyState, ZoneEnemyMath (grunt->charger composition
  by epoch). ZoneEnemyDirectorSystem (server, Burst): drip-spawns the
  wave at a deterministic ring under a MaxAlive cap while a player is
  out and the base is Calm; marks ClearedThisEpoch on a real clear.
  [UpdateAfter(ExpeditionFieldSystem)] only (avoids a sort cycle).
- BLOCKER 1: EnemyAISystem region-filters target selection (player +
  structure snapshots gain parallel region lists; no base structures /
  no Core fallback for expedition husks).
- BLOCKER 3: WaveSystem, ThreatDirectorSystem timeout cull, and
  CyclePhaseSystem DefendCleared + Core-breach cull all count/cull
  RegionTag{Base} husks only (the breach cull was caught region-blind
  by the post-impl review: a base breach wiped the live expedition
  wave and spuriously paid the reward).
- BLOCKER 4: reward de-duped via CycleRuntime.LastRewardedEpoch +
  ClearedThisEpoch; ExpeditionGateSystem deposits RewardOre once/epoch.
- ExpeditionFieldSystem teardown also culls zone enemies + region-
  guards the clutter loop. Subscene wired with the director + roster.

368/368 EditMode green + clean netcode Play smoke. Docs: DR-040 ->
built, session log, CLAUDE.md cross-region tag-reaudit rule.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 22:58:26 -07:00

121 lines
5.7 KiB
C#

using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Transforms;
namespace ProjectM.Server
{
/// <summary>
/// Server-only Husk wave/threat director: a state machine that escalates the swarm. In <c>Lull</c> it waits
/// until the lull timer expires, then starts the next wave (count = <c>BaseCount + (wave-1)*CountPerWave</c>). In
/// <c>Spawning</c> it spawns one Husk every <c>SpawnIntervalTicks</c> at a deterministic ring slot around the
/// <see cref="BaseAnchor"/>, round-robin over the <see cref="WaveEnemyPrefab"/> pool, until the wave is fully
/// spawned; then it waits for the field to be cleared (no live <see cref="EnemyTag"/>) before returning to
/// <c>Lull</c>. Plain <see cref="SimulationSystemGroup"/>, server-authoritative (Husks are interpolated ghosts).
/// Replaces the flat <c>EnemySpawnSystem</c> sustain. Tick gating uses the wrap-safe <see cref="NetworkTick"/>
/// compare + <see cref="TickUtil.NonZero"/>.
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
[UpdateInGroup(typeof(SimulationSystemGroup))]
public partial struct WaveSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<WaveDirector>();
state.RequireForUpdate<WaveState>();
state.RequireForUpdate<NetworkTime>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var serverTick = SystemAPI.GetSingleton<NetworkTime>().ServerTick;
if (!serverTick.IsValid)
return;
uint now = serverTick.TickIndexForValidTick;
// Player-driven loop: the base-defense wave only spawns during a Siege.
if (SystemAPI.TryGetSingleton<CycleState>(out var cycle) && cycle.Phase != CyclePhase.Siege)
return;
var director = SystemAPI.GetSingleton<WaveDirector>();
var directorEntity = SystemAPI.GetSingletonEntity<WaveDirector>();
var prefabs = SystemAPI.GetBuffer<WaveEnemyPrefab>(directorEntity);
if (prefabs.Length == 0)
return;
var wave = SystemAPI.GetComponent<WaveState>(directorEntity);
// Ring centre on the base plot when present.
float3 center = new float3(0f, 1f, 0f);
if (SystemAPI.TryGetSingleton<BaseAnchor>(out var baseAnchor))
center = BaseGridMath.PlotCenter(baseAnchor);
// Due when no action is scheduled yet (NextActionTick 0) or the scheduled tick is at/behind now.
bool dueNow = wave.NextActionTick == 0 || !new NetworkTick(wave.NextActionTick).IsNewerThan(serverTick);
if (wave.Phase == WavePhase.Lull)
{
if (dueNow)
{
// Start the next (bigger) wave.
wave.WaveNumber += 1;
wave.RemainingToSpawn =
math.max(1, director.BaseCount + (wave.WaveNumber - 1) * director.CountPerWave);
wave.Phase = WavePhase.Spawning;
wave.NextActionTick = TickUtil.NonZero(now); // spawn the first Husk this tick
}
}
else // Spawning
{
if (wave.RemainingToSpawn > 0)
{
if (dueNow)
{
int slots = math.max(1, director.RingSlots);
int prefabIdx = wave.SpawnCounter % prefabs.Length;
float3 pos = EnemyAIMath.RingPosition(center, wave.SpawnCounter, slots, director.RingRadius);
pos.y = center.y;
var ecb = new EntityCommandBuffer(Allocator.Temp);
var husk = ecb.Instantiate(prefabs[prefabIdx].Prefab);
// Preserve the prefab's baked variant Scale (a replicated [GhostField]) + rotation;
// LocalTransform.FromPosition() would reset Scale->1, shrinking/growing animated variants.
var baked = state.EntityManager.GetComponentData<LocalTransform>(prefabs[prefabIdx].Prefab);
ecb.SetComponent(husk, baked.WithPosition(pos));
// Husks belong to the base region (hidden from expedition players by relevancy).
ecb.AddComponent(husk, new RegionTag { Region = RegionId.Base });
ecb.Playback(state.EntityManager);
ecb.Dispose();
wave.SpawnCounter += 1;
wave.RemainingToSpawn -= 1;
wave.NextActionTick = TickUtil.NonZero(now + (uint)math.max(1, director.SpawnIntervalTicks));
}
}
else
{
// Wave fully spawned: cleared only when no BASE husk remains. Expedition zone enemies are also
// EnemyTag but RegionTag{Expedition}; they must NOT hold the base siege open (DR-040 BLOCKER 3).
int baseHusks = 0;
foreach (var hr in SystemAPI.Query<RefRO<RegionTag>>().WithAll<EnemyTag>())
if (hr.ValueRO.Region == RegionId.Base) baseHusks++;
if (baseHusks == 0)
{
// Wave cleared: calm before the next.
wave.Phase = WavePhase.Lull;
wave.NextActionTick = TickUtil.NonZero(now + (uint)math.max(1, director.LullTicks));
}
}
}
SystemAPI.SetComponent(directorEntity, wave);
}
}
}