Core Game Loop Additions

This commit is contained in:
2026-06-03 22:41:27 -07:00
parent 79ff06a7df
commit 8e9b4412ce
70 changed files with 3084 additions and 2 deletions
@@ -0,0 +1,88 @@
using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
namespace ProjectM.Server
{
/// <summary>
/// Server-only procedural expedition-field manager. Edge-triggered off the cycle phase (via the server-only
/// <see cref="CycleRuntime.PrevPhase"/>): on ENTERING Expedition for a not-yet-seeded cycle it scatters
/// <see cref="ResourceFieldSpawner.Count"/> resource-node ghosts (seeded by CycleNumber via
/// <see cref="Unity.Mathematics.Random"/>) around the expedition region origin, each
/// <see cref="RegionTag"/>{Expedition}; on LEAVING Expedition it destroys every node. Runs in the plain
/// server SimulationSystemGroup <c>[UpdateAfter(CyclePhaseSystem)]</c> so the phase edge is observed the
/// same tick. Server-authoritative; clients despawn nodes via GhostDespawnSystem. Per-cycle reproducible
/// (the seed is the monotonic int CycleNumber, compared by equality — never tick math; never seed 0).
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(CyclePhaseSystem))]
public partial struct ExpeditionFieldSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<ResourceFieldSpawner>();
state.RequireForUpdate<CycleState>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var cycleEntity = SystemAPI.GetSingletonEntity<CycleState>();
var cycle = SystemAPI.GetComponent<CycleState>(cycleEntity);
var runtime = SystemAPI.GetComponent<CycleRuntime>(cycleEntity);
var spawner = SystemAPI.GetSingleton<ResourceFieldSpawner>();
float3 baseCenter = new float3(0f, 1f, 0f);
if (SystemAPI.TryGetSingleton<BaseAnchor>(out var anchor))
baseCenter = BaseGridMath.PlotCenter(anchor);
float3 origin = RegionMath.RegionOrigin(RegionId.Expedition, baseCenter);
var ecb = new EntityCommandBuffer(Allocator.Temp);
// SPAWN edge: entered Expedition for a cycle we have not seeded yet.
if (cycle.Phase == CyclePhase.Expedition
&& runtime.LastSpawnedCycle != cycle.CycleNumber
&& spawner.Prefab != Entity.Null)
{
var baseXform = SystemAPI.GetComponent<LocalTransform>(spawner.Prefab);
var prefabNode = SystemAPI.GetComponent<ResourceNode>(spawner.Prefab);
var rng = new Random((uint)math.max(1, cycle.CycleNumber));
int count = math.max(1, spawner.Count);
for (int i = 0; i < count; i++)
{
var node = ecb.Instantiate(spawner.Prefab);
float ang = rng.NextFloat(0f, math.PI * 2f);
float rad = spawner.Radius * math.sqrt(rng.NextFloat(0f, 1f));
var xform = baseXform;
xform.Position = origin + new float3(math.cos(ang) * rad, 0f, math.sin(ang) * rad);
ecb.SetComponent(node, xform);
// Round-robin the resource type (Aether / Ore / Biomass) over the prefab's baked node.
var rn = prefabNode;
rn.ResourceId = (byte)(ResourceId.Aether + (byte)(i % 3));
ecb.SetComponent(node, rn);
}
runtime.LastSpawnedCycle = cycle.CycleNumber;
}
// DESTROY edge: left Expedition — clear the whole field.
if (runtime.PrevPhase == CyclePhase.Expedition && cycle.Phase != CyclePhase.Expedition)
{
foreach (var (rn, e) in SystemAPI.Query<RefRO<ResourceNode>>().WithEntityAccess())
ecb.DestroyEntity(e);
}
runtime.PrevPhase = cycle.Phase;
SystemAPI.SetComponent(cycleEntity, runtime);
ecb.Playback(state.EntityManager);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9267d7809e68ea54caa55378f33e67f6
@@ -0,0 +1,134 @@
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 resource harvest: sweeps each surviving projectile's this-tick travel segment against
/// resource-node ghosts and deposits <see cref="ResourceNode.HarvestPerHit"/> of the node's
/// <see cref="ResourceNode.ResourceId"/> into the GLOBAL resource ledger (the CycleDirector's
/// <see cref="StorageEntry"/> buffer, resolved via <see cref="ResourceLedger"/> — NEVER
/// GetSingleton&lt;StorageEntry&gt;, which would collide with the base storage container). Runs in the plain
/// server SimulationSystemGroup <c>[UpdateAfter(PredictedSimulationSystemGroup)]</c> — after
/// ProjectileDamageSystem has already consumed Health-target hits and range-expired projectiles, so this
/// only sees true survivors. The swept segment is reconstructed from <see cref="Projectile.LastStep"/>
/// (written by ProjectileMoveSystem in the fixed-step group), so it is tunnelling-safe WITHOUT depending on
/// this plain group's variable-frame DeltaTime. A node hit by two projectiles in one tick deposits twice
/// but is destroyed exactly once. Relies on the asserted ~1000-unit base/expedition coordinate gap so a
/// base projectile can never geometrically reach an expedition node.
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(PredictedSimulationSystemGroup))]
public partial struct ResourceHarvestSystem : ISystem
{
const float k_ProjectileRadius = 0.2f;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<Projectile>();
state.RequireForUpdate<ResourceNode>();
state.RequireForUpdate<ResourceLedger>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var ledgerEntity = SystemAPI.GetSingletonEntity<ResourceLedger>();
var ledger = SystemAPI.GetBuffer<StorageEntry>(ledgerEntity);
// Snapshot all nodes once this tick.
var nodeEntities = new NativeList<Entity>(Allocator.Temp);
var nodePos = new NativeList<float2>(Allocator.Temp);
var nodeRadius = new NativeList<float>(Allocator.Temp);
var nodeRemaining = new NativeList<int>(Allocator.Temp);
var nodeResource = new NativeList<byte>(Allocator.Temp);
var nodePerHit = new NativeList<float>(Allocator.Temp);
foreach (var (xform, hr, node, e) in
SystemAPI.Query<RefRO<LocalTransform>, RefRO<HitRadius>, RefRO<ResourceNode>>().WithEntityAccess())
{
nodeEntities.Add(e);
nodePos.Add(xform.ValueRO.Position.xz);
nodeRadius.Add(hr.ValueRO.Value);
nodeRemaining.Add(node.ValueRO.Remaining);
nodeResource.Add(node.ValueRO.ResourceId);
nodePerHit.Add(node.ValueRO.HarvestPerHit);
}
var destroyed = new NativeArray<bool>(nodeEntities.Length, Allocator.Temp);
var ecb = new EntityCommandBuffer(Allocator.Temp);
foreach (var (xform, proj, projEntity) in
SystemAPI.Query<RefRO<LocalTransform>, RefRO<Projectile>>().WithEntityAccess())
{
float3 cur = xform.ValueRO.Position;
float2 segEnd = cur.xz;
float2 segStart = segEnd - proj.ValueRO.Direction * proj.ValueRO.LastStep;
float2 seg = segEnd - segStart;
float segLenSq = math.lengthsq(seg);
int bestIdx = -1;
float bestT = float.MaxValue;
for (int i = 0; i < nodeEntities.Length; i++)
{
if (destroyed[i]) continue;
float2 tp = nodePos[i];
float t = segLenSq > 1e-8f ? math.saturate(math.dot(tp - segStart, seg) / segLenSq) : 0f;
float2 closest = segStart + t * seg;
float hitDist = nodeRadius[i] + k_ProjectileRadius;
if (math.distancesq(tp, closest) <= hitDist * hitDist && t < bestT)
{
bestT = t;
bestIdx = i;
}
}
if (bestIdx < 0)
continue;
int amount = (int)nodePerHit[bestIdx];
StorageMath.Deposit(ledger, nodeResource[bestIdx], amount);
int rem = nodeRemaining[bestIdx] - amount;
nodeRemaining[bestIdx] = rem;
ecb.DestroyEntity(projEntity);
if (rem <= 0)
{
if (!destroyed[bestIdx])
{
destroyed[bestIdx] = true;
ecb.DestroyEntity(nodeEntities[bestIdx]);
}
}
else
{
// Persist the decremented Remaining (replicated GhostField) so depletion carries across ticks.
SystemAPI.SetComponent(nodeEntities[bestIdx], new ResourceNode
{
ResourceId = nodeResource[bestIdx],
Remaining = rem,
HarvestPerHit = nodePerHit[bestIdx],
});
}
}
ecb.Playback(state.EntityManager);
ecb.Dispose();
destroyed.Dispose();
nodeEntities.Dispose();
nodePos.Dispose();
nodeRadius.Dispose();
nodeRemaining.Dispose();
nodeResource.Dispose();
nodePerHit.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1e1ce72e524297a48a08085c68ff908e