Continued

This commit is contained in:
2026-06-04 00:06:18 -07:00
parent 8e9b4412ce
commit 5c11ff4fad
42 changed files with 1287 additions and 29 deletions
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 73829e22632af284d880736d6b0a371f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,92 @@
using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.NetCode;
namespace ProjectM.Server
{
/// <summary>
/// Server-authoritative ability-damage upgrade (handles <see cref="AbilityUpgradeRequest"/> RPCs). Resolves
/// the sender's player (SourceConnection -&gt; NetworkId -&gt; GhostOwner) and, if the global ledger affords the
/// Aether cost, withdraws it IN-PLACE and grows a single damage <see cref="StatModifier"/> on the player
/// (replace-by-SourceId so the [InternalBufferCapacity(8)] buffer stays bounded — repeated upgrades grow one
/// row's percent rather than appending). StatRecomputeSystem folds it into EffectiveAbilityStats.Damage on
/// both worlds. Plain server SimulationSystemGroup (not predicted → applied once).
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct AbilityUpgradeSystem : ISystem
{
const uint UpgradeSourceId = 0x00A0E711u; // distinct sentinel so the upgrade modifier is found + grown
const float TierStep = 0.25f; // +25% damage per tier
const int CostAmount = 20; // Aether per tier
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<ResourceLedger>();
var builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll<AbilityUpgradeRequest, ReceiveRpcCommandRequest>();
state.RequireForUpdate(state.GetEntityQuery(builder));
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var ledger = SystemAPI.GetBuffer<StorageEntry>(SystemAPI.GetSingletonEntity<ResourceLedger>());
var playerByConn = new NativeHashMap<int, Entity>(8, Allocator.Temp);
foreach (var (owner, entity) in
SystemAPI.Query<RefRO<GhostOwner>>().WithAll<PlayerTag, StatModifier>().WithEntityAccess())
playerByConn[owner.ValueRO.NetworkId] = entity;
var ecb = new EntityCommandBuffer(Allocator.Temp);
foreach (var (receive, requestEntity) in
SystemAPI.Query<RefRO<ReceiveRpcCommandRequest>>().WithAll<AbilityUpgradeRequest>().WithEntityAccess())
{
var conn = receive.ValueRO.SourceConnection;
if (SystemAPI.HasComponent<NetworkId>(conn)
&& playerByConn.TryGetValue(SystemAPI.GetComponent<NetworkId>(conn).Value, out var player))
{
int have = 0;
for (int i = 0; i < ledger.Length; i++)
if (ledger[i].ItemId == ResourceId.Aether) { have = ledger[i].Count; break; }
if (have >= CostAmount)
{
StorageMath.Withdraw(ledger, ResourceId.Aether, CostAmount);
var mods = SystemAPI.GetBuffer<StatModifier>(player);
bool grown = false;
for (int i = 0; i < mods.Length; i++)
{
if (mods[i].SourceId == UpgradeSourceId && mods[i].Target == (byte)StatTarget.Damage)
{
var m = mods[i];
m.Value += TierStep;
mods[i] = m;
grown = true;
break;
}
}
if (!grown)
mods.Add(new StatModifier
{
Target = (byte)StatTarget.Damage,
Op = (byte)ModOp.PercentAdd,
Value = TierStep,
SourceId = UpgradeSourceId,
});
}
}
ecb.DestroyEntity(requestEntity);
}
ecb.Playback(state.EntityManager);
playerByConn.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ff2ed6b5fa37a174aa7413f4d2f5d6b3
@@ -0,0 +1,104 @@
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-authoritative structure placement (handles <see cref="BuildPlaceRequest"/> RPCs). Derives
/// occupancy by scanning live <see cref="PlacedStructure"/> ghosts into a Temp NativeHashSet (structures
/// are the source of truth — no cached buffer on the immutable BaseAnchor). For each request it validates
/// catalog/legality/occupancy/cost, and on success commits IN-PLACE (StorageMath.Withdraw on the global
/// ledger + reserve the cell in the set) so two same-tick requests for one cell can't both pass — the
/// StorageOpReceiveSystem in-place idiom — then instantiates the catalog prefab at the cell center
/// (RegionTag{Base}, world-owned, NextTick=0, LastProcessedTick stamped). Plain server SimulationSystemGroup
/// (not predicted → applied once). Rejects invalid requests silently.
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct BuildPlaceSystem : ISystem
{
ComponentLookup<LocalTransform> m_TransformLookup;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
m_TransformLookup = state.GetComponentLookup<LocalTransform>(isReadOnly: true);
state.RequireForUpdate<StructureCatalog>();
state.RequireForUpdate<BaseAnchor>();
state.RequireForUpdate<ResourceLedger>();
state.RequireForUpdate<NetworkTime>();
var builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll<BuildPlaceRequest, ReceiveRpcCommandRequest>();
state.RequireForUpdate(state.GetEntityQuery(builder));
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
m_TransformLookup.Update(ref state);
uint now = SystemAPI.GetSingleton<NetworkTime>().ServerTick.TickIndexForValidTick;
var anchor = SystemAPI.GetSingleton<BaseAnchor>();
var catalog = SystemAPI.GetBuffer<StructureCatalogEntry>(SystemAPI.GetSingletonEntity<StructureCatalog>());
var ledger = SystemAPI.GetBuffer<StorageEntry>(SystemAPI.GetSingletonEntity<ResourceLedger>());
// Derive occupancy from the live structure set (authoritative source of truth).
var occupied = new NativeHashSet<int2>(64, Allocator.Temp);
foreach (var ps in SystemAPI.Query<RefRO<PlacedStructure>>())
occupied.Add(ps.ValueRO.Cell);
var ecb = new EntityCommandBuffer(Allocator.Temp);
foreach (var (request, receive, requestEntity) in
SystemAPI.Query<RefRO<BuildPlaceRequest>, RefRO<ReceiveRpcCommandRequest>>().WithEntityAccess())
{
var req = request.ValueRO;
int2 cell = new int2(req.CellX, req.CellZ);
int entryIdx = -1;
for (int i = 0; i < catalog.Length; i++)
if (catalog[i].Type == req.StructureType) { entryIdx = i; break; }
if (entryIdx >= 0 && catalog[entryIdx].Prefab != Entity.Null
&& BuildPlacementMath.CanPlace(anchor, occupied, cell))
{
var entry = catalog[entryIdx];
int have = 0;
for (int i = 0; i < ledger.Length; i++)
if (ledger[i].ItemId == entry.CostResourceId) { have = ledger[i].Count; break; }
if (have >= entry.CostAmount)
{
// Commit IN-PLACE so a second same-tick request sees the spend + reservation.
StorageMath.Withdraw(ledger, entry.CostResourceId, entry.CostAmount);
occupied.Add(cell);
var structure = ecb.Instantiate(entry.Prefab);
var xform = m_TransformLookup[entry.Prefab];
xform.Position = BaseGridMath.CellToWorld(anchor, cell); // preserve baked Scale
ecb.SetComponent(structure, xform);
ecb.SetComponent(structure, new PlacedStructure
{
Type = req.StructureType,
Cell = cell,
NextTick = 0u,
LastProcessedTick = TickUtil.NonZero(now),
});
ecb.AddComponent(structure, new RegionTag { Region = RegionId.Base });
}
}
ecb.DestroyEntity(requestEntity);
}
ecb.Playback(state.EntityManager);
occupied.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d1886c7056b315e42b7754f50c43c59e
@@ -0,0 +1,110 @@
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 turret fire (hitscan) — EnemyAISystem reversed. Snapshots living Husks once (entity, planar
/// pos, region); each turret picks the nearest Husk in ITS region within Range and, on a NetworkTick
/// cooldown stored in <see cref="PlacedStructure.NextTick"/>, appends a direct <c>DamageEvent</c>
/// (SourceNetworkId=-1) to it. Reuses HealthApplyDamageSystem (already destroys EnemyTag at HP&lt;=0) — no
/// projectile, no tunnelling, no friendly-fire. Plain server SimulationSystemGroup
/// <c>[UpdateAfter(PredictedSimulationSystemGroup)]</c> (the predicted group is OrderFirst → UpdateBefore is
/// ignored); the appended DamageEvent drains next tick (~16ms), consistent with EnemyAISystem. Self-gates:
/// Husks only exist during the Defend wave.
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(PredictedSimulationSystemGroup))]
public partial struct TurretFireSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<NetworkTime>();
state.RequireForUpdate(state.GetEntityQuery(ComponentType.ReadOnly<Turret>()));
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var serverTick = SystemAPI.GetSingleton<NetworkTime>().ServerTick;
if (!serverTick.IsValid)
return;
uint now = serverTick.TickIndexForValidTick;
var huskEntities = new NativeList<Entity>(Allocator.Temp);
var huskPos = new NativeList<float2>(Allocator.Temp);
var huskRegion = new NativeList<byte>(Allocator.Temp);
foreach (var (xform, health, region, e) in
SystemAPI.Query<RefRO<LocalTransform>, RefRO<Health>, RefRO<RegionTag>>()
.WithAll<EnemyTag>().WithEntityAccess())
{
if (health.ValueRO.Current <= 0f)
continue;
huskEntities.Add(e);
huskPos.Add(xform.ValueRO.Position.xz);
huskRegion.Add(region.ValueRO.Region);
}
if (huskEntities.Length == 0)
{
huskEntities.Dispose(); huskPos.Dispose(); huskRegion.Dispose();
return;
}
var ecb = new EntityCommandBuffer(Allocator.Temp);
foreach (var (ps, turret, xform, region) in
SystemAPI.Query<RefRW<PlacedStructure>, RefRO<Turret>, RefRO<LocalTransform>, RefRO<RegionTag>>())
{
uint nextRaw = ps.ValueRO.NextTick;
if (nextRaw != 0)
{
var nextTick = new NetworkTick(nextRaw);
if (nextTick.IsValid && nextTick.IsNewerThan(serverTick))
continue; // still cooling down
}
float2 tp = xform.ValueRO.Position.xz;
byte treg = region.ValueRO.Region;
float rangeSq = turret.ValueRO.Range * turret.ValueRO.Range;
int best = -1;
float bestSq = float.MaxValue;
for (int i = 0; i < huskEntities.Length; i++)
{
if (huskRegion[i] != treg)
continue;
float sq = math.distancesq(huskPos[i], tp);
if (sq <= rangeSq && sq < bestSq)
{
bestSq = sq;
best = i;
}
}
if (best >= 0)
{
ecb.AppendToBuffer(huskEntities[best], new DamageEvent
{
Amount = turret.ValueRO.Damage,
SourceNetworkId = -1,
});
uint cd = (uint)math.max(1, turret.ValueRO.CooldownTicks);
ps.ValueRW.NextTick = TickUtil.NonZero(now + cd);
}
}
ecb.Playback(state.EntityManager);
ecb.Dispose();
huskEntities.Dispose(); huskPos.Dispose(); huskRegion.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 53cc7669bd6cc5d4e8307b18732897bc
@@ -71,6 +71,13 @@ namespace ProjectM.Server
cycle.Phase = CyclePhase.Expedition;
cycle.CycleNumber += 1;
cycle.PhaseEndTick = TickUtil.NonZero(now + CyclePhase.ExpeditionTicks);
// Long-arc goal: one charge per completed cycle (single writer).
if (SystemAPI.HasComponent<GoalProgress>(cycleEntity))
{
var goal = SystemAPI.GetComponent<GoalProgress>(cycleEntity);
goal.Charge += 1;
SystemAPI.SetComponent(cycleEntity, goal);
}
}
break;
}