Files
Project-M/Assets/_Project/Scripts/Server/Combat/HealthApplyDamageSystem.cs
T
kronic 62e48a3b0b LANTERN purge: delete the superseded base/expedition shell (audit H1/H3/M5)
The 2026-08-06 audit found the shipping scene was still the abandoned
co-op-Hades game with LANTERN combat bolted on, and that a third of the
codebase was live code for a direction abandoned on 2026-07-13. Operator
chose deletion over freezing: "everything is saved in source control if
needed. I want the project to be clean."

DELETED (~140 source files, Scripts 335->231, Tests 77->43):
- Enemy variants + boss (H3). ChargerAuthoring / SpitterAuthoring /
  SwarmerAuthoring were attached to ZERO prefabs, so LungeState /
  SpitterState / SwarmerTag were never baked: ~272 lines of Bursted AI
  passes, BossAISystem (261 lines) and the whole MixBands escalation
  curve could not match a single chunk at runtime, while 734 lines of
  green tests certified them. Both shipping enemy prefabs were already
  byte-identical in stats.
- Run/room lifecycle: RunDirector FSM, RunInfo/RunMap/RoomPlan/RoomTag,
  route select, portal interact, ready-check, room field/teardown.
- Meta shop, prep loadout, boons (incl. KillRewardSystem and
  DashTrailDamageSystem, which existed only to serve boon flags).
- Build palette + structures, shared storage, inventory/equipment
  (already recorded PAUSED in CLAUDE.md).
- The HUD panels driving all of the above (HudSystem 1168 -> 610).

KEPT deliberately: BaseGridMath + BaseAnchor (8 systems use PlotCenter
for spawn rings, respawn and dynamic light), the resource ledger +
StorageMath, the save system, region/relevancy. Three of these were in
the delete set until I checked their consumers — worth remembering that
the file-level manifest was wrong about them.

Also folds in audit finding M5: PlayerClass was a second, server-only
copy of the byte FrameId already replicates. It existed for the meta
shop; with that gone, FrameId is the single frame identity.

Harvest is now single-sink (ledger). HarvestMath keeps its shape so
LANTERN's carried-vs-banked cargo split lands in one place, not two.

295/295 EditMode green, zero compile errors. Subscene re-bake and Play
validation follow in the next commit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 12:59:39 -07:00

175 lines
9.7 KiB
C#

