Files
Project-M/Assets/_Project/Scripts/Server/HomeBase/StorageOpReceiveSystem.cs
T
2026-06-02 18:28:23 -07:00

55 lines
2.2 KiB
C#

using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.NetCode;
namespace ProjectM.Server
{
/// <summary>
/// Server-authoritative handler for <see cref="StorageOpRequest"/> RPCs (deposit/withdraw on the
/// shared storage container). Resolves the single <see cref="SharedStorageContainer"/> as a singleton,
/// applies the op to its replicated <see cref="StorageEntry"/> buffer via <see cref="StorageMath"/>,
/// and destroys the request entity. Runs in the default SimulationSystemGroup (NOT the prediction
/// loop), so a server event is applied exactly once (no rollback double-apply). Op is read as a byte
/// (see <see cref="StorageOp"/>); the buffer mutation auto-replicates to all clients via GhostField.
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct StorageOpReceiveSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<SharedStorageContainer>();
var builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll<StorageOpRequest, ReceiveRpcCommandRequest>();
state.RequireForUpdate(state.GetEntityQuery(builder));
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var containerEntity = SystemAPI.GetSingletonEntity<SharedStorageContainer>();
var contents = SystemAPI.GetBuffer<StorageEntry>(containerEntity);
var ecb = new EntityCommandBuffer(Allocator.Temp);
foreach (var (request, requestEntity) in
SystemAPI.Query<RefRO<StorageOpRequest>>().WithAll<ReceiveRpcCommandRequest>().WithEntityAccess())
{
var op = request.ValueRO;
if (op.Op == StorageOp.Withdraw)
StorageMath.Withdraw(contents, op.ItemId, op.Count);
else
StorageMath.Deposit(contents, op.ItemId, op.Count);
ecb.DestroyEntity(requestEntity);
}
ecb.Playback(state.EntityManager);
}
}
}