World revamp

This commit is contained in:
dingo
2026-02-16 08:56:15 -05:00
parent c7ac5ea0a0
commit 7e6d494e44
10 changed files with 2190 additions and 738 deletions
+127
View File
@@ -0,0 +1,127 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Server.Networking;
using Server.Networking.Messages;
namespace GameServer.World;
public sealed class WorldBroadcastService
{
private readonly WorldChunkCache _cache;
private readonly IMessageSerializer _ser;
private readonly ILogger<WorldBroadcastService> _log;
public WorldBroadcastService(WorldChunkCache cache, IMessageSerializer ser, ILogger<WorldBroadcastService> log)
{
_cache = cache;
_ser = ser;
_log = log;
}
/// <summary>
/// Compute chunk load/unload updates for a player based on their current position.
/// Uses the cache exclusively -- the only async path is a cache-miss DB load for new chunks.
/// </summary>
public async ValueTask<List<(string type, object payload)>> GetChunkUpdatesAsync(
WorldChunkCache.CachedRegion region,
WorldSessionState s,
CancellationToken ct)
{
var required = new HashSet<string>(StringComparer.Ordinal);
var list = new List<(string, object)>();
var chunksPerRegionX = region.ZonesPerRegionX * region.ChunksPerZoneX;
var chunksPerRegionY = region.ZonesPerRegionY * region.ChunksPerZoneY;
if (chunksPerRegionX <= 0 || chunksPerRegionY <= 0)
return list;
var centerAbsChunkX = (s.ZoneX * region.ChunksPerZoneX) + s.ChunkX;
var centerAbsChunkY = (s.ZoneY * region.ChunksPerZoneY) + s.ChunkY;
for (var ay = Math.Max(0, centerAbsChunkY - 1); ay <= Math.Min(chunksPerRegionY - 1, centerAbsChunkY + 1); ay++)
for (var ax = Math.Max(0, centerAbsChunkX - 1); ax <= Math.Min(chunksPerRegionX - 1, centerAbsChunkX + 1); ax++)
{
var zx = ax / region.ChunksPerZoneX;
var zy = ay / region.ChunksPerZoneY;
var cx = ax % region.ChunksPerZoneX;
var cy = ay % region.ChunksPerZoneY;
var key = $"{region.Id}:{zx}:{zy}:{cx}:{cy}";
required.Add(key);
if (!s.ChunkVersions.ContainsKey(key))
{
var cached = await _cache.GetChunkAsync(region.Id, zx, zy, cx, cy, ct);
s.ChunkVersions[key] = cached?.Version ?? 0;
if (cached != null)
{
list.Add(("chunk_full", new
{
type = "chunk_full",
chunk = cached.ChunkDto,
tiles = cached.TileDtos,
objects = cached.ObjectDtos,
npcs = cached.NpcDtos,
mobs = cached.MobDtos
}));
}
else
{
list.Add(("chunk_full", new
{
type = "chunk_full",
chunk = new { regionId = region.Id, zoneX = zx, zoneY = zy, chunkX = cx, chunkY = cy, version = 0, width = region.ChunkWidthTiles, height = region.ChunkHeightTiles },
tiles = Array.Empty<object>(),
objects = Array.Empty<object>(),
npcs = Array.Empty<object>(),
mobs = Array.Empty<object>()
}));
}
}
}
foreach (var stale in s.ChunkVersions.Keys.Where(k => !required.Contains(k)).ToList())
{
s.ChunkVersions.Remove(stale);
var p = stale.Split(':');
list.Add(("chunk_unload", new
{
type = "chunk_unload",
regionId = int.Parse(p[0]),
zoneX = int.Parse(p[1]),
zoneY = int.Parse(p[2]),
chunkX = int.Parse(p[3]),
chunkY = int.Parse(p[4])
}));
}
return list;
}
public async Task SendAsync(IConnection connection, int opCode, object payload, CancellationToken ct)
{
try
{
var bytes = _ser.Serialize(payload);
var msg = new ServerMessage(opCode, bytes);
await connection.SendAsync(_ser.Serialize(msg), ct);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed sending opcode {Op} to {ConnectionId}", opCode, connection.Id);
}
}
public Task SendErrorAsync(IConnection connection, string error, CancellationToken ct)
=> SendAsync(connection, OpCodes.ERROR, new { error }, ct);
public async Task BroadcastToRegionAsync(
int opCode,
object payload,
int regionId,
ConcurrentDictionary<Guid, WorldSessionState> players,
Guid? exceptConnectionId = null)
{
var tasks = players.Values
.Where(p => p.RegionId == regionId && (exceptConnectionId == null || p.ConnectionId != exceptConnectionId.Value))
.Select(p => SendAsync(p.Connection, opCode, payload, CancellationToken.None));
await Task.WhenAll(tasks);
}
}
+501
View File
@@ -0,0 +1,501 @@
using System.Collections.Concurrent;
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace GameServer.World;
public sealed class WorldChunkCache
{
private const int TileSize = 32;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<WorldChunkCache> _log;
private readonly ConcurrentDictionary<int, CachedRegion> _regions = new();
private readonly ConcurrentDictionary<string, CachedChunk?> _chunks = new();
private readonly ConcurrentDictionary<string, SemaphoreSlim> _loadLocks = new();
public WorldChunkCache(IServiceScopeFactory scopeFactory, ILogger<WorldChunkCache> log)
{
_scopeFactory = scopeFactory;
_log = log;
}
// ---- Cached data structures ----
public sealed class CachedRegion
{
public int Id { get; init; }
public string Name { get; init; } = "";
public int ZonesPerRegionX { get; init; }
public int ZonesPerRegionY { get; init; }
public int ChunksPerZoneX { get; init; }
public int ChunksPerZoneY { get; init; }
public int ChunkWidthTiles { get; init; }
public int ChunkHeightTiles { get; init; }
}
public sealed class CachedChunk
{
public long DbId { get; init; }
public long Version { get; init; }
public int RegionId { get; init; }
public int ZoneX { get; init; }
public int ZoneY { get; init; }
public int ChunkX { get; init; }
public int ChunkY { get; init; }
public int WidthTiles { get; init; }
public int HeightTiles { get; init; }
// Flat walkability + paywall arrays indexed by [y * width + x]
public bool[] Walkable { get; init; } = Array.Empty<bool>();
public bool[] IsPaywall { get; init; } = Array.Empty<bool>();
// Full DTOs for client serialization (same shapes as the original LoadChunkAsync)
public object ChunkDto { get; init; } = new { };
public object[] TileDtos { get; init; } = Array.Empty<object>();
public object[] ObjectDtos { get; init; } = Array.Empty<object>();
public object[] NpcDtos { get; init; } = Array.Empty<object>();
public object[] MobDtos { get; init; } = Array.Empty<object>();
// Portal objects indexed for spatial lookup
public CachedPortalObject[] Portals { get; init; } = Array.Empty<CachedPortalObject>();
}
public sealed class CachedPortalObject
{
public long Id { get; init; }
public int TileX { get; init; }
public int TileY { get; init; }
public int Width { get; init; }
public int Height { get; init; }
public string? MetadataJson { get; init; }
}
// ---- Public API ----
public async ValueTask<CachedRegion?> GetRegionAsync(int regionId, CancellationToken ct = default)
{
if (_regions.TryGetValue(regionId, out var cached))
return cached;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var region = await db.WorldRegions.AsNoTracking()
.FirstOrDefaultAsync(r => r.Id == regionId && r.IsEnabled, ct);
if (region == null) return null;
var cachedRegion = new CachedRegion
{
Id = region.Id,
Name = region.Name,
ZonesPerRegionX = region.ZonesPerRegionX,
ZonesPerRegionY = region.ZonesPerRegionY,
ChunksPerZoneX = region.ChunksPerZoneX,
ChunksPerZoneY = region.ChunksPerZoneY,
ChunkWidthTiles = region.ChunkWidthTiles,
ChunkHeightTiles = region.ChunkHeightTiles
};
_regions[regionId] = cachedRegion;
return cachedRegion;
}
public async ValueTask<CachedRegion?> ResolveRegionAsync(int? requestedId, CancellationToken ct = default)
{
if (requestedId.HasValue && requestedId.Value > 0)
{
var match = await GetRegionAsync(requestedId.Value, ct);
if (match != null) return match;
}
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var region = await db.WorldRegions.AsNoTracking()
.Where(r => r.IsEnabled)
.OrderBy(r => r.Id)
.FirstOrDefaultAsync(ct);
if (region == null) return null;
var cached = new CachedRegion
{
Id = region.Id,
Name = region.Name,
ZonesPerRegionX = region.ZonesPerRegionX,
ZonesPerRegionY = region.ZonesPerRegionY,
ChunksPerZoneX = region.ChunksPerZoneX,
ChunksPerZoneY = region.ChunksPerZoneY,
ChunkWidthTiles = region.ChunkWidthTiles,
ChunkHeightTiles = region.ChunkHeightTiles
};
_regions[region.Id] = cached;
return cached;
}
public async ValueTask<CachedChunk?> GetChunkAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct = default)
{
var key = ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY);
if (_chunks.TryGetValue(key, out var cached))
return cached;
var loadLock = _loadLocks.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
await loadLock.WaitAsync(ct);
try
{
if (_chunks.TryGetValue(key, out cached))
return cached;
cached = await LoadChunkFromDbAsync(regionId, zoneX, zoneY, chunkX, chunkY, ct);
_chunks[key] = cached;
return cached;
}
finally
{
loadLock.Release();
}
}
public bool IsTileWalkable(CachedRegion region, float wx, float wy, bool isVip)
{
var gx = (int)MathF.Floor(wx / TileSize);
var gy = (int)MathF.Floor(wy / TileSize);
if (gx < 0 || gy < 0) return true;
var zoneW = region.ChunksPerZoneX * region.ChunkWidthTiles;
var zoneH = region.ChunksPerZoneY * region.ChunkHeightTiles;
if (zoneW <= 0 || zoneH <= 0) return true;
var zx = gx / zoneW;
var zy = gy / zoneH;
if (zx >= region.ZonesPerRegionX || zy >= region.ZonesPerRegionY) return true;
var lzx = gx - (zx * zoneW);
var lzy = gy - (zy * zoneH);
var cx = lzx / region.ChunkWidthTiles;
var cy = lzy / region.ChunkHeightTiles;
var tx = lzx % region.ChunkWidthTiles;
var ty = lzy % region.ChunkHeightTiles;
var key = ChunkKey(region.Id, zx, zy, cx, cy);
if (!_chunks.TryGetValue(key, out var chunk) || chunk == null) return true;
var idx = (ty * chunk.WidthTiles) + tx;
if (idx < 0 || idx >= chunk.Walkable.Length) return true;
if (!chunk.Walkable[idx]) return false;
if (chunk.IsPaywall[idx] && !isVip) return false;
return true;
}
public bool IsPositionWalkable(CachedRegion region, float wx, float wy, bool isVip)
{
if (!IsTileWalkable(region, wx, wy, isVip)) return false;
if (!IsTileWalkable(region, wx + 8f, wy, isVip)) return false;
if (!IsTileWalkable(region, wx - 8f, wy, isVip)) return false;
if (!IsTileWalkable(region, wx, wy + 8f, isVip)) return false;
if (!IsTileWalkable(region, wx, wy - 8f, isVip)) return false;
return true;
}
public CachedPortalObject? FindPortalAtPosition(CachedRegion region, float wx, float wy)
{
var gx = (int)MathF.Floor(wx / TileSize);
var gy = (int)MathF.Floor(wy / TileSize);
if (gx < 0 || gy < 0) return null;
var zoneW = region.ChunksPerZoneX * region.ChunkWidthTiles;
var zoneH = region.ChunksPerZoneY * region.ChunkHeightTiles;
if (zoneW <= 0 || zoneH <= 0) return null;
var zx = gx / zoneW;
var zy = gy / zoneH;
if (zx < 0 || zy < 0 || zx >= region.ZonesPerRegionX || zy >= region.ZonesPerRegionY) return null;
var lzx = gx - (zx * zoneW);
var lzy = gy - (zy * zoneH);
var cx = lzx / region.ChunkWidthTiles;
var cy = lzy / region.ChunkHeightTiles;
var tx = lzx % region.ChunkWidthTiles;
var ty = lzy % region.ChunkHeightTiles;
var key = ChunkKey(region.Id, zx, zy, cx, cy);
if (!_chunks.TryGetValue(key, out var chunk) || chunk == null) return null;
foreach (var portal in chunk.Portals)
{
if (tx >= portal.TileX && ty >= portal.TileY &&
tx < (portal.TileX + portal.Width) && ty < (portal.TileY + portal.Height))
return portal;
}
return null;
}
public void InvalidateChunk(int regionId, int zoneX, int zoneY, int chunkX, int chunkY)
{
var key = ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY);
_chunks.TryRemove(key, out _);
_log.LogInformation("Invalidated chunk cache: {Key}", key);
}
public void InvalidateRegion(int regionId)
{
_regions.TryRemove(regionId, out _);
var keysToRemove = _chunks.Keys.Where(k => k.StartsWith($"{regionId}:")).ToList();
foreach (var key in keysToRemove)
_chunks.TryRemove(key, out _);
_log.LogInformation("Invalidated region cache: {RegionId} ({Count} chunks)", regionId, keysToRemove.Count);
}
public async Task EnsureZonesAsync(int regionId, CancellationToken ct = default)
{
var region = await GetRegionAsync(regionId, ct);
if (region == null) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var existing = await db.WorldZones
.Where(z => z.RegionId == regionId)
.Select(z => new { z.ZoneX, z.ZoneY })
.ToListAsync(ct);
var set = existing.Select(z => $"{z.ZoneX}:{z.ZoneY}").ToHashSet(StringComparer.Ordinal);
var now = DateTime.UtcNow;
var changed = false;
for (var y = 0; y < region.ZonesPerRegionY; y++)
for (var x = 0; x < region.ZonesPerRegionX; x++)
{
if (set.Contains($"{x}:{y}")) continue;
db.WorldZones.Add(new WorldZone
{
RegionId = regionId,
ZoneX = x,
ZoneY = y,
Name = $"Zone {x},{y}",
IsEnabled = true,
CreatedAt = now,
UpdatedAt = now
});
changed = true;
}
if (changed) await db.SaveChangesAsync(ct);
}
// ---- Internal ----
private static string ChunkKey(int regionId, int zoneX, int zoneY, int chunkX, int chunkY)
=> $"{regionId}:{zoneX}:{zoneY}:{chunkX}:{chunkY}";
private async Task<CachedChunk?> LoadChunkFromDbAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var region = await GetRegionAsync(regionId, ct);
if (region == null) return null;
var zone = await db.WorldZones.AsNoTracking()
.FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled, ct);
if (zone == null)
{
return BuildEmptyChunk(region, zoneX, zoneY, chunkX, chunkY);
}
var chunk = await db.WorldChunks.AsNoTracking()
.FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == chunkX && c.ChunkY == chunkY, ct);
if (chunk == null)
{
return BuildEmptyChunk(region, zoneX, zoneY, chunkX, chunkY);
}
var tiles = await db.WorldChunkTiles.AsNoTracking()
.Where(t => t.WorldChunkId == chunk.Id)
.OrderBy(t => t.TileY).ThenBy(t => t.TileX)
.ToListAsync(ct);
var objects = await db.WorldChunkObjects.AsNoTracking()
.Include(o => o.ObjectDefinition)
.Where(o => o.WorldChunkId == chunk.Id)
.OrderBy(o => o.TileY).ThenBy(o => o.TileX)
.ToListAsync(ct);
var npcs = await db.WorldChunkNpcSpawns.AsNoTracking()
.Include(n => n.NpcDefinition)
.Where(n => n.WorldChunkId == chunk.Id)
.OrderBy(n => n.TileY).ThenBy(n => n.TileX)
.ToListAsync(ct);
var mobs = await db.WorldChunkMobSpawns.AsNoTracking()
.Include(m => m.MobDefinition)
.Where(m => m.WorldChunkId == chunk.Id)
.OrderBy(m => m.TileY).ThenBy(m => m.TileX)
.ToListAsync(ct);
// Build walkability arrays
var w = region.ChunkWidthTiles;
var h = region.ChunkHeightTiles;
var walkable = new bool[w * h];
var isPaywall = new bool[w * h];
// Default: all walkable unless a tile explicitly says otherwise
Array.Fill(walkable, true);
foreach (var t in tiles)
{
var idx = (t.TileY * w) + t.TileX;
if (idx >= 0 && idx < walkable.Length)
{
walkable[idx] = t.IsWalkable;
isPaywall[idx] = t.IsInvisiblePaywall;
}
}
// Build portal objects
var portals = objects
.Where(o =>
{
var isTeleport = o.ObjectDefinition?.InteractionType == ObjectInteractionType.Teleport ||
(o.MetadataJson?.Contains("portalType", StringComparison.OrdinalIgnoreCase) ?? false);
return isTeleport;
})
.Select(o => new CachedPortalObject
{
Id = o.Id,
TileX = o.TileX,
TileY = o.TileY,
Width = Math.Max(1, o.ObjectDefinition?.Width ?? 1),
Height = Math.Max(1, o.ObjectDefinition?.Height ?? 1),
MetadataJson = o.MetadataJson
})
.ToArray();
// Build DTOs for client serialization (same shapes as original LoadChunkAsync)
var tileDtos = tiles.Select(t => (object)new
{
id = t.Id,
x = t.TileX,
y = t.TileY,
sheetId = t.SheetId,
frameIndex = t.FrameIndex,
isWalkable = t.IsWalkable,
isInvisiblePaywall = t.IsInvisiblePaywall
}).ToArray();
var objectDtos = objects.Select(o => (object)new
{
id = o.Id,
x = o.TileX,
y = o.TileY,
objectDefinitionId = o.ObjectDefinitionId,
objectName = o.ObjectDefinition != null ? o.ObjectDefinition.Name : $"Object {o.ObjectDefinitionId}",
interactionType = o.ObjectDefinition != null ? o.ObjectDefinition.InteractionType.ToString() : null,
rotation = o.Rotation,
metadataJson = o.MetadataJson
}).ToArray();
var npcDtos = npcs.Select(n => (object)new
{
id = n.Id,
x = n.TileX,
y = n.TileY,
npcDefinitionId = n.NpcDefinitionId,
npcName = n.NpcDefinition != null ? n.NpcDefinition.Name : $"NPC {n.NpcDefinitionId}",
rotation = n.Rotation,
metadataJson = n.MetadataJson
}).ToArray();
var mobDtos = mobs.Select(m => (object)new
{
id = m.Id,
x = m.TileX,
y = m.TileY,
mobDefinitionId = m.MobDefinitionId,
mobName = m.MobDefinition != null ? m.MobDefinition.Name : $"Mob {m.MobDefinitionId}",
rotation = m.Rotation,
spawnCount = m.SpawnCount,
respawnSeconds = m.RespawnSeconds,
metadataJson = m.MetadataJson
}).ToArray();
var chunkDto = new
{
id = chunk.Id,
regionId,
zoneX,
zoneY,
chunkX,
chunkY,
version = chunk.Version,
width = w,
height = h
};
_log.LogDebug("Loaded chunk {Key} from DB: {TileCount} tiles, {ObjectCount} objects, {PortalCount} portals",
ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY), tiles.Count, objects.Count, portals.Length);
return new CachedChunk
{
DbId = chunk.Id,
Version = chunk.Version,
RegionId = regionId,
ZoneX = zoneX,
ZoneY = zoneY,
ChunkX = chunkX,
ChunkY = chunkY,
WidthTiles = w,
HeightTiles = h,
Walkable = walkable,
IsPaywall = isPaywall,
ChunkDto = chunkDto,
TileDtos = tileDtos,
ObjectDtos = objectDtos,
NpcDtos = npcDtos,
MobDtos = mobDtos,
Portals = portals
};
}
private static CachedChunk BuildEmptyChunk(CachedRegion region, int zoneX, int zoneY, int chunkX, int chunkY)
{
var w = region.ChunkWidthTiles;
var h = region.ChunkHeightTiles;
var walkable = new bool[w * h];
Array.Fill(walkable, true);
return new CachedChunk
{
DbId = 0,
Version = 0,
RegionId = region.Id,
ZoneX = zoneX,
ZoneY = zoneY,
ChunkX = chunkX,
ChunkY = chunkY,
WidthTiles = w,
HeightTiles = h,
Walkable = walkable,
IsPaywall = new bool[w * h],
ChunkDto = new
{
regionId = region.Id,
zoneX,
zoneY,
chunkX,
chunkY,
version = 0,
width = w,
height = h
},
TileDtos = Array.Empty<object>(),
ObjectDtos = Array.Empty<object>(),
NpcDtos = Array.Empty<object>(),
MobDtos = Array.Empty<object>(),
Portals = Array.Empty<CachedPortalObject>()
};
}
}
+84 -738
View File
@@ -1,6 +1,4 @@
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using DataServer.Data;
using DataServer.Data.Entities;
using GameServices.Auth;
@@ -16,20 +14,18 @@ namespace GameServer.World;
public sealed class WorldHandler : IClientMessageHandler
{
private const int TileSize = 32;
private const float MoveWalk = 120f;
private const float MoveRun = 180f;
private const float TickStepSec = 0.10f;
private static readonly TimeSpan NeutralInputGrace = TimeSpan.FromMilliseconds(180);
private static readonly TimeSpan DirectionalPriorityGrace = TimeSpan.FromMilliseconds(450);
private const long PortalCooldownTicks = 8; // 0.8s at 10hz
private readonly ILogger<WorldHandler> _log;
private readonly ISessionRegistry _sessions;
private readonly IMessageSerializer _ser;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ConcurrentDictionary<Guid, SessionState> _players = new();
private readonly WorldChunkCache _cache;
private readonly WorldMovementService _movement;
private readonly WorldBroadcastService _broadcast;
private readonly ConcurrentDictionary<Guid, WorldSessionState> _players = new();
private readonly ConcurrentDictionary<ulong, long> _portalCooldownByCharacter = new();
private readonly JsonSerializerOptions _json = new() { PropertyNameCaseInsensitive = true };
private readonly bool _debugInput;
private Task? _tickTask;
@@ -40,13 +36,18 @@ public sealed class WorldHandler : IClientMessageHandler
public WorldHandler(
ILogger<WorldHandler> log,
ISessionRegistry sessions,
IMessageSerializer ser,
IServiceScopeFactory scopeFactory)
IServiceScopeFactory scopeFactory,
WorldChunkCache cache,
WorldMovementService movement,
WorldBroadcastService broadcast)
{
_log = log;
_sessions = sessions;
_ser = ser;
_scopeFactory = scopeFactory;
_cache = cache;
_movement = movement;
_broadcast = broadcast;
var debugInputEnv = Environment.GetEnvironmentVariable("WORLD_INPUT_DEBUG");
_debugInput = !string.IsNullOrWhiteSpace(debugInputEnv) &&
(debugInputEnv == "1" || string.Equals(debugInputEnv, "true", StringComparison.OrdinalIgnoreCase));
@@ -65,7 +66,7 @@ public sealed class WorldHandler : IClientMessageHandler
_tickCts = new CancellationTokenSource();
_tickTask = Task.Run(() => TickLoopAsync(_tickCts.Token), _tickCts.Token);
_initialized = true;
_log.LogInformation("WorldHandler initialized");
_log.LogInformation("WorldHandler initialized (cached movement pipeline)");
return Task.CompletedTask;
}
@@ -77,7 +78,7 @@ public sealed class WorldHandler : IClientMessageHandler
if (!_sessions.TryGet(connection.Id, out var accountId, out _))
{
if (opCode == OpCodes.WORLD_INPUT) return;
await SendErrorAsync(connection, "auth_required", ct);
await _broadcast.SendErrorAsync(connection, "auth_required", ct);
return;
}
@@ -89,7 +90,7 @@ public sealed class WorldHandler : IClientMessageHandler
if (opCode == OpCodes.WORLD_INPUT)
{
await HandleInputAsync(connection, accountId, payload, ct);
HandleInput(connection, accountId, payload);
}
}
@@ -98,18 +99,23 @@ public sealed class WorldHandler : IClientMessageHandler
if (_players.TryRemove(connectionId, out var s))
{
_ = PersistPlayerLocationAsync(s);
_ = BroadcastAsync(OpCodes.WORLD_DESPAWN, new { playerId = s.CharacterId, reason = "disconnect" }, s.RegionId, s.ConnectionId);
_ = _broadcast.BroadcastToRegionAsync(
OpCodes.WORLD_DESPAWN,
new { playerId = s.CharacterId, reason = "disconnect" },
s.RegionId, _players, s.ConnectionId);
}
}
// ---- Spawn (DB access only here, once per connect) ----
private async Task HandleSpawnAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var req = Parse<SpawnReq>(payload) ?? new SpawnReq();
var req = WorldInputParser.Parse<WorldInputParser.SpawnReq>(payload) ?? new WorldInputParser.SpawnReq();
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var account = await db.Accounts.AsNoTracking().FirstOrDefaultAsync(a => a.Id == accountId, ct);
if (account == null) { await SendErrorAsync(conn, "account_not_found", ct); return; }
if (account == null) { await _broadcast.SendErrorAsync(conn, "account_not_found", ct); return; }
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.AccountId == accountId && !c.IsDeleted, ct);
if (character == null)
@@ -119,10 +125,11 @@ public sealed class WorldHandler : IClientMessageHandler
await db.SaveChangesAsync(ct);
}
var region = await ResolveRegionAsync(db, req.RegionId ?? character.WorldRegionId, ct);
if (region == null) { await SendErrorAsync(conn, "region_not_found", ct); return; }
var region = await _cache.ResolveRegionAsync(req.RegionId ?? character.WorldRegionId, ct);
if (region == null) { await _broadcast.SendErrorAsync(conn, "region_not_found", ct); return; }
await _cache.EnsureZonesAsync(region.Id, ct);
await EnsureZonesAsync(db, region, ct);
var requestedExplicitChunk = req.ZoneX.HasValue || req.ZoneY.HasValue || req.ChunkX.HasValue || req.ChunkY.HasValue;
var zx = Math.Clamp(req.ZoneX ?? character.WorldZoneX ?? 0, 0, Math.Max(0, region.ZonesPerRegionX - 1));
var zy = Math.Clamp(req.ZoneY ?? character.WorldZoneY ?? 0, 0, Math.Max(0, region.ZonesPerRegionY - 1));
@@ -131,17 +138,17 @@ public sealed class WorldHandler : IClientMessageHandler
var tx = Math.Max(0, Math.Min(region.ChunkWidthTiles - 1, region.ChunkWidthTiles / 2));
var ty = Math.Max(0, Math.Min(region.ChunkHeightTiles - 1, region.ChunkHeightTiles / 2));
var x = requestedExplicitChunk
? WorldPxX(region, zx, cx, tx)
: (character.WorldX ?? WorldPxX(region, zx, cx, tx));
? WorldMovementService.WorldPxX(region, zx, cx, tx)
: (character.WorldX ?? WorldMovementService.WorldPxX(region, zx, cx, tx));
var y = requestedExplicitChunk
? WorldPxY(region, zy, cy, ty)
: (character.WorldY ?? WorldPxY(region, zy, cy, ty));
// Stored world coords should be tile-center aligned; treat 0/invalid as legacy-bad and recover.
if (!float.IsFinite(x) || x < (TileSize / 2f)) x = WorldPxX(region, zx, cx, tx);
if (!float.IsFinite(y) || y < (TileSize / 2f)) y = WorldPxY(region, zy, cy, ty);
? WorldMovementService.WorldPxY(region, zy, cy, ty)
: (character.WorldY ?? WorldMovementService.WorldPxY(region, zy, cy, ty));
var (pzX, pzY, pcX, pcY) = ToChunkPos(region, x, y);
var s = new SessionState
if (!float.IsFinite(x) || x < (TileSize / 2f)) x = WorldMovementService.WorldPxX(region, zx, cx, tx);
if (!float.IsFinite(y) || y < (TileSize / 2f)) y = WorldMovementService.WorldPxY(region, zy, cy, ty);
var (pzX, pzY, pcX, pcY) = WorldMovementService.ToChunkPos(region, x, y);
var s = new WorldSessionState
{
ConnectionId = conn.Id,
Connection = conn,
@@ -169,7 +176,7 @@ public sealed class WorldHandler : IClientMessageHandler
character.LastPlayedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
var initial = await ChunkUpdatesAsync(db, region, s, ct);
var initial = await _broadcast.GetChunkUpdatesAsync(region, s, ct);
var tileSheets = await db.TileMapSheets
.AsNoTracking()
.Where(ts => ts.IsEnabled)
@@ -186,7 +193,8 @@ public sealed class WorldHandler : IClientMessageHandler
sheetH = ts.SheetHeight
})
.ToArrayAsync(ct);
await SendAsync(conn, OpCodes.WORLD_SPAWN, new
await _broadcast.SendAsync(conn, OpCodes.WORLD_SPAWN, new
{
success = true,
player = new { id = s.CharacterId, name = s.Name, x = s.X, y = s.Y, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY, isVip = s.IsVip },
@@ -196,20 +204,22 @@ public sealed class WorldHandler : IClientMessageHandler
nearbyPlayers = VisiblePlayers(s).Select(p => new { id = p.CharacterId, name = p.Name, x = p.X, y = p.Y, facing = p.Facing, speed = p.Speed, isMoving = p.IsMoving })
}, ct);
await BroadcastAsync(OpCodes.WORLD_SPAWN, new
await _broadcast.BroadcastToRegionAsync(OpCodes.WORLD_SPAWN, new
{
success = true,
isRemote = true,
player = new { id = s.CharacterId, name = s.Name, x = s.X, y = s.Y, facing = s.Facing, speed = s.Speed, isMoving = s.IsMoving, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY }
}, s.RegionId, s.ConnectionId);
}, s.RegionId, _players, s.ConnectionId);
}
private Task HandleInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
// ---- Input (pure in-memory, no DB) ----
private void HandleInput(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload)
{
if (!_players.TryGetValue(conn.Id, out var s)) { return Task.CompletedTask; }
if (s.AccountId != accountId) { return Task.CompletedTask; }
var req = ParseWorldInput(payload, s.X, s.Y);
if (req == null) { return Task.CompletedTask; }
if (!_players.TryGetValue(conn.Id, out var s)) return;
if (s.AccountId != accountId) return;
var req = WorldInputParser.ParseWorldInput(payload, s.X, s.Y);
if (req == null) return;
var dx = MathF.Max(-1f, MathF.Min(1f, req.MoveX));
var dy = MathF.Max(-1f, MathF.Min(1f, req.MoveY));
@@ -233,12 +243,9 @@ public sealed class WorldHandler : IClientMessageHandler
}
else if (hasMovement)
{
// Directional input takes precedence over any previously latched target.
s.HasPendingTarget = false;
}
// Store latest input; movement/collision is applied once per world tick to avoid input backlog.
// Keep the last non-neutral direction briefly to avoid neutral packet jitter canceling held input.
if (hasMovement)
{
s.PendingMoveX = dx;
@@ -248,8 +255,6 @@ public sealed class WorldHandler : IClientMessageHandler
}
else
{
// Match dungeon semantics: an explicit neutral directional packet should
// clear movement immediately instead of waiting for neutral-input grace.
var explicitDirectionalStop = req.NativeDirectional && !req.UseTargetPosition;
var shouldStopNow = explicitDirectionalStop ||
(req.IsMovingProvided && !req.IsMoving) ||
@@ -264,9 +269,8 @@ public sealed class WorldHandler : IClientMessageHandler
}
if (!string.IsNullOrWhiteSpace(req.Facing))
{
s.PendingFacing = req.Facing;
}
s.PendingSeq = req.Seq;
if (_debugInput)
@@ -276,9 +280,10 @@ public sealed class WorldHandler : IClientMessageHandler
conn.Id, req.Seq, req.NativeDirectional, req.UseTargetPosition, req.HasTargetPosition,
req.MoveX, req.MoveY, req.TargetX, req.TargetY, s.HasPendingTarget, s.PendingMoveX, s.PendingMoveY, s.X, s.Y);
}
return Task.CompletedTask;
}
// ---- Tick loop (zero DB queries in hot path) ----
private async Task TickLoopAsync(CancellationToken ct)
{
var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100));
@@ -297,20 +302,32 @@ public sealed class WorldHandler : IClientMessageHandler
private async Task SendStatesAsync(CancellationToken ct)
{
if (_players.IsEmpty) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var tick = Interlocked.Read(ref _tick);
foreach (var s in _players.Values)
// Process all players in parallel instead of sequentially
var tasks = _players.Values.Select(s => ProcessPlayerTickAsync(s, tick, ct));
await Task.WhenAll(tasks);
}
private async Task ProcessPlayerTickAsync(WorldSessionState s, long tick, CancellationToken ct)
{
try
{
var region = await db.WorldRegions.AsNoTracking().FirstOrDefaultAsync(r => r.Id == s.RegionId && r.IsEnabled, ct);
if (region == null) { s.Errors.Add("region_not_found"); continue; }
await ApplyPendingInputAsync(db, region, s, ct);
var updates = await ChunkUpdatesAsync(db, region, s, ct);
var region = await _cache.GetRegionAsync(s.RegionId, ct);
if (region == null) { s.Errors.Add("region_not_found"); return; }
// Movement + collision + portal detection (synchronous, pure in-memory)
_movement.ApplyMovement(region, s, tick, _portalCooldownByCharacter, _debugInput);
// Resolve cross-region portal teleports (async cache lookup, rare)
await _movement.ResolvePortalTeleportAsync(s, tick, _portalCooldownByCharacter, ct);
// Chunk updates (from cache, possibly one async load for first-time chunks)
var updates = await _broadcast.GetChunkUpdatesAsync(region, s, ct);
var errs = s.Errors.Count == 0 ? null : s.Errors.Distinct().ToArray();
s.Errors.Clear();
await SendAsync(s.Connection, OpCodes.WORLD_STATE, new
await _broadcast.SendAsync(s.Connection, OpCodes.WORLD_STATE, new
{
tick,
ackSeq = s.Seq,
@@ -322,593 +339,24 @@ public sealed class WorldHandler : IClientMessageHandler
}, ct);
s.PendingPortalEvent = null;
}
}
private async Task ApplyPendingInputAsync(GameDbContext db, WorldRegion region, SessionState s, CancellationToken ct)
{
var beforeX = s.X;
var beforeY = s.Y;
float dx;
float dy;
var targetMode = s.HasPendingTarget;
var targetX = s.PendingTargetX;
var targetY = s.PendingTargetY;
var stepScale = 1f;
if (s.HasPendingTarget)
catch (Exception ex)
{
var tx = targetX - s.X;
var ty = targetY - s.Y;
var targetDist = MathF.Sqrt((tx * tx) + (ty * ty));
if (targetDist <= 1f)
{
s.HasPendingTarget = false;
targetMode = false;
dx = s.PendingMoveX;
dy = s.PendingMoveY;
}
else
{
dx = tx / targetDist;
dy = ty / targetDist;
var speedForScale = s.PendingIsRunning ? MoveRun : MoveWalk;
var maxTickStep = speedForScale * TickStepSec;
if (maxTickStep > 0.001f)
{
stepScale = MathF.Min(1f, targetDist / maxTickStep);
}
}
}
else
{
dx = s.PendingMoveX;
dy = s.PendingMoveY;
}
dx = MathF.Max(-1f, MathF.Min(1f, dx));
dy = MathF.Max(-1f, MathF.Min(1f, dy));
var len = MathF.Sqrt((dx * dx) + (dy * dy));
if (len > 1f)
{
dx /= len;
dy /= len;
}
var speed = s.PendingIsRunning ? MoveRun : MoveWalk;
var effectiveSpeed = speed * stepScale;
var nextX = s.X + (dx * effectiveSpeed * TickStepSec);
var nextY = s.Y + (dy * effectiveSpeed * TickStepSec);
var moving = MathF.Abs(dx) > 0.001f || MathF.Abs(dy) > 0.001f;
if (moving)
{
if (await WalkableAsync(db, region, nextX, s.Y, s.IsVip, ct)) s.X = nextX; else s.Errors.Add("blocked_non_walkable");
if (await WalkableAsync(db, region, s.X, nextY, s.IsVip, ct)) s.Y = nextY; else s.Errors.Add("blocked_non_walkable");
}
if (targetMode && s.HasPendingTarget)
{
var rx = targetX - s.X;
var ry = targetY - s.Y;
var remaining = MathF.Sqrt((rx * rx) + (ry * ry));
if (remaining <= 1f)
{
s.HasPendingTarget = false;
}
}
var (zx, zy, cx, cy) = ToChunkPos(region, s.X, s.Y);
s.ZoneX = zx; s.ZoneY = zy; s.ChunkX = cx; s.ChunkY = cy;
s.VelX = moving ? dx * effectiveSpeed : 0f;
s.VelY = moving ? dy * effectiveSpeed : 0f;
s.Speed = moving ? effectiveSpeed : 0f;
s.IsMoving = moving;
s.Facing = Facing(s.PendingFacing, dx, dy, s.Facing);
s.Seq = s.PendingSeq;
await TryTriggerPortalAsync(db, region, s, ct);
if (_debugInput)
{
_log.LogInformation(
"WORLD_TICK seq={Seq} targetMode={TargetMode} hasPendingTarget={HasPendingTarget} input=({InputX:F3},{InputY:F3}) effSpeed={Speed:F1} vel=({VelX:F1},{VelY:F1}) pos=({BeforeX:F2},{BeforeY:F2})->({AfterX:F2},{AfterY:F2})",
s.Seq, targetMode, s.HasPendingTarget, dx, dy, s.Speed, s.VelX, s.VelY, beforeX, beforeY, s.X, s.Y);
_log.LogWarning(ex, "Error processing tick for player {CharacterId}", s.CharacterId);
}
}
private IEnumerable<SessionState> VisiblePlayers(SessionState self)
=> _players.Values.Where(p => p.ConnectionId != self.ConnectionId && p.RegionId == self.RegionId && Math.Abs(p.ZoneX - self.ZoneX) <= 1 && Math.Abs(p.ZoneY - self.ZoneY) <= 1 && Math.Abs(p.X - self.X) <= (TileSize * 48) && Math.Abs(p.Y - self.Y) <= (TileSize * 48));
private IEnumerable<WorldSessionState> VisiblePlayers(WorldSessionState self)
=> _players.Values.Where(p =>
p.ConnectionId != self.ConnectionId &&
p.RegionId == self.RegionId &&
Math.Abs(p.ZoneX - self.ZoneX) <= 1 &&
Math.Abs(p.ZoneY - self.ZoneY) <= 1 &&
Math.Abs(p.X - self.X) <= (TileSize * 48) &&
Math.Abs(p.Y - self.Y) <= (TileSize * 48));
private async Task<List<(string type, object payload)>> ChunkUpdatesAsync(GameDbContext db, WorldRegion region, SessionState s, CancellationToken ct)
{
var required = new HashSet<string>(StringComparer.Ordinal);
var list = new List<(string, object)>();
var chunksPerRegionX = region.ZonesPerRegionX * region.ChunksPerZoneX;
var chunksPerRegionY = region.ZonesPerRegionY * region.ChunksPerZoneY;
if (chunksPerRegionX <= 0 || chunksPerRegionY <= 0)
{
return list;
}
// ---- Persistence (only on disconnect) ----
var centerAbsChunkX = (s.ZoneX * region.ChunksPerZoneX) + s.ChunkX;
var centerAbsChunkY = (s.ZoneY * region.ChunksPerZoneY) + s.ChunkY;
for (var ay = Math.Max(0, centerAbsChunkY - 1); ay <= Math.Min(chunksPerRegionY - 1, centerAbsChunkY + 1); ay++)
for (var ax = Math.Max(0, centerAbsChunkX - 1); ax <= Math.Min(chunksPerRegionX - 1, centerAbsChunkX + 1); ax++)
{
var zx = ax / region.ChunksPerZoneX;
var zy = ay / region.ChunksPerZoneY;
var cx = ax % region.ChunksPerZoneX;
var cy = ay % region.ChunksPerZoneY;
var key = $"{region.Id}:{zx}:{zy}:{cx}:{cy}";
required.Add(key);
// Load chunk payload only when it enters the visible set.
// Runtime chunk edits should be pushed by dedicated world-edit services/events.
if (!s.ChunkVersions.ContainsKey(key))
{
var data = await LoadChunkAsync(db, region, zx, zy, cx, cy, ct);
s.ChunkVersions[key] = data.version;
list.Add(("chunk_full", new { type = "chunk_full", chunk = data.chunk, tiles = data.tiles, objects = data.objects, npcs = data.npcs, mobs = data.mobs }));
}
}
foreach (var stale in s.ChunkVersions.Keys.Where(k => !required.Contains(k)).ToList())
{
s.ChunkVersions.Remove(stale);
var p = stale.Split(':');
list.Add(("chunk_unload", new { type = "chunk_unload", regionId = int.Parse(p[0]), zoneX = int.Parse(p[1]), zoneY = int.Parse(p[2]), chunkX = int.Parse(p[3]), chunkY = int.Parse(p[4]) }));
}
return list;
}
private async Task<(long version, object chunk, object[] tiles, object[] objects, object[] npcs, object[] mobs)> LoadChunkAsync(GameDbContext db, WorldRegion region, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct)
{
var zone = await db.WorldZones.AsNoTracking().FirstOrDefaultAsync(z => z.RegionId == region.Id && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled, ct);
if (zone == null)
return (0, new { regionId = region.Id, zoneX, zoneY, chunkX, chunkY, version = 0, width = region.ChunkWidthTiles, height = region.ChunkHeightTiles }, Array.Empty<object>(), Array.Empty<object>(), Array.Empty<object>(), Array.Empty<object>());
var chunk = await db.WorldChunks.AsNoTracking().FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == chunkX && c.ChunkY == chunkY, ct);
if (chunk == null)
return (0, new { regionId = region.Id, zoneX, zoneY, chunkX, chunkY, version = 0, width = region.ChunkWidthTiles, height = region.ChunkHeightTiles }, Array.Empty<object>(), Array.Empty<object>(), Array.Empty<object>(), Array.Empty<object>());
var tiles = await db.WorldChunkTiles.AsNoTracking().Where(t => t.WorldChunkId == chunk.Id).OrderBy(t => t.TileY).ThenBy(t => t.TileX).Select(t => new { id = t.Id, x = t.TileX, y = t.TileY, sheetId = t.SheetId, frameIndex = t.FrameIndex, isWalkable = t.IsWalkable, isInvisiblePaywall = t.IsInvisiblePaywall }).ToArrayAsync(ct);
var objects = await db.WorldChunkObjects.AsNoTracking().Include(o => o.ObjectDefinition).Where(o => o.WorldChunkId == chunk.Id).OrderBy(o => o.TileY).ThenBy(o => o.TileX).Select(o => new { id = o.Id, x = o.TileX, y = o.TileY, objectDefinitionId = o.ObjectDefinitionId, objectName = o.ObjectDefinition != null ? o.ObjectDefinition.Name : $"Object {o.ObjectDefinitionId}", interactionType = o.ObjectDefinition != null ? o.ObjectDefinition.InteractionType.ToString() : null, rotation = o.Rotation, metadataJson = o.MetadataJson }).ToArrayAsync(ct);
var npcs = await db.WorldChunkNpcSpawns.AsNoTracking().Include(n => n.NpcDefinition).Where(n => n.WorldChunkId == chunk.Id).OrderBy(n => n.TileY).ThenBy(n => n.TileX).Select(n => new { id = n.Id, x = n.TileX, y = n.TileY, npcDefinitionId = n.NpcDefinitionId, npcName = n.NpcDefinition != null ? n.NpcDefinition.Name : $"NPC {n.NpcDefinitionId}", rotation = n.Rotation, metadataJson = n.MetadataJson }).ToArrayAsync(ct);
var mobs = await db.WorldChunkMobSpawns.AsNoTracking().Include(m => m.MobDefinition).Where(m => m.WorldChunkId == chunk.Id).OrderBy(m => m.TileY).ThenBy(m => m.TileX).Select(m => new { id = m.Id, x = m.TileX, y = m.TileY, mobDefinitionId = m.MobDefinitionId, mobName = m.MobDefinition != null ? m.MobDefinition.Name : $"Mob {m.MobDefinitionId}", rotation = m.Rotation, spawnCount = m.SpawnCount, respawnSeconds = m.RespawnSeconds, metadataJson = m.MetadataJson }).ToArrayAsync(ct);
return (chunk.Version, new { id = chunk.Id, regionId = region.Id, zoneX, zoneY, chunkX, chunkY, version = chunk.Version, width = region.ChunkWidthTiles, height = region.ChunkHeightTiles }, tiles.Cast<object>().ToArray(), objects.Cast<object>().ToArray(), npcs.Cast<object>().ToArray(), mobs.Cast<object>().ToArray());
}
private async Task<bool> WalkableAsync(GameDbContext db, WorldRegion region, float wx, float wy, bool isVip, CancellationToken ct)
{
var checks = new[] { (0f, 0f), (8f, 0f), (-8f, 0f), (0f, 8f), (0f, -8f) };
foreach (var (ox, oy) in checks)
{
var tile = await ResolveTileAsync(db, region, wx + ox, wy + oy, ct);
if (tile == null) continue;
if (!tile.IsWalkable) return false;
if (tile.IsInvisiblePaywall && !isVip) return false;
}
return true;
}
private async Task TryTriggerPortalAsync(GameDbContext db, WorldRegion region, SessionState s, CancellationToken ct)
{
var nowTick = Interlocked.Read(ref _tick);
if (_portalCooldownByCharacter.TryGetValue(s.CharacterId, out var untilTick) && untilTick > nowTick)
{
return;
}
var portalObject = await ResolvePortalObjectAtPositionAsync(db, region, s.X, s.Y, ct);
if (portalObject == null || string.IsNullOrWhiteSpace(portalObject.MetadataJson))
{
return;
}
if (!TryParsePortalMetadata(portalObject.MetadataJson, out var portalMeta))
{
return;
}
_portalCooldownByCharacter[s.CharacterId] = nowTick + PortalCooldownTicks;
if (portalMeta.PortalType.Equals("world", StringComparison.OrdinalIgnoreCase))
{
if (TryResolveWorldPortalTarget(portalMeta, out var targetRegionId, out var targetZoneX, out var targetZoneY, out var targetChunkX, out var targetChunkY, out var targetTileX, out var targetTileY))
{
var targetRegion = await db.WorldRegions.AsNoTracking().FirstOrDefaultAsync(r => r.Id == targetRegionId && r.IsEnabled, ct);
if (targetRegion != null)
{
var nx = WorldPxX(targetRegion, targetZoneX, targetChunkX, targetTileX);
var ny = WorldPxY(targetRegion, targetZoneY, targetChunkY, targetTileY);
s.RegionId = targetRegion.Id;
s.X = nx;
s.Y = ny;
var (zx, zy, cx, cy) = ToChunkPos(targetRegion, s.X, s.Y);
s.ZoneX = zx; s.ZoneY = zy; s.ChunkX = cx; s.ChunkY = cy;
s.PendingPortalEvent = new
{
type = "world_teleport",
sourceObjectId = portalObject.Id,
regionId = s.RegionId,
zoneX = s.ZoneX,
zoneY = s.ZoneY,
chunkX = s.ChunkX,
chunkY = s.ChunkY,
x = s.X,
y = s.Y
};
return;
}
}
s.Errors.Add("portal_world_target_invalid");
return;
}
s.PendingPortalEvent = new
{
type = "dungeon_request",
sourceObjectId = portalObject.Id,
portalType = portalMeta.PortalType,
dungeonTemplateId = portalMeta.DungeonTemplateId,
randomTier = portalMeta.RandomTier,
levelBracketMin = portalMeta.LevelBracketMin,
levelBracketMax = portalMeta.LevelBracketMax
};
}
private async Task<WorldChunkObject?> ResolvePortalObjectAtPositionAsync(GameDbContext db, WorldRegion region, float wx, float wy, CancellationToken ct)
{
var gx = (int)MathF.Floor(wx / TileSize);
var gy = (int)MathF.Floor(wy / TileSize);
if (gx < 0 || gy < 0) return null;
var zoneW = region.ChunksPerZoneX * region.ChunkWidthTiles;
var zoneH = region.ChunksPerZoneY * region.ChunkHeightTiles;
if (zoneW <= 0 || zoneH <= 0) return null;
var zx = gx / zoneW;
var zy = gy / zoneH;
if (zx < 0 || zy < 0 || zx >= region.ZonesPerRegionX || zy >= region.ZonesPerRegionY) return null;
var lzx = gx - (zx * zoneW);
var lzy = gy - (zy * zoneH);
var cx = lzx / region.ChunkWidthTiles;
var cy = lzy / region.ChunkHeightTiles;
var tx = lzx % region.ChunkWidthTiles;
var ty = lzy % region.ChunkHeightTiles;
var zone = await db.WorldZones.AsNoTracking().FirstOrDefaultAsync(z => z.RegionId == region.Id && z.ZoneX == zx && z.ZoneY == zy && z.IsEnabled, ct);
if (zone == null) return null;
var chunk = await db.WorldChunks.AsNoTracking().FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == cx && c.ChunkY == cy, ct);
if (chunk == null) return null;
var objects = await db.WorldChunkObjects
.AsNoTracking()
.Include(o => o.ObjectDefinition)
.Where(o => o.WorldChunkId == chunk.Id)
.ToListAsync(ct);
return objects.FirstOrDefault(o =>
{
var w = Math.Max(1, o.ObjectDefinition?.Width ?? 1);
var h = Math.Max(1, o.ObjectDefinition?.Height ?? 1);
var isTeleport = o.ObjectDefinition?.InteractionType == ObjectInteractionType.Teleport ||
(o.MetadataJson?.Contains("portalType", StringComparison.OrdinalIgnoreCase) ?? false);
if (!isTeleport) return false;
return tx >= o.TileX && ty >= o.TileY && tx < (o.TileX + w) && ty < (o.TileY + h);
});
}
private static bool TryParsePortalMetadata(string metadataJson, out WorldPortalMetadata metadata)
{
metadata = new WorldPortalMetadata();
try
{
var parsed = JsonSerializer.Deserialize<WorldPortalMetadata>(metadataJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (parsed == null || string.IsNullOrWhiteSpace(parsed.PortalType))
{
return false;
}
metadata = parsed;
return true;
}
catch
{
return false;
}
}
private static bool TryResolveWorldPortalTarget(
WorldPortalMetadata m,
out int targetRegionId,
out int targetZoneX,
out int targetZoneY,
out int targetChunkX,
out int targetChunkY,
out int targetTileX,
out int targetTileY)
{
targetRegionId = m.TargetRegionId ?? 0;
targetZoneX = m.TargetZoneX ?? 0;
targetZoneY = m.TargetZoneY ?? 0;
targetChunkX = m.TargetChunkX ?? 0;
targetChunkY = m.TargetChunkY ?? 0;
targetTileX = m.TargetTileX ?? 0;
targetTileY = m.TargetTileY ?? 0;
return targetRegionId > 0;
}
private async Task<WorldChunkTile?> ResolveTileAsync(GameDbContext db, WorldRegion region, float wx, float wy, CancellationToken ct)
{
var gx = (int)MathF.Floor(wx / TileSize);
var gy = (int)MathF.Floor(wy / TileSize);
if (gx < 0 || gy < 0) return null;
var zoneW = region.ChunksPerZoneX * region.ChunkWidthTiles;
var zoneH = region.ChunksPerZoneY * region.ChunkHeightTiles;
if (zoneW <= 0 || zoneH <= 0) return null;
var zx = gx / zoneW; var zy = gy / zoneH;
if (zx < 0 || zy < 0 || zx >= region.ZonesPerRegionX || zy >= region.ZonesPerRegionY) return null;
var lzx = gx - (zx * zoneW); var lzy = gy - (zy * zoneH);
var cx = lzx / region.ChunkWidthTiles; var cy = lzy / region.ChunkHeightTiles;
var tx = lzx % region.ChunkWidthTiles; var ty = lzy % region.ChunkHeightTiles;
var zone = await db.WorldZones.AsNoTracking().FirstOrDefaultAsync(z => z.RegionId == region.Id && z.ZoneX == zx && z.ZoneY == zy && z.IsEnabled, ct);
if (zone == null) return null;
var chunk = await db.WorldChunks.AsNoTracking().FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == cx && c.ChunkY == cy, ct);
if (chunk == null) return null;
return await db.WorldChunkTiles.AsNoTracking().FirstOrDefaultAsync(t => t.WorldChunkId == chunk.Id && t.TileX == tx && t.TileY == ty, ct);
}
private async Task<WorldRegion?> ResolveRegionAsync(GameDbContext db, int? requestedId, CancellationToken ct)
{
if (requestedId.HasValue && requestedId.Value > 0)
{
var match = await db.WorldRegions.AsNoTracking().FirstOrDefaultAsync(r => r.Id == requestedId.Value && r.IsEnabled, ct);
if (match != null) return match;
}
return await db.WorldRegions.AsNoTracking().Where(r => r.IsEnabled).OrderBy(r => r.Id).FirstOrDefaultAsync(ct);
}
private async Task EnsureZonesAsync(GameDbContext db, WorldRegion region, CancellationToken ct)
{
var existing = await db.WorldZones.Where(z => z.RegionId == region.Id).Select(z => new { z.ZoneX, z.ZoneY }).ToListAsync(ct);
var set = existing.Select(z => $"{z.ZoneX}:{z.ZoneY}").ToHashSet(StringComparer.Ordinal);
var now = DateTime.UtcNow; var changed = false;
for (var y = 0; y < region.ZonesPerRegionY; y++)
for (var x = 0; x < region.ZonesPerRegionX; x++)
{
if (set.Contains($"{x}:{y}")) continue;
db.WorldZones.Add(new WorldZone { RegionId = region.Id, ZoneX = x, ZoneY = y, Name = $"Zone {x},{y}", IsEnabled = true, CreatedAt = now, UpdatedAt = now });
changed = true;
}
if (changed) await db.SaveChangesAsync(ct);
}
private static float WorldPxX(WorldRegion r, int zoneX, int chunkX, int tileX) => (((zoneX * (r.ChunksPerZoneX * r.ChunkWidthTiles)) + (chunkX * r.ChunkWidthTiles) + tileX) * TileSize) + (TileSize / 2f);
private static float WorldPxY(WorldRegion r, int zoneY, int chunkY, int tileY) => (((zoneY * (r.ChunksPerZoneY * r.ChunkHeightTiles)) + (chunkY * r.ChunkHeightTiles) + tileY) * TileSize) + (TileSize / 2f);
private static (int zx, int zy, int cx, int cy) ToChunkPos(WorldRegion r, float wx, float wy)
{
var gx = Math.Max(0, (int)MathF.Floor(wx / TileSize));
var gy = Math.Max(0, (int)MathF.Floor(wy / TileSize));
var zoneW = r.ChunksPerZoneX * r.ChunkWidthTiles;
var zoneH = r.ChunksPerZoneY * r.ChunkHeightTiles;
var zx = Math.Clamp(zoneW > 0 ? gx / zoneW : 0, 0, Math.Max(0, r.ZonesPerRegionX - 1));
var zy = Math.Clamp(zoneH > 0 ? gy / zoneH : 0, 0, Math.Max(0, r.ZonesPerRegionY - 1));
var lzx = gx - (zx * zoneW); var lzy = gy - (zy * zoneH);
var cx = Math.Clamp(r.ChunkWidthTiles > 0 ? lzx / r.ChunkWidthTiles : 0, 0, Math.Max(0, r.ChunksPerZoneX - 1));
var cy = Math.Clamp(r.ChunkHeightTiles > 0 ? lzy / r.ChunkHeightTiles : 0, 0, Math.Max(0, r.ChunksPerZoneY - 1));
return (zx, zy, cx, cy);
}
private static string Facing(string? facing, float dx, float dy, string fallback)
{
if (!string.IsNullOrWhiteSpace(facing))
{
var f = facing.Trim().ToLowerInvariant();
if (f is "up" or "down" or "left" or "right") return f;
}
if (MathF.Abs(dx) > MathF.Abs(dy)) return dx >= 0 ? "right" : "left";
if (MathF.Abs(dy) > 0.001f) return dy >= 0 ? "down" : "up";
return fallback;
}
private T? Parse<T>(ReadOnlyMemory<byte> payload)
{
try
{
if (payload.IsEmpty) return default;
var s = Encoding.UTF8.GetString(payload.Span);
if (string.IsNullOrWhiteSpace(s)) return default;
return JsonSerializer.Deserialize<T>(s, _json);
}
catch { return default; }
}
private InputReq? ParseWorldInput(ReadOnlyMemory<byte> payload, float currentX, float currentY)
{
if (payload.IsEmpty) return null;
try
{
using var doc = JsonDocument.Parse(Encoding.UTF8.GetString(payload.Span));
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return null;
// Some clients wrap movement inside an "input" object.
var source = root;
if (TryGetProperty(root, "input", out var nested) && nested.ValueKind == JsonValueKind.Object)
{
source = nested;
}
float moveX = 0f;
float moveY = 0f;
var hasMoveX = TryGetFloat(source, out moveX, "moveX", "dx", "inputX", "horizontal");
var hasMoveY = TryGetFloat(source, out moveY, "moveY", "dy", "inputY", "vertical");
var hasRawX = TryGetFloat(source, out var rawX, "x");
var hasRawY = TryGetFloat(source, out var rawY, "y");
// Support directional top-level/nested x/y values in [-1,1].
if (!hasMoveX && hasRawX && IsDirectionalValue(rawX))
{
moveX = rawX;
hasMoveX = true;
}
if (!hasMoveY && hasRawY && IsDirectionalValue(rawY))
{
moveY = rawY;
hasMoveY = true;
}
// Compatibility: allow absolute target movement only when target fields are explicit.
// Plain x/y frequently carry client render position and must not drive world movement.
var hasAbsTarget = false;
var useAbsTarget = false;
var absTargetX = 0f;
var absTargetY = 0f;
var hadNativeDirectional = hasMoveX || hasMoveY;
var hasTargetX = TryGetFloat(source, out var parsedTargetX, "targetX", "worldTargetX");
var hasTargetY = TryGetFloat(source, out var parsedTargetY, "targetY", "worldTargetY");
if (hasTargetX && hasTargetY)
{
hasAbsTarget = true;
absTargetX = parsedTargetX;
absTargetY = parsedTargetY;
var dx = absTargetX - currentX;
var dy = absTargetY - currentY;
var len = MathF.Sqrt((dx * dx) + (dy * dy));
var directionalIsNeutral = (!hasMoveX && !hasMoveY) ||
(MathF.Abs(moveX) <= 0.01f && MathF.Abs(moveY) <= 0.01f);
if (directionalIsNeutral && len > 0.5f)
{
useAbsTarget = true;
moveX = dx / len;
moveY = dy / len;
hasMoveX = true;
hasMoveY = true;
}
}
if (!hasMoveX && !hasMoveY)
{
return null;
}
TryGetUInt(source, out var seq, "seq", "clientSeq", "inputSeq");
TryGetBool(source, out var isRunning, "isRunning", "running", "sprint");
var hasIsMoving = TryGetBool(source, out var isMoving, "isMoving", "moving");
TryGetString(source, out var facing, "facing", "dir", "direction");
return new InputReq
{
Seq = seq,
MoveX = moveX,
MoveY = moveY,
IsRunning = isRunning,
Facing = facing,
IsMovingProvided = hasIsMoving,
IsMoving = isMoving,
HasTargetPosition = hasAbsTarget,
UseTargetPosition = useAbsTarget,
NativeDirectional = hadNativeDirectional,
TargetX = absTargetX,
TargetY = absTargetY
};
}
catch
{
return null;
}
}
private static bool TryGetProperty(JsonElement source, string name, out JsonElement value)
{
foreach (var p in source.EnumerateObject())
{
if (string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
{
value = p.Value;
return true;
}
}
value = default;
return false;
}
private static bool TryGetFloat(JsonElement source, out float value, params string[] names)
{
foreach (var n in names)
{
if (!TryGetProperty(source, n, out var e)) continue;
if (e.ValueKind == JsonValueKind.Number && e.TryGetSingle(out value)) return true;
if (e.ValueKind == JsonValueKind.String && float.TryParse(e.GetString(), out value)) return true;
}
value = 0f;
return false;
}
private static bool TryGetUInt(JsonElement source, out uint value, params string[] names)
{
foreach (var n in names)
{
if (!TryGetProperty(source, n, out var e)) continue;
if (e.ValueKind == JsonValueKind.Number && e.TryGetUInt32(out value)) return true;
if (e.ValueKind == JsonValueKind.String && uint.TryParse(e.GetString(), out value)) return true;
}
value = 0;
return false;
}
private static bool TryGetBool(JsonElement source, out bool value, params string[] names)
{
foreach (var n in names)
{
if (!TryGetProperty(source, n, out var e)) continue;
if (e.ValueKind == JsonValueKind.True || e.ValueKind == JsonValueKind.False)
{
value = e.GetBoolean();
return true;
}
if (e.ValueKind == JsonValueKind.Number && e.TryGetInt32(out var num))
{
value = num != 0;
return true;
}
if (e.ValueKind == JsonValueKind.String && bool.TryParse(e.GetString(), out value))
{
return true;
}
}
value = false;
return false;
}
private static bool TryGetString(JsonElement source, out string? value, params string[] names)
{
foreach (var n in names)
{
if (!TryGetProperty(source, n, out var e)) continue;
if (e.ValueKind == JsonValueKind.String)
{
value = e.GetString();
return true;
}
}
value = null;
return false;
}
private static bool IsDirectionalValue(float value)
=> float.IsFinite(value) && value >= -1.05f && value <= 1.05f;
private async Task BroadcastAsync(int opCode, object payload, int regionId, Guid? exceptConnectionId = null)
{
var tasks = _players.Values
.Where(p => p.RegionId == regionId && (exceptConnectionId == null || p.ConnectionId != exceptConnectionId.Value))
.Select(p => SendAsync(p.Connection, opCode, payload, CancellationToken.None));
await Task.WhenAll(tasks);
}
private async Task PersistPlayerLocationAsync(SessionState s)
private async Task PersistPlayerLocationAsync(WorldSessionState s)
{
try
{
@@ -932,106 +380,4 @@ public sealed class WorldHandler : IClientMessageHandler
_log.LogWarning(ex, "Failed to persist world location for character {CharacterId}", s.CharacterId);
}
}
private async Task SendAsync(IConnection connection, int opCode, object payload, CancellationToken ct)
{
try
{
var bytes = _ser.Serialize(payload);
var msg = new ServerMessage(opCode, bytes);
await connection.SendAsync(_ser.Serialize(msg), ct);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed sending opcode {Op} to {ConnectionId}", opCode, connection.Id);
}
}
private Task SendErrorAsync(IConnection connection, string error, CancellationToken ct) => SendAsync(connection, OpCodes.ERROR, new { error }, ct);
private sealed class SessionState
{
public Guid ConnectionId { get; set; }
public IConnection Connection { get; set; } = null!;
public ulong AccountId { get; set; }
public ulong CharacterId { get; set; }
public string Name { get; set; } = "";
public bool IsVip { get; set; }
public int RegionId { get; set; }
public int ZoneX { get; set; }
public int ZoneY { get; set; }
public int ChunkX { get; set; }
public int ChunkY { get; set; }
public float X { get; set; }
public float Y { get; set; }
public float VelX { get; set; }
public float VelY { get; set; }
public string Facing { get; set; } = "down";
public float Speed { get; set; }
public bool IsMoving { get; set; }
public uint Seq { get; set; }
public float PendingMoveX { get; set; }
public float PendingMoveY { get; set; }
public bool PendingIsRunning { get; set; }
public string? PendingFacing { get; set; }
public uint PendingSeq { get; set; }
public DateTime LastNonNeutralInputAt { get; set; } = DateTime.UtcNow;
public DateTime PreferDirectionalUntil { get; set; } = DateTime.MinValue;
public bool HasPendingTarget { get; set; }
public float PendingTargetX { get; set; }
public float PendingTargetY { get; set; }
public Dictionary<string, long> ChunkVersions { get; } = new(StringComparer.Ordinal);
public List<string> Errors { get; } = new();
public object? PendingPortalEvent { get; set; }
}
private sealed class SpawnReq
{
public int? RegionId { get; set; }
public int? ZoneX { get; set; }
public int? ZoneY { get; set; }
public int? ChunkX { get; set; }
public int? ChunkY { get; set; }
}
private sealed class InputReq
{
public uint Seq { get; set; }
public float MoveX { get; set; }
public float MoveY { get; set; }
public bool IsRunning { get; set; }
public string? Facing { get; set; }
public bool IsMovingProvided { get; set; }
public bool IsMoving { get; set; }
public bool HasTargetPosition { get; set; }
public bool UseTargetPosition { get; set; }
public bool NativeDirectional { get; set; }
public float TargetX { get; set; }
public float TargetY { get; set; }
}
private sealed class LegacyInputReq
{
public uint ClientSeq { get; set; }
public float Dx { get; set; }
public float Dy { get; set; }
public bool IsRunning { get; set; }
public string? Facing { get; set; }
}
private sealed class WorldPortalMetadata
{
public string PortalType { get; set; } = "";
public int? TargetRegionId { get; set; }
public int? TargetZoneX { get; set; }
public int? TargetZoneY { get; set; }
public int? TargetChunkX { get; set; }
public int? TargetChunkY { get; set; }
public int? TargetTileX { get; set; }
public int? TargetTileY { get; set; }
public int? DungeonTemplateId { get; set; }
public int? RandomTier { get; set; }
public int? LevelBracketMin { get; set; }
public int? LevelBracketMax { get; set; }
}
}
+214
View File
@@ -0,0 +1,214 @@
using System.Text;
using System.Text.Json;
namespace GameServer.World;
public static class WorldInputParser
{
private static readonly JsonSerializerOptions JsonOpts = new() { PropertyNameCaseInsensitive = true };
public sealed class InputReq
{
public uint Seq { get; set; }
public float MoveX { get; set; }
public float MoveY { get; set; }
public bool IsRunning { get; set; }
public string? Facing { get; set; }
public bool IsMovingProvided { get; set; }
public bool IsMoving { get; set; }
public bool HasTargetPosition { get; set; }
public bool UseTargetPosition { get; set; }
public bool NativeDirectional { get; set; }
public float TargetX { get; set; }
public float TargetY { get; set; }
}
public sealed class SpawnReq
{
public int? RegionId { get; set; }
public int? ZoneX { get; set; }
public int? ZoneY { get; set; }
public int? ChunkX { get; set; }
public int? ChunkY { get; set; }
}
public static T? Parse<T>(ReadOnlyMemory<byte> payload)
{
try
{
if (payload.IsEmpty) return default;
var s = Encoding.UTF8.GetString(payload.Span);
if (string.IsNullOrWhiteSpace(s)) return default;
return JsonSerializer.Deserialize<T>(s, JsonOpts);
}
catch { return default; }
}
public static InputReq? ParseWorldInput(ReadOnlyMemory<byte> payload, float currentX, float currentY)
{
if (payload.IsEmpty) return null;
try
{
using var doc = JsonDocument.Parse(Encoding.UTF8.GetString(payload.Span));
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return null;
var source = root;
if (TryGetProperty(root, "input", out var nested) && nested.ValueKind == JsonValueKind.Object)
source = nested;
float moveX = 0f;
float moveY = 0f;
var hasMoveX = TryGetFloat(source, out moveX, "moveX", "dx", "inputX", "horizontal");
var hasMoveY = TryGetFloat(source, out moveY, "moveY", "dy", "inputY", "vertical");
var hasRawX = TryGetFloat(source, out var rawX, "x");
var hasRawY = TryGetFloat(source, out var rawY, "y");
if (!hasMoveX && hasRawX && IsDirectionalValue(rawX))
{
moveX = rawX;
hasMoveX = true;
}
if (!hasMoveY && hasRawY && IsDirectionalValue(rawY))
{
moveY = rawY;
hasMoveY = true;
}
var hasAbsTarget = false;
var useAbsTarget = false;
var absTargetX = 0f;
var absTargetY = 0f;
var hadNativeDirectional = hasMoveX || hasMoveY;
var hasTargetX = TryGetFloat(source, out var parsedTargetX, "targetX", "worldTargetX");
var hasTargetY = TryGetFloat(source, out var parsedTargetY, "targetY", "worldTargetY");
if (hasTargetX && hasTargetY)
{
hasAbsTarget = true;
absTargetX = parsedTargetX;
absTargetY = parsedTargetY;
var dx = absTargetX - currentX;
var dy = absTargetY - currentY;
var len = MathF.Sqrt((dx * dx) + (dy * dy));
var directionalIsNeutral = (!hasMoveX && !hasMoveY) ||
(MathF.Abs(moveX) <= 0.01f && MathF.Abs(moveY) <= 0.01f);
if (directionalIsNeutral && len > 0.5f)
{
useAbsTarget = true;
moveX = dx / len;
moveY = dy / len;
hasMoveX = true;
hasMoveY = true;
}
}
if (!hasMoveX && !hasMoveY)
return null;
TryGetUInt(source, out var seq, "seq", "clientSeq", "inputSeq");
TryGetBool(source, out var isRunning, "isRunning", "running", "sprint");
var hasIsMoving = TryGetBool(source, out var isMoving, "isMoving", "moving");
TryGetString(source, out var facing, "facing", "dir", "direction");
return new InputReq
{
Seq = seq,
MoveX = moveX,
MoveY = moveY,
IsRunning = isRunning,
Facing = facing,
IsMovingProvided = hasIsMoving,
IsMoving = isMoving,
HasTargetPosition = hasAbsTarget,
UseTargetPosition = useAbsTarget,
NativeDirectional = hadNativeDirectional,
TargetX = absTargetX,
TargetY = absTargetY
};
}
catch
{
return null;
}
}
internal static bool TryGetProperty(JsonElement source, string name, out JsonElement value)
{
foreach (var p in source.EnumerateObject())
{
if (string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
{
value = p.Value;
return true;
}
}
value = default;
return false;
}
internal static bool TryGetFloat(JsonElement source, out float value, params string[] names)
{
foreach (var n in names)
{
if (!TryGetProperty(source, n, out var e)) continue;
if (e.ValueKind == JsonValueKind.Number && e.TryGetSingle(out value)) return true;
if (e.ValueKind == JsonValueKind.String && float.TryParse(e.GetString(), out value)) return true;
}
value = 0f;
return false;
}
internal static bool TryGetUInt(JsonElement source, out uint value, params string[] names)
{
foreach (var n in names)
{
if (!TryGetProperty(source, n, out var e)) continue;
if (e.ValueKind == JsonValueKind.Number && e.TryGetUInt32(out value)) return true;
if (e.ValueKind == JsonValueKind.String && uint.TryParse(e.GetString(), out value)) return true;
}
value = 0;
return false;
}
internal static bool TryGetBool(JsonElement source, out bool value, params string[] names)
{
foreach (var n in names)
{
if (!TryGetProperty(source, n, out var e)) continue;
if (e.ValueKind == JsonValueKind.True || e.ValueKind == JsonValueKind.False)
{
value = e.GetBoolean();
return true;
}
if (e.ValueKind == JsonValueKind.Number && e.TryGetInt32(out var num))
{
value = num != 0;
return true;
}
if (e.ValueKind == JsonValueKind.String && bool.TryParse(e.GetString(), out value))
return true;
}
value = false;
return false;
}
internal static bool TryGetString(JsonElement source, out string? value, params string[] names)
{
foreach (var n in names)
{
if (!TryGetProperty(source, n, out var e)) continue;
if (e.ValueKind == JsonValueKind.String)
{
value = e.GetString();
return true;
}
}
value = null;
return false;
}
internal static bool IsDirectionalValue(float value)
=> float.IsFinite(value) && value >= -1.05f && value <= 1.05f;
}
+313
View File
@@ -0,0 +1,313 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
namespace GameServer.World;
public sealed class WorldMovementService
{
private const int TileSize = 32;
private const float MoveWalk = 120f;
private const float MoveRun = 180f;
private const float TickStepSec = 0.10f;
private const long PortalCooldownTicks = 8; // 0.8s at 10hz
private readonly WorldChunkCache _cache;
private readonly ILogger<WorldMovementService> _log;
public WorldMovementService(WorldChunkCache cache, ILogger<WorldMovementService> log)
{
_cache = cache;
_log = log;
}
/// <summary>
/// Apply pending input to a player session. Performs movement, collision,
/// chunk position update, and portal detection. All from cached data -- zero DB queries.
/// </summary>
public void ApplyMovement(
WorldChunkCache.CachedRegion region,
WorldSessionState s,
long currentTick,
ConcurrentDictionary<ulong, long> portalCooldowns,
bool debugInput)
{
var beforeX = s.X;
var beforeY = s.Y;
float dx;
float dy;
var targetMode = s.HasPendingTarget;
var targetX = s.PendingTargetX;
var targetY = s.PendingTargetY;
var stepScale = 1f;
if (s.HasPendingTarget)
{
var tx = targetX - s.X;
var ty = targetY - s.Y;
var targetDist = MathF.Sqrt((tx * tx) + (ty * ty));
if (targetDist <= 1f)
{
s.HasPendingTarget = false;
targetMode = false;
dx = s.PendingMoveX;
dy = s.PendingMoveY;
}
else
{
dx = tx / targetDist;
dy = ty / targetDist;
var speedForScale = s.PendingIsRunning ? MoveRun : MoveWalk;
var maxTickStep = speedForScale * TickStepSec;
if (maxTickStep > 0.001f)
stepScale = MathF.Min(1f, targetDist / maxTickStep);
}
}
else
{
dx = s.PendingMoveX;
dy = s.PendingMoveY;
}
dx = MathF.Max(-1f, MathF.Min(1f, dx));
dy = MathF.Max(-1f, MathF.Min(1f, dy));
var len = MathF.Sqrt((dx * dx) + (dy * dy));
if (len > 1f)
{
dx /= len;
dy /= len;
}
var speed = s.PendingIsRunning ? MoveRun : MoveWalk;
var effectiveSpeed = speed * stepScale;
var nextX = s.X + (dx * effectiveSpeed * TickStepSec);
var nextY = s.Y + (dy * effectiveSpeed * TickStepSec);
var moving = MathF.Abs(dx) > 0.001f || MathF.Abs(dy) > 0.001f;
if (moving)
{
// Slide collision: try each axis independently (same behavior as original)
if (_cache.IsPositionWalkable(region, nextX, s.Y, s.IsVip))
s.X = nextX;
else
s.Errors.Add("blocked_non_walkable");
if (_cache.IsPositionWalkable(region, s.X, nextY, s.IsVip))
s.Y = nextY;
else
s.Errors.Add("blocked_non_walkable");
}
if (targetMode && s.HasPendingTarget)
{
var rx = targetX - s.X;
var ry = targetY - s.Y;
var remaining = MathF.Sqrt((rx * rx) + (ry * ry));
if (remaining <= 1f)
s.HasPendingTarget = false;
}
var (zx, zy, cx, cy) = ToChunkPos(region, s.X, s.Y);
s.ZoneX = zx;
s.ZoneY = zy;
s.ChunkX = cx;
s.ChunkY = cy;
s.VelX = moving ? dx * effectiveSpeed : 0f;
s.VelY = moving ? dy * effectiveSpeed : 0f;
s.Speed = moving ? effectiveSpeed : 0f;
s.IsMoving = moving;
s.Facing = ResolveFacing(s.PendingFacing, dx, dy, s.Facing);
s.Seq = s.PendingSeq;
TryTriggerPortal(region, s, currentTick, portalCooldowns);
if (debugInput)
{
_log.LogInformation(
"WORLD_TICK seq={Seq} targetMode={TargetMode} hasPendingTarget={HasPendingTarget} input=({InputX:F3},{InputY:F3}) effSpeed={Speed:F1} vel=({VelX:F1},{VelY:F1}) pos=({BeforeX:F2},{BeforeY:F2})->({AfterX:F2},{AfterY:F2})",
s.Seq, targetMode, s.HasPendingTarget, dx, dy, s.Speed, s.VelX, s.VelY, beforeX, beforeY, s.X, s.Y);
}
}
/// <summary>
/// Handle portal teleport. For world-type portals that need to resolve a target region,
/// the portal event is built with cached region data. Returns true if a portal was triggered
/// that requires async region lookup (world teleport to different region).
/// </summary>
public async ValueTask ResolvePortalTeleportAsync(
WorldSessionState s,
long currentTick,
ConcurrentDictionary<ulong, long> portalCooldowns,
CancellationToken ct)
{
// If a world teleport portal event was queued but needs target region resolution
if (s.PendingPortalEvent is PortalTeleportRequest req)
{
var targetRegion = await _cache.GetRegionAsync(req.TargetRegionId, ct);
if (targetRegion != null)
{
var nx = WorldPxX(targetRegion, req.TargetZoneX, req.TargetChunkX, req.TargetTileX);
var ny = WorldPxY(targetRegion, req.TargetZoneY, req.TargetChunkY, req.TargetTileY);
s.RegionId = targetRegion.Id;
s.X = nx;
s.Y = ny;
var (zx, zy, cx, cy) = ToChunkPos(targetRegion, s.X, s.Y);
s.ZoneX = zx;
s.ZoneY = zy;
s.ChunkX = cx;
s.ChunkY = cy;
// Clear chunk versions so all chunks get sent fresh
s.ChunkVersions.Clear();
s.PendingPortalEvent = new
{
type = "world_teleport",
sourceObjectId = req.SourceObjectId,
regionId = s.RegionId,
zoneX = s.ZoneX,
zoneY = s.ZoneY,
chunkX = s.ChunkX,
chunkY = s.ChunkY,
x = s.X,
y = s.Y
};
}
else
{
s.Errors.Add("portal_world_target_invalid");
s.PendingPortalEvent = null;
}
}
}
private void TryTriggerPortal(
WorldChunkCache.CachedRegion region,
WorldSessionState s,
long currentTick,
ConcurrentDictionary<ulong, long> portalCooldowns)
{
if (portalCooldowns.TryGetValue(s.CharacterId, out var untilTick) && untilTick > currentTick)
return;
var portal = _cache.FindPortalAtPosition(region, s.X, s.Y);
if (portal == null || string.IsNullOrWhiteSpace(portal.MetadataJson))
return;
if (!WorldPortalMetadata.TryParse(portal.MetadataJson, out var meta))
return;
portalCooldowns[s.CharacterId] = currentTick + PortalCooldownTicks;
if (meta.PortalType.Equals("world", StringComparison.OrdinalIgnoreCase))
{
if (WorldPortalMetadata.TryResolveWorldTarget(meta,
out var targetRegionId, out var targetZoneX, out var targetZoneY,
out var targetChunkX, out var targetChunkY, out var targetTileX, out var targetTileY))
{
// If same region, resolve immediately
if (targetRegionId == region.Id)
{
var nx = WorldPxX(region, targetZoneX, targetChunkX, targetTileX);
var ny = WorldPxY(region, targetZoneY, targetChunkY, targetTileY);
s.X = nx;
s.Y = ny;
var (zx, zy, cx, cy) = ToChunkPos(region, s.X, s.Y);
s.ZoneX = zx;
s.ZoneY = zy;
s.ChunkX = cx;
s.ChunkY = cy;
s.ChunkVersions.Clear();
s.PendingPortalEvent = new
{
type = "world_teleport",
sourceObjectId = portal.Id,
regionId = s.RegionId,
zoneX = s.ZoneX,
zoneY = s.ZoneY,
chunkX = s.ChunkX,
chunkY = s.ChunkY,
x = s.X,
y = s.Y
};
return;
}
// Cross-region teleport: queue for async resolution
s.PendingPortalEvent = new PortalTeleportRequest
{
SourceObjectId = portal.Id,
TargetRegionId = targetRegionId,
TargetZoneX = targetZoneX,
TargetZoneY = targetZoneY,
TargetChunkX = targetChunkX,
TargetChunkY = targetChunkY,
TargetTileX = targetTileX,
TargetTileY = targetTileY
};
return;
}
s.Errors.Add("portal_world_target_invalid");
return;
}
s.PendingPortalEvent = new
{
type = "dungeon_request",
sourceObjectId = portal.Id,
portalType = meta.PortalType,
dungeonTemplateId = meta.DungeonTemplateId,
randomTier = meta.RandomTier,
levelBracketMin = meta.LevelBracketMin,
levelBracketMax = meta.LevelBracketMax
};
}
// ---- Static helpers ----
public static (int zx, int zy, int cx, int cy) ToChunkPos(WorldChunkCache.CachedRegion r, float wx, float wy)
{
var gx = Math.Max(0, (int)MathF.Floor(wx / TileSize));
var gy = Math.Max(0, (int)MathF.Floor(wy / TileSize));
var zoneW = r.ChunksPerZoneX * r.ChunkWidthTiles;
var zoneH = r.ChunksPerZoneY * r.ChunkHeightTiles;
var zx = Math.Clamp(zoneW > 0 ? gx / zoneW : 0, 0, Math.Max(0, r.ZonesPerRegionX - 1));
var zy = Math.Clamp(zoneH > 0 ? gy / zoneH : 0, 0, Math.Max(0, r.ZonesPerRegionY - 1));
var lzx = gx - (zx * zoneW);
var lzy = gy - (zy * zoneH);
var cx = Math.Clamp(r.ChunkWidthTiles > 0 ? lzx / r.ChunkWidthTiles : 0, 0, Math.Max(0, r.ChunksPerZoneX - 1));
var cy = Math.Clamp(r.ChunkHeightTiles > 0 ? lzy / r.ChunkHeightTiles : 0, 0, Math.Max(0, r.ChunksPerZoneY - 1));
return (zx, zy, cx, cy);
}
public static float WorldPxX(WorldChunkCache.CachedRegion r, int zoneX, int chunkX, int tileX)
=> (((zoneX * (r.ChunksPerZoneX * r.ChunkWidthTiles)) + (chunkX * r.ChunkWidthTiles) + tileX) * TileSize) + (TileSize / 2f);
public static float WorldPxY(WorldChunkCache.CachedRegion r, int zoneY, int chunkY, int tileY)
=> (((zoneY * (r.ChunksPerZoneY * r.ChunkHeightTiles)) + (chunkY * r.ChunkHeightTiles) + tileY) * TileSize) + (TileSize / 2f);
public static string ResolveFacing(string? facing, float dx, float dy, string fallback)
{
if (!string.IsNullOrWhiteSpace(facing))
{
var f = facing.Trim().ToLowerInvariant();
if (f is "up" or "down" or "left" or "right") return f;
}
if (MathF.Abs(dx) > MathF.Abs(dy)) return dx >= 0 ? "right" : "left";
if (MathF.Abs(dy) > 0.001f) return dy >= 0 ? "down" : "up";
return fallback;
}
/// <summary>
/// Internal DTO used to queue a cross-region portal teleport for async resolution.
/// </summary>
internal sealed class PortalTeleportRequest
{
public long SourceObjectId { get; init; }
public int TargetRegionId { get; init; }
public int TargetZoneX { get; init; }
public int TargetZoneY { get; init; }
public int TargetChunkX { get; init; }
public int TargetChunkY { get; init; }
public int TargetTileX { get; init; }
public int TargetTileY { get; init; }
}
}
+58
View File
@@ -0,0 +1,58 @@
using System.Text.Json;
namespace GameServer.World;
public sealed class WorldPortalMetadata
{
public string PortalType { get; set; } = "";
public int? TargetRegionId { get; set; }
public int? TargetZoneX { get; set; }
public int? TargetZoneY { get; set; }
public int? TargetChunkX { get; set; }
public int? TargetChunkY { get; set; }
public int? TargetTileX { get; set; }
public int? TargetTileY { get; set; }
public int? DungeonTemplateId { get; set; }
public int? RandomTier { get; set; }
public int? LevelBracketMin { get; set; }
public int? LevelBracketMax { get; set; }
private static readonly JsonSerializerOptions JsonOpts = new() { PropertyNameCaseInsensitive = true };
public static bool TryParse(string metadataJson, out WorldPortalMetadata metadata)
{
metadata = new WorldPortalMetadata();
try
{
var parsed = JsonSerializer.Deserialize<WorldPortalMetadata>(metadataJson, JsonOpts);
if (parsed == null || string.IsNullOrWhiteSpace(parsed.PortalType))
return false;
metadata = parsed;
return true;
}
catch
{
return false;
}
}
public static bool TryResolveWorldTarget(
WorldPortalMetadata m,
out int targetRegionId,
out int targetZoneX,
out int targetZoneY,
out int targetChunkX,
out int targetChunkY,
out int targetTileX,
out int targetTileY)
{
targetRegionId = m.TargetRegionId ?? 0;
targetZoneX = m.TargetZoneX ?? 0;
targetZoneY = m.TargetZoneY ?? 0;
targetChunkX = m.TargetChunkX ?? 0;
targetChunkY = m.TargetChunkY ?? 0;
targetTileX = m.TargetTileX ?? 0;
targetTileY = m.TargetTileY ?? 0;
return targetRegionId > 0;
}
}
+43
View File
@@ -0,0 +1,43 @@
using Server.Networking;
namespace GameServer.World;
public sealed class WorldSessionState
{
public Guid ConnectionId { get; set; }
public IConnection Connection { get; set; } = null!;
public ulong AccountId { get; set; }
public ulong CharacterId { get; set; }
public string Name { get; set; } = "";
public bool IsVip { get; set; }
public int RegionId { get; set; }
public int ZoneX { get; set; }
public int ZoneY { get; set; }
public int ChunkX { get; set; }
public int ChunkY { get; set; }
public float X { get; set; }
public float Y { get; set; }
public float VelX { get; set; }
public float VelY { get; set; }
public string Facing { get; set; } = "down";
public float Speed { get; set; }
public bool IsMoving { get; set; }
public uint Seq { get; set; }
// Pending input state
public float PendingMoveX { get; set; }
public float PendingMoveY { get; set; }
public bool PendingIsRunning { get; set; }
public string? PendingFacing { get; set; }
public uint PendingSeq { get; set; }
public DateTime LastNonNeutralInputAt { get; set; } = DateTime.UtcNow;
public DateTime PreferDirectionalUntil { get; set; } = DateTime.MinValue;
public bool HasPendingTarget { get; set; }
public float PendingTargetX { get; set; }
public float PendingTargetY { get; set; }
// Chunk tracking
public Dictionary<string, long> ChunkVersions { get; } = new(StringComparer.Ordinal);
public List<string> Errors { get; } = new();
public object? PendingPortalEvent { get; set; }
}
+28
View File
@@ -0,0 +1,28 @@
# Client Fixes / Notes After WorldHandler Refactor
## Server Protocol: UNCHANGED
The wire protocol (OpCodes, payload shapes, message flows) is identical after the refactor.
No client code changes are required for compatibility.
## Performance Impact
The server tick loop no longer hits the database. Movement/collision is now pure in-memory.
The client should observe dramatically faster movement response -- the "1 tile per 3 seconds"
latency was caused by 30+ DB round-trips per player per tick on the server side.
## Client Recommendations
### LOCAL_MOVE_SPEED mismatch
The client uses `LOCAL_MOVE_SPEED = 160.0` for local prediction, but the server walk speed
is `120 px/s` and run speed is `180 px/s`. This means the client's local prediction overshoots
when walking, causing small rubber-banding corrections via `VISUAL_RECONCILE_RATE`.
Options:
- Match client prediction to server walk speed: change `LOCAL_MOVE_SPEED` to `120.0`
- Or read speed from WORLD_SPAWN payload and use it dynamically
- Run speed (shift held) already reasonably matches at 180 vs client 160
### Other observations
- `MOVE_SEND_INTERVAL_MS = 100` correctly matches the server 10Hz tick rate
- `VISUAL_RECONCILE_RATE = 4.0` and `VISUAL_SNAP_DISTANCE = 256.0` are reasonable
- Client-side collision pre-check (line 350-355) only checks 1 tile vs server's 5-point check
-- this is fine, it just means the client may sometimes send input that the server rejects
+819
View File
@@ -0,0 +1,819 @@
extends CanvasLayer
const WORLD_RUNTIME_FLAG := "application/config/world_runtime_enabled"
const WORLD_DEBUG_PAYWALL_FLAG := "application/config/world_debug_show_paywalls"
const MOVE_SEND_INTERVAL_MS := 100
const LOCAL_MOVE_SPEED := 160.0
const VISUAL_RECONCILE_RATE := 4.0
const VISUAL_SNAP_DISTANCE := 256.0
@onready var return_to_hub_btn = $Control/Panel/VBoxContainer/ReturnToHubBtn
@onready var status_label = $Control/Panel/VBoxContainer/StatusLabel
@onready var mode_label = $Control/Panel/VBoxContainer/ModeLabel
@onready var connect_btn = $Control/Panel/VBoxContainer/ConnectBtn
@onready var world_bg = $ColorRect
@onready var menu_control = $Control
@onready var menu_panel = $Control/Panel
var runtime = null
var world_root: Node2D = null
var visual_renderer: VisualTileMapRenderer = null
var paywall_overlay: Node2D = null
var tile_fallback_overlay: Node2D = null
var object_container: Node2D = null
var npc_container: Node2D = null
var players_container: Node2D = null
var player_marker: Node2D = null
var world_camera: Camera2D = null
var npc_scene: PackedScene = null
var player_scene: PackedScene = null
var other_player_scene: PackedScene = null
var self_player_node: Node2D = null
var other_player_nodes: Dictionary = {} # id -> Node2D
var _show_paywall_debug: bool = false
var _last_move_send_ms: int = 0
var _object_texture_cache: Dictionary = {}
var _last_move_vec: Vector2 = Vector2.ZERO
var _last_world_input_log_ms: int = 0
var _was_visible: bool = true
var _last_sent_move_vec: Vector2 = Vector2.ZERO
var _last_sent_facing: String = ""
var _render_self_position: Vector2 = Vector2.ZERO
var _has_render_self_position: bool = false
func _ready():
if return_to_hub_btn:
return_to_hub_btn.pressed.connect(_on_return_to_hub_pressed)
if connect_btn:
connect_btn.pressed.connect(_on_connect_pressed)
if GameState:
GameState.state_changed.connect(_on_game_state_changed)
_init_world_nodes()
_setup_runtime()
_was_visible = visible
func _input(event: InputEvent):
if runtime == null:
return
if runtime.mode != runtime.MODE_ACTIVE_WORLD:
return
if event.is_action_pressed("escape_menu"):
if menu_panel:
menu_panel.visible = not menu_panel.visible
if world_bg:
world_bg.visible = menu_panel.visible
get_viewport().set_input_as_handled()
func _on_return_to_hub_pressed():
if GameState and GameState.has_method("return_to_hub_from_world"):
GameState.return_to_hub_from_world()
func _process(delta: float):
var is_now_visible = visible
if _was_visible != is_now_visible:
_was_visible = is_now_visible
if not is_now_visible:
# When this screen is hidden (state switched away), clear all world runtime/UI state.
_reset_world_session()
if runtime == null:
return
if runtime.mode != runtime.MODE_ACTIVE_WORLD:
return
_handle_world_input(delta)
_update_render_self_position(delta)
_sync_player_marker()
func _setup_runtime():
var enabled = ProjectSettings.get_setting(WORLD_RUNTIME_FLAG, true)
if not enabled:
if status_label:
status_label.text = "World runtime disabled by feature flag."
if mode_label:
mode_label.text = "Mode: disabled"
if connect_btn:
connect_btn.disabled = true
return
var runtime_script = load("res://scripts/world/world_runtime_client.gd")
runtime = runtime_script.new()
add_child(runtime)
runtime.mode_changed.connect(_on_mode_changed)
runtime.chunk_refresh_required.connect(_on_chunk_refresh_required)
runtime.chunk_updated.connect(_on_chunk_updated)
runtime.chunk_unloaded.connect(_on_chunk_unloaded)
runtime.set_mode(runtime.MODE_CONNECTING)
if GameState:
GameState.world_spawn_received.connect(_on_world_spawn_received)
GameState.world_state_received.connect(_on_world_state_received)
GameState.world_despawn_received.connect(_on_world_despawn_received)
if status_label:
status_label.text = "World runtime ready. Connect to request spawn."
func _on_connect_pressed():
if runtime == null:
return
if runtime.mode == runtime.MODE_AWAITING_SPAWN or runtime.mode == runtime.MODE_ACTIVE_WORLD:
return
runtime.set_mode(runtime.MODE_AWAITING_SPAWN)
if status_label:
status_label.text = "Awaiting world spawn from server..."
if GameState and GameState.has_method("request_world_spawn"):
GameState.request_world_spawn()
func _on_mode_changed(mode: String):
if mode_label:
mode_label.text = "Mode: %s" % mode
if connect_btn:
connect_btn.disabled = (mode == runtime.MODE_AWAITING_SPAWN or mode == runtime.MODE_ACTIVE_WORLD)
connect_btn.text = "Connected" if mode == runtime.MODE_ACTIVE_WORLD else "Connect World"
if menu_panel:
menu_panel.visible = mode != runtime.MODE_ACTIVE_WORLD
if world_bg:
world_bg.visible = mode != runtime.MODE_ACTIVE_WORLD
func _on_chunk_refresh_required(chunk_key: String):
if status_label:
status_label.text = "Chunk refresh required: %s" % chunk_key
func _on_world_spawn_received(data: Dictionary):
if runtime == null:
return
runtime.apply_spawn(data)
_render_self_position = Vector2(
float(runtime.self_player.get("x", 0.0)),
float(runtime.self_player.get("y", 0.0))
)
_has_render_self_position = true
_rebuild_world_visuals()
_rebuild_world_entities()
_ensure_self_player_node()
_update_player_entities()
_sync_player_marker()
# Spawn means world is active; force-hide menu in case stale UI toggles survived.
if menu_panel:
menu_panel.visible = false
if world_bg:
world_bg.visible = false
if status_label:
if runtime.chunk_cache.is_empty():
status_label.text = "World spawn received (no chunks in payload)."
else:
status_label.text = "World spawn received."
func _on_world_state_received(data: Dictionary):
if runtime == null:
return
runtime.apply_world_state(data)
_update_player_entities()
_sync_player_marker()
#_rebuild_world_entities()
func _on_world_despawn_received(data: Dictionary):
if runtime == null:
return
runtime.set_mode(runtime.MODE_RECOVERING)
if status_label:
status_label.text = "World despawned: %s" % str(data.get("reason", "unknown"))
if connect_btn:
connect_btn.disabled = false
connect_btn.text = "Connect World"
_clear_player_entities()
func _on_game_state_changed(state: String):
if state == "WORLD":
# Always start world scene from a clean baseline before new connect/spawn.
_reset_world_session()
_prepare_world_entry_ui()
return
# Any non-world state should fully reset world session/UI to prevent stale re-entry.
_reset_world_session()
func _on_chunk_updated(_chunk_key: String):
_rebuild_world_visuals()
_rebuild_world_entities()
func _on_chunk_unloaded(_chunk_key: String):
_rebuild_world_visuals()
_rebuild_world_entities()
func _init_world_nodes():
_show_paywall_debug = bool(ProjectSettings.get_setting(WORLD_DEBUG_PAYWALL_FLAG, false))
world_root = Node2D.new()
world_root.name = "WorldRoot"
add_child(world_root)
# Keep world above background but below menu/control.
var target_index = 1 if world_bg != null else 0
move_child(world_root, target_index)
visual_renderer = VisualTileMapRenderer.new()
visual_renderer.name = "WorldVisualRenderer"
world_root.add_child(visual_renderer)
paywall_overlay = Node2D.new()
paywall_overlay.name = "PaywallOverlay"
paywall_overlay.z_index = 5
world_root.add_child(paywall_overlay)
tile_fallback_overlay = Node2D.new()
tile_fallback_overlay.name = "TileFallbackOverlay"
tile_fallback_overlay.z_index = 2
world_root.add_child(tile_fallback_overlay)
object_container = Node2D.new()
object_container.name = "WorldObjects"
object_container.z_index = 20
world_root.add_child(object_container)
npc_container = Node2D.new()
npc_container.name = "WorldNpcs"
npc_container.z_index = 30
world_root.add_child(npc_container)
players_container = Node2D.new()
players_container.name = "WorldPlayers"
players_container.z_index = 35
world_root.add_child(players_container)
player_marker = Node2D.new()
player_marker.name = "SelfPlayer"
player_marker.z_index = 40
world_root.add_child(player_marker)
_create_player_marker_visual()
world_camera = Camera2D.new()
world_camera.name = "WorldCamera"
world_camera.enabled = true
world_camera.zoom = Vector2(1.3, 1.3)
world_root.add_child(world_camera)
if ResourceLoader.exists("res://scenes/dungeon/mob.tscn"):
npc_scene = load("res://scenes/dungeon/mob.tscn")
if ResourceLoader.exists("res://scenes/dungeon/player.tscn"):
player_scene = load("res://scenes/dungeon/player.tscn")
if ResourceLoader.exists("res://scenes/dungeon/other_player.tscn"):
other_player_scene = load("res://scenes/dungeon/other_player.tscn")
func _create_player_marker_visual():
for child in player_marker.get_children():
child.queue_free()
var sprite = Sprite2D.new()
if SpriteGenerator:
sprite.texture = SpriteGenerator.get_circle()
sprite.modulate = Color(0.35, 0.9, 1.0, 1.0)
sprite.scale = Vector2(0.8, 0.8)
else:
var poly = Polygon2D.new()
poly.polygon = PackedVector2Array([
Vector2(-12, -12),
Vector2(12, -12),
Vector2(12, 12),
Vector2(-12, 12)
])
poly.color = Color(0.35, 0.9, 1.0, 1.0)
player_marker.add_child(poly)
return
player_marker.add_child(sprite)
func _sync_player_marker():
if runtime == null:
return
if not _has_render_self_position:
_render_self_position = Vector2(
float(runtime.self_player.get("x", 0.0)),
float(runtime.self_player.get("y", 0.0))
)
_has_render_self_position = true
var x = _render_self_position.x
var y = _render_self_position.y
if world_root:
var viewport_center = get_viewport().get_visible_rect().size * 0.5
world_root.position = viewport_center - Vector2(x, y)
if world_camera:
world_camera.position = Vector2(x, y)
if self_player_node and is_instance_valid(self_player_node):
if player_marker:
player_marker.visible = false
self_player_node.position = Vector2(x, y)
if self_player_node.has_method("set_player_name"):
self_player_node.set_player_name(str(runtime.self_player.get("name", "You")))
if self_player_node.has_method("update_health"):
var hp = int(runtime.self_player.get("health", 100))
var max_hp = int(runtime.self_player.get("maxHealth", runtime.self_player.get("max_health", 100)))
self_player_node.update_health(hp, max_hp)
if self_player_node.has_method("set_movement"):
self_player_node.set_movement(_last_move_vec)
return
if player_marker:
player_marker.visible = true
player_marker.position = Vector2(x, y)
func _update_render_self_position(delta: float):
if runtime == null:
return
var auth_pos = Vector2(
float(runtime.self_player.get("x", 0.0)),
float(runtime.self_player.get("y", 0.0))
)
if not _has_render_self_position:
_render_self_position = auth_pos
_has_render_self_position = true
return
# Dungeon-like local render prediction while keeping server authoritative position as truth.
var predicted = _render_self_position + (_last_move_vec * LOCAL_MOVE_SPEED * delta)
var error = auth_pos - predicted
if error.length() > VISUAL_SNAP_DISTANCE:
_render_self_position = auth_pos
return
var alpha = min(1.0, delta * VISUAL_RECONCILE_RATE)
_render_self_position = predicted + (error * alpha)
func _handle_world_input(delta: float):
var move_x = Input.get_axis("move_left", "move_right")
var move_y = Input.get_axis("move_up", "move_down")
var movement = Vector2(move_x, move_y)
if movement.length() > 1.0:
movement = movement.normalized()
var is_vip = bool(runtime.self_player.get("isVip", false))
var current_pos = Vector2(
float(runtime.self_player.get("x", 0.0)),
float(runtime.self_player.get("y", 0.0))
)
var target_pos = current_pos + movement * LOCAL_MOVE_SPEED * delta
# Keep world movement server-authoritative to avoid rubber-banding.
# We still evaluate local blocking to avoid sending obviously invalid movement spam.
if movement.length() > 0.0:
var target_tile_x = int(floor(target_pos.x / float(runtime.TILE_SIZE)))
var target_tile_y = int(floor(target_pos.y / float(runtime.TILE_SIZE)))
var blocked = runtime.is_target_tile_blocked(target_tile_x, target_tile_y, is_vip)
if blocked:
movement = Vector2.ZERO
_last_move_vec = movement
var now_ms = Time.get_ticks_msec()
var facing = _movement_to_facing(movement)
var is_running = Input.is_key_pressed(KEY_SHIFT)
var time_since_last = now_ms - _last_move_send_ms
var moved_changed = movement != _last_sent_move_vec
var facing_changed = facing != _last_sent_facing
var should_send = moved_changed \
or (movement.length() > 0.0 and time_since_last >= MOVE_SEND_INTERVAL_MS) \
or (facing_changed and movement.length() > 0.0)
if not should_send:
return
var seq = runtime.next_input_seq()
GameState.send_world_input(
seq,
movement.x,
movement.y,
is_running,
facing
)
_last_move_send_ms = now_ms
_last_sent_move_vec = movement
_last_sent_facing = facing
if movement.length() > 0.0 and now_ms - _last_world_input_log_ms > 500:
_last_world_input_log_ms = now_ms
print("[World] INPUT seq=%d move=(%.2f,%.2f) pos=(%.1f,%.1f) run=%s" % [
seq,
movement.x,
movement.y,
float(runtime.self_player.get("x", 0.0)),
float(runtime.self_player.get("y", 0.0)),
str(is_running)
])
func _movement_to_facing(movement: Vector2) -> String:
if movement.length() < 0.001:
return ""
if absf(movement.x) >= absf(movement.y):
return "right" if movement.x > 0.0 else "left"
return "down" if movement.y > 0.0 else "up"
func _rebuild_world_visuals():
if runtime == null or visual_renderer == null:
return
if paywall_overlay:
_clear_children(paywall_overlay)
if tile_fallback_overlay:
_clear_children(tile_fallback_overlay)
var sheets = runtime.tile_sheets.duplicate(true)
var available_sheet_ids: Dictionary = {}
for s in sheets:
available_sheet_ids[int(s.get("id", 0))] = true
var visual_tiles: Array = []
for key in runtime.chunk_cache:
var chunk_data = runtime.chunk_cache[key]
var zone_x = int(chunk_data.get("zoneX", 0))
var zone_y = int(chunk_data.get("zoneY", 0))
var chunk_x = int(chunk_data.get("chunkX", 0))
var chunk_y = int(chunk_data.get("chunkY", 0))
for tile in chunk_data.get("tiles", []):
var local_tile_x = int(tile.get("x", tile.get("tileX", 0)))
var local_tile_y = int(tile.get("y", tile.get("tileY", 0)))
var world_tile_x = runtime.world_tile_x(zone_x, chunk_x, local_tile_x)
var world_tile_y = runtime.world_tile_y(zone_y, chunk_y, local_tile_y)
var sheet_id = int(tile.get("sid", tile.get("sheetId", 0)))
var frame_index = int(tile.get("frame", tile.get("frameIndex", 0)))
visual_tiles.append({
"x": world_tile_x,
"y": world_tile_y,
"l": int(tile.get("l", 0)),
"sid": sheet_id,
"frame": frame_index,
"fx": bool(tile.get("fx", false)),
"fy": bool(tile.get("fy", false)),
"r": int(tile.get("r", 0))
})
if _show_paywall_debug and bool(tile.get("isInvisiblePaywall", false)):
_add_paywall_debug_overlay(world_tile_x, world_tile_y)
if not available_sheet_ids.has(sheet_id) and _fallback_sheet_path(sheet_id).is_empty():
_add_fallback_tile_overlay(world_tile_x, world_tile_y, sheet_id)
# Render textured tiles when sheet metadata exists.
if sheets.is_empty():
sheets = _build_fallback_world_sheets(visual_tiles)
if sheets.size() > 0:
visual_renderer.render_visual_tiles({
"sheets": sheets,
"tiles": visual_tiles
})
else:
visual_renderer.clear_tiles()
func _build_fallback_world_sheets(visual_tiles: Array) -> Array:
# WORLD_SPAWN payload currently sends sheetId/frameIndex but not sheet metadata.
# Build a local fallback catalog so VisualTileMapRenderer can render.
var used_sheet_ids: Dictionary = {}
for t in visual_tiles:
used_sheet_ids[int(t.get("sid", 0))] = true
var fallback_defs: Array = []
for sid in used_sheet_ids.keys():
var sheet_id = int(sid)
var path = _fallback_sheet_path(sheet_id)
if path.is_empty():
continue
var cols = 16
var sheet_w = 256
var sheet_h = 256
if ResourceLoader.exists(path):
var tex = load(path)
if tex and tex is Texture2D:
var w = tex.get_width()
var h = tex.get_height()
if w > 0:
cols = max(1, int(w / 16))
sheet_w = w
if h > 0:
sheet_h = h
fallback_defs.append({
"id": sheet_id,
"path": path,
"tileW": 16,
"tileH": 16,
"sheetW": sheet_w,
"sheetH": sheet_h,
"cols": cols
})
return fallback_defs
func _fallback_sheet_path(sheet_id: int) -> String:
# Known runtime/default mapping.
match sheet_id:
3:
return "res://assets/sprites/Dungeon_Tileset.png"
_:
return ""
func _fallback_tile_color(sheet_id: int) -> Color:
# Deterministic fallback color per sheet id when no sheet path is known.
var hue = float(abs(sheet_id * 53) % 360) / 360.0
return Color.from_hsv(hue, 0.35, 0.8, 0.9)
func _add_paywall_debug_overlay(world_tile_x: int, world_tile_y: int):
if paywall_overlay == null:
return
var tile_size = float(runtime.TILE_SIZE)
var poly = Polygon2D.new()
poly.color = Color(1.0, 0.2, 0.2, 0.35)
poly.polygon = PackedVector2Array([
Vector2(0, 0),
Vector2(tile_size, 0),
Vector2(tile_size, tile_size),
Vector2(0, tile_size)
])
poly.position = Vector2(world_tile_x * tile_size, world_tile_y * tile_size)
poly.z_index = 1
paywall_overlay.add_child(poly)
func _add_fallback_tile_overlay(world_tile_x: int, world_tile_y: int, sheet_id: int):
if tile_fallback_overlay == null:
return
var tile_size = float(runtime.TILE_SIZE)
var poly = Polygon2D.new()
poly.color = _fallback_tile_color(sheet_id)
poly.polygon = PackedVector2Array([
Vector2(0, 0),
Vector2(tile_size, 0),
Vector2(tile_size, tile_size),
Vector2(0, tile_size)
])
poly.position = Vector2(world_tile_x * tile_size, world_tile_y * tile_size)
tile_fallback_overlay.add_child(poly)
func _clear_children(node: Node):
for child in node.get_children():
child.queue_free()
func _ensure_self_player_node():
if players_container == null:
return
if self_player_node and is_instance_valid(self_player_node):
return
if player_scene:
self_player_node = player_scene.instantiate()
self_player_node.name = "SelfPlayerNode"
players_container.add_child(self_player_node)
if self_player_node.has_method("set_player_name"):
self_player_node.set_player_name(str(runtime.self_player.get("name", "You")))
else:
self_player_node = null
func _update_player_entities():
if runtime == null:
return
_ensure_self_player_node()
var seen_ids: Array = []
for pid in runtime.nearby_players.keys():
seen_ids.append(pid)
var player_data = runtime.nearby_players[pid]
var node = other_player_nodes.get(pid, null)
if node == null or not is_instance_valid(node):
if other_player_scene:
node = other_player_scene.instantiate()
node.name = "OtherPlayer_%s" % str(pid)
if players_container:
players_container.add_child(node)
other_player_nodes[pid] = node
else:
continue
node.position = Vector2(
float(player_data.get("x", 0.0)),
float(player_data.get("y", 0.0))
)
if node.has_method("update_data"):
var merged = player_data.duplicate(true)
if not merged.has("id"):
merged["id"] = pid
if not merged.has("name"):
merged["name"] = merged.get("playerName", "Player")
node.update_data(merged)
var to_remove: Array = []
for pid in other_player_nodes.keys():
if pid not in seen_ids:
to_remove.append(pid)
for pid in to_remove:
var node = other_player_nodes[pid]
if node and is_instance_valid(node):
node.queue_free()
other_player_nodes.erase(pid)
func _clear_player_entities():
if self_player_node and is_instance_valid(self_player_node):
self_player_node.queue_free()
self_player_node = null
for pid in other_player_nodes.keys():
var node = other_player_nodes[pid]
if node and is_instance_valid(node):
node.queue_free()
other_player_nodes.clear()
func _prepare_world_entry_ui():
if menu_panel:
menu_panel.visible = true
if world_bg:
world_bg.visible = true
if connect_btn:
connect_btn.disabled = false
connect_btn.text = "Connect World"
if status_label:
status_label.text = "World runtime ready. Connect to request spawn."
if runtime:
runtime.set_mode(runtime.MODE_CONNECTING)
func _reset_world_session():
_last_move_send_ms = 0
_last_world_input_log_ms = 0
_last_move_vec = Vector2.ZERO
_last_sent_move_vec = Vector2.ZERO
_last_sent_facing = ""
_render_self_position = Vector2.ZERO
_has_render_self_position = false
_clear_player_entities()
if object_container:
_clear_children(object_container)
if npc_container:
_clear_children(npc_container)
if paywall_overlay:
_clear_children(paywall_overlay)
if tile_fallback_overlay:
_clear_children(tile_fallback_overlay)
if visual_renderer:
visual_renderer.clear_tiles()
if runtime:
runtime.reset_runtime()
if world_root:
world_root.position = Vector2.ZERO
if world_camera:
world_camera.position = Vector2.ZERO
if player_marker:
player_marker.position = Vector2.ZERO
player_marker.visible = true
if menu_panel:
menu_panel.visible = true
if world_bg:
world_bg.visible = true
if connect_btn:
connect_btn.disabled = false
connect_btn.text = "Connect World"
if mode_label:
mode_label.text = "Mode: connecting"
if status_label:
status_label.text = "World runtime ready. Connect to request spawn."
func _rebuild_world_entities():
if runtime == null:
return
if object_container:
_clear_children(object_container)
if npc_container:
_clear_children(npc_container)
for key in runtime.chunk_cache:
var chunk_data = runtime.chunk_cache[key]
for obj in chunk_data.get("objects", []):
var object_pos = _resolve_entity_position(chunk_data, obj)
_add_world_object_instance(object_pos, obj)
for npc in chunk_data.get("npcs", []):
var npc_pos = _resolve_entity_position(chunk_data, npc)
_add_world_npc_instance(npc_pos, npc)
for mob in chunk_data.get("mobs", []):
var mob_pos = _resolve_entity_position(chunk_data, mob)
_add_world_npc_instance(mob_pos, mob)
func _resolve_entity_position(chunk_data: Dictionary, entity: Dictionary) -> Vector2:
# Runtime can emit either world pixel coords or chunk-local tile coords.
if entity.has("worldX") and entity.has("worldY"):
return Vector2(float(entity.get("worldX", 0.0)), float(entity.get("worldY", 0.0)))
var x = float(entity.get("x", 0.0))
var y = float(entity.get("y", 0.0))
var chunk_width_tiles = int(runtime.region.get("chunkWidthTiles", 0))
var chunk_height_tiles = int(runtime.region.get("chunkHeightTiles", 0))
if chunk_width_tiles > 0 and chunk_height_tiles > 0 and x >= 0.0 and y >= 0.0 and x < chunk_width_tiles and y < chunk_height_tiles:
var zone_x = int(chunk_data.get("zoneX", 0))
var zone_y = int(chunk_data.get("zoneY", 0))
var chunk_x = int(chunk_data.get("chunkX", 0))
var chunk_y = int(chunk_data.get("chunkY", 0))
var tx = runtime.world_tile_x(zone_x, chunk_x, int(x))
var ty = runtime.world_tile_y(zone_y, chunk_y, int(y))
return Vector2((tx + 0.5) * runtime.TILE_SIZE, (ty + 0.5) * runtime.TILE_SIZE)
return Vector2(x, y)
func _add_world_object_marker(position: Vector2, label_text: String):
if object_container == null:
return
var node = Node2D.new()
node.position = position
var marker = Polygon2D.new()
marker.color = Color(0.95, 0.75, 0.25, 0.9)
marker.polygon = PackedVector2Array([
Vector2(-8, -8),
Vector2(8, -8),
Vector2(8, 8),
Vector2(-8, 8)
])
node.add_child(marker)
var label = Label.new()
label.text = label_text.left(16)
label.position = Vector2(-28, -26)
node.add_child(label)
object_container.add_child(node)
func _add_world_object_instance(position: Vector2, object_data: Dictionary):
if object_container == null:
return
var sprite_path = _resolve_object_sprite_path(object_data)
if sprite_path.is_empty():
_add_world_object_marker(position, str(object_data.get("objectName", "Object")))
return
var texture = _load_world_texture(sprite_path)
if texture == null:
_add_world_object_marker(position, str(object_data.get("objectName", "Object")))
return
var node = Node2D.new()
node.position = position
var sprite = Sprite2D.new()
sprite.texture = texture
sprite.centered = true
sprite.texture_filter = CanvasItem.TEXTURE_FILTER_NEAREST
var scale_value = float(object_data.get("scale", object_data.get("Scale", 1.0)))
if scale_value <= 0.0:
scale_value = 1.0
sprite.scale = Vector2.ONE * scale_value
var tint = str(object_data.get("tintColor", object_data.get("TintColor", "")))
if not tint.is_empty():
sprite.modulate = Color.from_string(tint, Color.WHITE)
node.add_child(sprite)
object_container.add_child(node)
func _resolve_object_sprite_path(object_data: Dictionary) -> String:
var direct_keys = ["spritePath", "SpritePath", "path", "Path", "sprite", "Sprite"]
for key in direct_keys:
var value = str(object_data.get(key, ""))
if not value.is_empty():
return value
var sprite_config = object_data.get("spriteConfig", object_data.get("SpriteConfig", null))
if sprite_config is Dictionary:
if sprite_config.has("sheets"):
var sheets = sprite_config.get("sheets", {})
for sheet_key in sheets.keys():
var info = sheets[sheet_key]
if info is Dictionary:
var path = str(info.get("path", ""))
if not path.is_empty():
return path
if sprite_config.has("sprites"):
var sprites = sprite_config.get("sprites", {})
for anim in sprites.keys():
var path = str(sprites[anim])
if not path.is_empty():
return path
var definition_id = int(object_data.get("objectDefinitionId", object_data.get("definitionId", -1)))
if definition_id >= 0:
var local_path = "res://textures/objects/%d.png" % definition_id
if ResourceLoader.exists(local_path):
return local_path
return ""
func _load_world_texture(path: String) -> Texture2D:
if _object_texture_cache.has(path):
return _object_texture_cache[path]
var texture: Texture2D = null
if path.begins_with("res://"):
if ResourceLoader.exists(path):
texture = load(path)
elif UpdateManager:
texture = UpdateManager.load_texture(path)
if texture != null:
_object_texture_cache[path] = texture
return texture
func _add_world_npc_instance(position: Vector2, npc_data: Dictionary):
if npc_container == null:
return
if npc_scene == null:
_add_world_object_marker(position, str(npc_data.get("npcName", npc_data.get("name", "NPC"))))
return
var npc_node = npc_scene.instantiate()
npc_node.position = position
if npc_node.has_method("update_data"):
var merged = npc_data.duplicate(true)
if not merged.has("name") and merged.has("npcName"):
merged["name"] = merged["npcName"]
npc_node.update_data(merged)
npc_container.add_child(npc_node)
+3
View File
@@ -102,6 +102,9 @@ builder.Services.AddSingleton<IClientMessageHandler, AuthHandler>();
builder.Services.AddSingleton<DungeonHandler>();
builder.Services.AddSingleton<IClientMessageHandler>(sp => sp.GetRequiredService<DungeonHandler>());
builder.Services.AddSingleton<WorldChunkCache>();
builder.Services.AddSingleton<WorldMovementService>();
builder.Services.AddSingleton<WorldBroadcastService>();
builder.Services.AddSingleton<WorldHandler>();
builder.Services.AddSingleton<IClientMessageHandler>(sp => sp.GetRequiredService<WorldHandler>());
builder.Services.AddSingleton<LootService>();