using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
namespace ProjectM.Server
{
/// <summary>
/// Server-authoritative damage application. Drains each damageable entity's
/// <see cref="DamageEvent"/> buffer (appended by <see cref="ProjectileDamageSystem"/> earlier
/// this tick), subtracts the summed amount from <see cref="Health"/>, then clears the buffer so
/// each hit is applied exactly once. Entities that carry character stats (players) clamp to their
/// data-driven <see cref="EffectiveCharacterStats.MaxHealth"/> ceiling; others (training dummies)
/// clamp at zero. A dead <see cref="EnemyTag"/> is destroyed; player death is deferred.
/// Health.Current is a <c>[GhostField]</c>, so the new value replicates to clients for display.
///
/// Runs server-only (<see cref="WorldSystemFilterFlags.ServerSimulation"/>) inside the prediction
/// group so it shares tick timing with movement/damage, where it executes once per tick. The
/// single structural change (destroying a dead dummy) is batched through a frame-allocator
/// <see cref="EntityCommandBuffer"/> that is played back immediately to the entity manager — so a
/// plain-world EditMode test needs no separate ECB system.
/// </summary>
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
[UpdateInGroup(typeof(PredictedSimulationSystemGroup))]
[UpdateAfter(typeof(ProjectileDamageSystem))]
// Pin the drain AFTER DashSystem: a same-tick player-sourced projectile (ProjectileDamageSystem stamps
// SourceTick = now and this system drains the SAME tick) must see a dash window STARTED this tick —
// without the edge the negation at src == StartTick is an unconstrained sorter tiebreak. The Dash chain
// (StatRecompute→PlayerControl→Dash) and the projectile chain (PlayerAim→AbilityFire→ProjectileMove→
// ProjectileDamage→here) are otherwise disjoint, so this edge cannot form a cycle (Play-validated).
[UpdateAfter(typeof(DashSystem))]
[BurstCompile]
public partial struct HealthApplyDamageSystem : ISystem
{
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var ecb = new EntityCommandBuffer(Allocator.Temp);
bool haveTick = SystemAPI.TryGetSingleton<NetworkTime>(out var netTime);
uint negatedThisTick = 0;
uint punishesThisTick = 0;
foreach (var (health, dmg, entity) in
SystemAPI.Query<RefRW<Health>, DynamicBuffer<DamageEvent>>()
.WithEntityAccess())
{
if (dmg.Length == 0)
continue;
// Dev god-mode: while enabled, this entity ignores ALL damage (server-authoritative, once per tick).
if (SystemAPI.HasComponent<DebugGodMode>(entity) && SystemAPI.IsComponentEnabled<DebugGodMode>(entity))
{
dmg.Clear();
continue;
}
// Respawn invulnerability: a freshly-recovered player ignores damage for a window.
if (haveTick && netTime.ServerTick.IsValid && SystemAPI.HasComponent<RespawnInvuln>(entity))
{
uint until = SystemAPI.GetComponent<RespawnInvuln>(entity).UntilTick;
if (until != 0)
{
var untilTick = new NetworkTick(until);
if (untilTick.IsValid && untilTick.IsNewerThan(netTime.ServerTick))
{
dmg.Clear();
continue;
}
}
}
bool hasDash = haveTick && netTime.ServerTick.IsValid && SystemAPI.HasComponent<DashState>(entity);
DashState ds = hasDash ? SystemAPI.GetComponent<DashState>(entity) : default;
uint negatedForThisEntity = 0u;
float total = 0f;
int killerNetId = -1; // Phase 1.7: last player-sourced (non-negated) hit this tick → on-kill boon credit
for (int i = 0; i < dmg.Length; i++)
{
uint src = dmg[i].SourceTick;
if (hasDash && src != 0u && ds.IFrameUntilTick != 0u)
{
var srcTick = new NetworkTick(src);
var startTick = new NetworkTick(ds.StartTick);
var untilTick = new NetworkTick(ds.IFrameUntilTick);
// Dash i-frames cover the HALF-OPEN window [StartTick, IFrameUntilTick): negate iff src >= start AND src < until.
bool atOrAfterStart = srcTick.IsValid && startTick.IsValid && !startTick.IsNewerThan(srcTick);
bool beforeUntil = untilTick.IsValid && untilTick.IsNewerThan(srcTick);
if (atOrAfterStart && beforeUntil)
{
negatedThisTick++;
negatedForThisEntity++;
continue; // dash i-frame negates this hit (per-element, not a whole-buffer clear)
}
}
total += dmg[i].Amount;
if (dmg[i].SourceNetworkId >= 0) killerNetId = dmg[i].SourceNetworkId; // Phase 1.7 kill credit
// 2026-08-07 audit purge: the Charger whiff-punish scoring lived here (a player hit landing
// inside LungeState.StaggerUntilTick scored a punish). LungeState was never baked onto any
// prefab, so this branch was unreachable; it went with the Charger.
}
dmg.Clear();
if (negatedForThisEntity != 0u)
{
ds.NegatedCount += negatedForThisEntity; // server-side spam signal; DashSystem reads it at window-close
SystemAPI.SetComponent(entity, ds);
}
float newHp = health.ValueRO.Current - total;
// Effective max health (base + modifiers) is the runtime ceiling for entities that carry
// character stats (players); others just clamp at zero. No auto-heal on a max increase.
if (SystemAPI.HasComponent<EffectiveCharacterStats>(entity))
newHp = math.clamp(newHp, 0f, SystemAPI.GetComponent<EffectiveCharacterStats>(entity).MaxHealth);
else
newHp = math.max(0f, newHp);
health.ValueRW.Current = newHp;
// Server-authoritative death: training dummies + EB-1 Destructible structures despawn instantly;
// player death is deferred (clamp only). A structure carries NO EffectiveCharacterStats, so it took
// the math.max(0,..) branch above and CAN reach 0 — never give a structure stats (it would clamp to
// a non-zero floor and become immortal).
// Phase 1 (B3): ENEMIES get a corpse window instead — mark Dying ONCE on the lethal crossing and
// zero every live cue (the replicated windup, the lunge state + ghost bit, knockback) so clients
// never see a corpse telegraphing. Plain-world EditMode tests have no NetworkTime → keep the old
// instant destroy there so the existing suite still means what it asserts.
if (health.ValueRO.Current <= 0f)
{
if (SystemAPI.HasComponent<EnemyTag>(entity) && haveTick && netTime.ServerTick.IsValid)
{
if (!SystemAPI.HasComponent<Dying>(entity))
{
ecb.AddComponent(entity, new Dying
{
UntilTick = TickUtil.NonZero(netTime.ServerTick.TickIndexForValidTick + Tuning.EnemyDeathWindowTicks),
KillerNetId = killerNetId, // Phase 1.7: KillRewardSystem reads this for Siphon/Frenzy
Rewarded = 0,
});
if (SystemAPI.HasComponent<AttackWindup>(entity)) SystemAPI.SetComponent(entity, default(AttackWindup));
if (SystemAPI.HasComponent<KnockbackState>(entity)) SystemAPI.SetComponent(entity, default(KnockbackState));
}
}
else if (SystemAPI.HasComponent<EnemyTag>(entity) || SystemAPI.HasComponent<Destructible>(entity))
ecb.DestroyEntity(entity);
}
}
// Phase 1 (B3): corpse expiry — destroy Dying enemies whose window elapsed (at-most-once: the Dying
// mark is the only path here, and destruction removes it). NetworkTick compare, never raw uint math.
if (haveTick && netTime.ServerTick.IsValid)
{
foreach (var (dying, entity) in SystemAPI.Query<RefRO<Dying>>().WithEntityAccess())
{
var until = new NetworkTick(dying.ValueRO.UntilTick);
if (until.IsValid && !until.IsNewerThan(netTime.ServerTick))
ecb.DestroyEntity(entity);
}
}
if ((negatedThisTick != 0u || punishesThisTick != 0u) && SystemAPI.HasSingleton<DevTelemetry>())
{
var telem = SystemAPI.GetSingletonRW<DevTelemetry>();
telem.ValueRW.DashIFrameNegatedHits += negatedThisTick;
telem.ValueRW.ChargerWhiffPunishesLanded += punishesThisTick;
}
ecb.Playback(state.EntityManager);
ecb.Dispose();
}
}
}