GamePlay
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
// Server.Services.World/WorldHandler.cs
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Server.Networking;
|
||||
using Server.Networking.Handling;
|
||||
using Server.Networking.Messages;
|
||||
using Server.Services.Auth;
|
||||
using SystemRevivalServer.Networking.Messages;
|
||||
|
||||
namespace Server.Services.World;
|
||||
|
||||
public sealed class WorldHandler : IClientMessageHandler
|
||||
{
|
||||
private readonly ILogger<WorldHandler> _log;
|
||||
private readonly IWorldService _world;
|
||||
private readonly ISessionRegistry _sessions;
|
||||
private readonly IZoneLeaseService _lease;
|
||||
private readonly IMessageSerializer _ser;
|
||||
private readonly HandlerContext _ctx;
|
||||
|
||||
public WorldHandler(
|
||||
ILogger<WorldHandler> log,
|
||||
IWorldService world,
|
||||
ISessionRegistry sessions,
|
||||
IZoneLeaseService lease,
|
||||
IMessageSerializer ser)
|
||||
{
|
||||
_log = log; _world = world; _sessions = sessions; _lease = lease; _ser = ser;
|
||||
_ctx = new HandlerContext(ser);
|
||||
}
|
||||
|
||||
public IReadOnlyCollection<int> SupportedOpCodes => new[]
|
||||
{
|
||||
OpCodes.WORLD_SPAWN_REQUEST,
|
||||
OpCodes.WORLD_INPUT
|
||||
};
|
||||
|
||||
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
// Expect: TryGet(connId, out accountId, out token)
|
||||
if (!_sessions.TryGet(connection.Id, out var accountId, out var token))
|
||||
{
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "auth_required" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Expect: TryGetCharacter(connId, out characterId) ← add this to ISessionRegistry if missing
|
||||
if (!_sessions.TryGetCharacter(connection.Id, out var charId))
|
||||
{
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "character_required" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (opCode)
|
||||
{
|
||||
case OpCodes.WORLD_SPAWN_REQUEST:
|
||||
{
|
||||
var req = _ser.Deserialize<WorldSpawnRequest>(payload);
|
||||
if (!_lease.IsOwner((ulong)req.ZoneId))
|
||||
{
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "not_owner_zone" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var result = await _world.SpawnAsync(accountId, charId, ct);
|
||||
var ok = result.ok; var error = result.error; var self = result.self; var neighbors = result.neighbors;
|
||||
|
||||
if (!ok)
|
||||
{
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = error ?? "spawn_failed" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.WORLD_SPAWN, self, ct);
|
||||
foreach (var n in neighbors)
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.WORLD_SPAWN, n, ct);
|
||||
break;
|
||||
}
|
||||
|
||||
case OpCodes.WORLD_INPUT:
|
||||
{
|
||||
var req = _ser.Deserialize<WorldInput>(payload);
|
||||
if (!_lease.IsOwner((ulong)req.ZoneId)) return; // ignore for MVP
|
||||
_world.EnqueueInput((ulong)req.ZoneId, charId, req.Dx, req.Dy, req.Facing, req.ClientSeq);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// Server.Services.World/WorldService.cs
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Server.Data;
|
||||
using Server.World;
|
||||
using StackExchange.Redis;
|
||||
using SystemRevivalServer.Networking.Messages;
|
||||
|
||||
namespace Server.Services.World;
|
||||
|
||||
public sealed class WorldService : IWorldService
|
||||
{
|
||||
private readonly ILogger<WorldService> _log;
|
||||
private readonly ICharactersRepository _chars;
|
||||
private readonly IPresenceStore _presence;
|
||||
private readonly IDatabase _db; // Redis
|
||||
private readonly TimeSpan _cellTtl = TimeSpan.FromSeconds(30);
|
||||
|
||||
// In-memory zone state (per owner node)
|
||||
private sealed record Entity(ulong Id, string Name, float X, float Y, float Z, float FacingRad, float Speed);
|
||||
|
||||
private readonly ConcurrentDictionary<ulong, ConcurrentDictionary<ulong, Entity>> _zones = new();
|
||||
private readonly ConcurrentDictionary<ulong, ConcurrentQueue<(ulong CharId, float Dx, float Dy, float FacingRad)>> _inputs = new();
|
||||
|
||||
public WorldService(
|
||||
ILogger<WorldService> log,
|
||||
ICharactersRepository chars,
|
||||
IPresenceStore presence,
|
||||
IDatabase db)
|
||||
{
|
||||
_log = log; _chars = chars; _presence = presence; _db = db;
|
||||
}
|
||||
|
||||
public async Task<(bool ok, string? error, WorldSpawn self, IEnumerable<WorldSpawn> neighbors)>
|
||||
SpawnAsync(ulong accountId, ulong characterId, CancellationToken ct)
|
||||
{
|
||||
// Prefer Redis presence; fallback to DB row.
|
||||
var pos = await _presence.GetAsync(characterId, ct);
|
||||
Character? row;
|
||||
|
||||
if (pos is null)
|
||||
{
|
||||
row = await _chars.FindByIdAsync(characterId, ct);
|
||||
if (row is null || row.AccountId != accountId)
|
||||
return (false, "char_not_found", default!, Array.Empty<WorldSpawn>());
|
||||
|
||||
var facingRad = row.FacingDeg * (MathF.PI / 180f);
|
||||
pos = new Pos(row.ZoneId, (float)row.PosX, (float)row.PosY, (float)row.PosZ, facingRad);
|
||||
await _presence.SetAsync(characterId, pos, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
row = await _chars.FindByIdAsync(characterId, ct);
|
||||
if (row is null)
|
||||
return (false, "char_not_found", default!, Array.Empty<WorldSpawn>());
|
||||
}
|
||||
|
||||
// Update spatial cell
|
||||
var cell = SpatialIndex.Cell(pos.X, pos.Y, pos.Z);
|
||||
await SpatialIndex.UpdateAsync(_db, pos.ZoneId, characterId, cell, cell, _cellTtl);
|
||||
|
||||
// Track in-memory entity
|
||||
var zone = _zones.GetOrAdd(pos.ZoneId, _ => new());
|
||||
var ent = new Entity(characterId, row!.Name, pos.X, pos.Y, pos.Z, pos.FacingRad, 5f);
|
||||
zone[characterId] = ent;
|
||||
|
||||
var self = new WorldSpawn(ent.Id, ent.Name, (int)pos.ZoneId, ent.X, ent.Y, ent.Z, ent.FacingRad, ent.Speed);
|
||||
var neighbors = zone.Values.Where(e => e.Id != ent.Id)
|
||||
.Select(e => new WorldSpawn(e.Id, e.Name, (int)pos.ZoneId, e.X, e.Y, e.Z, e.FacingRad, e.Speed))
|
||||
.ToArray();
|
||||
|
||||
return (true, null, self, neighbors);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void EnqueueInput(ulong zoneId, ulong characterId, float dx, float dy, float facingRad, uint clientSeq)
|
||||
{
|
||||
var q = _inputs.GetOrAdd(zoneId, _ => new());
|
||||
q.Enqueue((characterId, dx, dy, facingRad));
|
||||
}
|
||||
|
||||
public async Task TickOwnerAsync(ulong zoneId, float dt, CancellationToken ct)
|
||||
{
|
||||
if (!_zones.TryGetValue(zoneId, out var ents)) return;
|
||||
|
||||
if (_inputs.TryGetValue(zoneId, out var q))
|
||||
{
|
||||
while (q.TryDequeue(out var itm))
|
||||
{
|
||||
if (!ents.TryGetValue(itm.CharId, out var e)) continue;
|
||||
|
||||
// Normalize input
|
||||
var dx = itm.Dx; var dy = itm.Dy;
|
||||
var mag = MathF.Sqrt(dx * dx + dy * dy);
|
||||
if (mag > 1e-4f) { dx /= mag; dy /= mag; }
|
||||
|
||||
var nx = e.X + dx * e.Speed * dt;
|
||||
var ny = e.Y + dy * e.Speed * dt;
|
||||
var nf = float.IsFinite(itm.FacingRad) ? itm.FacingRad : e.FacingRad;
|
||||
|
||||
var updated = e with { X = nx, Y = ny, FacingRad = nf };
|
||||
ents[e.Id] = updated;
|
||||
|
||||
await _presence.SetAsync(e.Id, new Pos(zoneId, nx, ny, e.Z, nf), ct);
|
||||
|
||||
var oldCell = SpatialIndex.Cell(e.X, e.Y, e.Z);
|
||||
var newCell = SpatialIndex.Cell(nx, ny, e.Z);
|
||||
await SpatialIndex.UpdateAsync(_db, zoneId, e.Id, oldCell, newCell, _cellTtl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public WorldState BuildSnapshot(ulong zoneId, long tick)
|
||||
{
|
||||
if (!_zones.TryGetValue(zoneId, out var ents))
|
||||
return new WorldState((int)zoneId, tick, Array.Empty<WorldEntityState>());
|
||||
|
||||
var list = ents.Values.Select(e => new WorldEntityState(e.Id, e.X, e.Y, e.Z, e.FacingRad, e.Speed)).ToArray();
|
||||
return new WorldState((int)zoneId, tick, list);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user