From 054e618e16f8ce4252beb1a64284b974191ba0ab Mon Sep 17 00:00:00 2001 From: dingo Date: Sun, 15 Feb 2026 10:11:35 -0500 Subject: [PATCH] OpCode Changes --- Game/Dungeon/DungeonHandler.cs | 110 +++++++++++++++++++++++++++++++-- Game/World/WorldHandler.cs | 51 +++++++++------ Networking/Messages/OpCodes.cs | 12 ++-- Networking/NetworkManager.cs | 35 ++++++----- pending-clientChanges.md | 20 +++--- 5 files changed, 174 insertions(+), 54 deletions(-) diff --git a/Game/Dungeon/DungeonHandler.cs b/Game/Dungeon/DungeonHandler.cs index 7711a37..dc4fab5 100644 --- a/Game/Dungeon/DungeonHandler.cs +++ b/Game/Dungeon/DungeonHandler.cs @@ -953,12 +953,114 @@ public sealed partial class DungeonHandler : IClientMessageHandler { if (session.PlayerInstance == null) return; - var input = _ser.Deserialize(payload); - session.PlayerInstance.InputX = input.Dx; - session.PlayerInstance.InputY = input.Dy; - session.PlayerInstance.Rotation = input.AimAngle; + var (dx, dy, aimAngle) = ParseMoveInput(payload, session.PlayerInstance.X, session.PlayerInstance.Y); + session.PlayerInstance.InputX = dx; + session.PlayerInstance.InputY = dy; + session.PlayerInstance.Rotation = aimAngle; } + private static (float Dx, float Dy, float AimAngle) ParseMoveInput(ReadOnlyMemory payload, float currentX, float currentY) + { + if (payload.IsEmpty) return (0f, 0f, 0f); + + try + { + using var doc = JsonDocument.Parse(System.Text.Encoding.UTF8.GetString(payload.Span)); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return (0f, 0f, 0f); + + var source = root; + if (TryGetJsonProperty(root, "input", out var nested) && nested.ValueKind == JsonValueKind.Object) + { + source = nested; + } + + var hasDx = TryGetJsonFloat(source, out var dx, "dx", "moveX", "inputX", "horizontal"); + var hasDy = TryGetJsonFloat(source, out var dy, "dy", "moveY", "inputY", "vertical"); + var hasRawX = TryGetJsonFloat(source, out var rawX, "x"); + var hasRawY = TryGetJsonFloat(source, out var rawY, "y"); + + if (!hasDx && hasRawX && IsDirectionalValue(rawX)) + { + dx = rawX; + hasDx = true; + } + if (!hasDy && hasRawY && IsDirectionalValue(rawY)) + { + dy = rawY; + hasDy = true; + } + + // Compatibility: absolute target coordinates from location-style clients. + if (!hasDx && !hasDy && hasRawX && hasRawY && (!IsDirectionalValue(rawX) || !IsDirectionalValue(rawY))) + { + var tx = rawX - currentX; + var ty = rawY - currentY; + var targetLen = MathF.Sqrt((tx * tx) + (ty * ty)); + if (targetLen > 0.001f) + { + dx = tx / targetLen; + dy = ty / targetLen; + hasDx = true; + hasDy = true; + } + } + + if (!hasDx) dx = 0f; + if (!hasDy) dy = 0f; + + var len = MathF.Sqrt((dx * dx) + (dy * dy)); + if (len > 1f) + { + dx /= len; + dy /= len; + } + else + { + dx = Math.Clamp(dx, -1f, 1f); + dy = Math.Clamp(dy, -1f, 1f); + } + + TryGetJsonFloat(source, out var aimAngle, "aimAngle", "rotation", "angle"); + return (dx, dy, aimAngle); + } + catch + { + return (0f, 0f, 0f); + } + } + + private static bool TryGetJsonProperty(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 TryGetJsonFloat(JsonElement source, out float value, params string[] names) + { + foreach (var n in names) + { + if (!TryGetJsonProperty(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 IsDirectionalValue(float value) + => float.IsFinite(value) && value >= -1.05f && value <= 1.05f; + private void HandleInputAttack(DungeonPlayerSession session, ReadOnlyMemory payload) { if (session.PlayerInstance == null) return; diff --git a/Game/World/WorldHandler.cs b/Game/World/WorldHandler.cs index e367f4b..9b3127e 100644 --- a/Game/World/WorldHandler.cs +++ b/Game/World/WorldHandler.cs @@ -202,7 +202,7 @@ public sealed class WorldHandler : IClientMessageHandler { if (!_players.TryGetValue(conn.Id, out var s)) { await SendErrorAsync(conn, "world_not_spawned", ct); return; } if (s.AccountId != accountId) { await SendErrorAsync(conn, "session_account_mismatch", ct); return; } - var req = ParseWorldInput(payload); + var req = ParseWorldInput(payload, s.X, s.Y); if (req == null) { return; } var dx = MathF.Max(-1f, MathF.Min(1f, req.MoveX)); @@ -565,7 +565,7 @@ public sealed class WorldHandler : IClientMessageHandler catch { return default; } } - private InputReq? ParseWorldInput(ReadOnlyMemory payload) + private InputReq? ParseWorldInput(ReadOnlyMemory payload, float currentX, float currentY) { if (payload.IsEmpty) return null; @@ -577,35 +577,46 @@ public sealed class WorldHandler : IClientMessageHandler // Some clients wrap movement inside an "input" object. var source = root; - var sourceIsNestedInput = false; if (TryGetProperty(root, "input", out var nested) && nested.ValueKind == JsonValueKind.Object) { source = nested; - sourceIsNestedInput = true; } - // Accept top-level x/y only when they look like direction input; reject absolute coords. - float moveX; - float moveY; - var hasMoveX = sourceIsNestedInput - ? TryGetFloat(source, out moveX, "moveX", "dx", "inputX", "x", "horizontal") - : TryGetFloat(source, out moveX, "moveX", "dx", "inputX", "horizontal"); - var hasMoveY = sourceIsNestedInput - ? TryGetFloat(source, out moveY, "moveY", "dy", "inputY", "y", "vertical") - : TryGetFloat(source, out moveY, "moveY", "dy", "inputY", "vertical"); - if (!sourceIsNestedInput) + 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)) { - if (!hasMoveX && TryGetFloat(source, out var maybeX, "x") && IsDirectionalValue(maybeX)) + moveX = rawX; + hasMoveX = true; + } + if (!hasMoveY && hasRawY && IsDirectionalValue(rawY)) + { + moveY = rawY; + hasMoveY = true; + } + + // Compatibility: clients that send absolute target x/y (dungeon-style). + if (!hasMoveX && !hasMoveY && hasRawX && hasRawY && (!IsDirectionalValue(rawX) || !IsDirectionalValue(rawY))) + { + var dx = rawX - currentX; + var dy = rawY - currentY; + var len = MathF.Sqrt((dx * dx) + (dy * dy)); + if (len > 0.001f) { - moveX = maybeX; + moveX = dx / len; + moveY = dy / len; hasMoveX = true; - } - if (!hasMoveY && TryGetFloat(source, out var maybeY, "y") && IsDirectionalValue(maybeY)) - { - moveY = maybeY; hasMoveY = true; } } + if (!hasMoveX && !hasMoveY) { return null; diff --git a/Networking/Messages/OpCodes.cs b/Networking/Messages/OpCodes.cs index 74261fb..c783107 100644 --- a/Networking/Messages/OpCodes.cs +++ b/Networking/Messages/OpCodes.cs @@ -86,34 +86,34 @@ public static class OpCodes /// public const int CHAR_SELECT_RESULT = 205; - // ===== World/Overworld (300-319) ===== + // ===== World/Overworld (700-719) ===== /// /// Client -> Server: Request to spawn in world after character selection /// - public const int WORLD_SPAWN_REQUEST = 300; + public const int WORLD_SPAWN_REQUEST = 700; /// /// Server -> Client: Spawn notification (your own character or other players joining) /// - public const int WORLD_SPAWN = 301; + public const int WORLD_SPAWN = 701; /// /// Server -> Client: Despawn notification (player leaving) /// - public const int WORLD_DESPAWN = 302; + public const int WORLD_DESPAWN = 702; /// /// Client -> Server: Player input (movement, actions) /// Sent at ~20 Hz or per tick /// - public const int WORLD_INPUT = 310; + public const int WORLD_INPUT = 710; /// /// Server -> Client: World state snapshot /// Sent at ~10-20 Hz /// - public const int WORLD_STATE = 311; + public const int WORLD_STATE = 711; // ===== Error Messages (900-999) ===== diff --git a/Networking/NetworkManager.cs b/Networking/NetworkManager.cs index fe01bf7..3262318 100644 --- a/Networking/NetworkManager.cs +++ b/Networking/NetworkManager.cs @@ -320,35 +320,42 @@ public sealed class NetworkManager // Notify router about disconnection for handler cleanup (e.g., DungeonHandler) _router.OnDisconnect(conn.Id); - if (_sessions.TryGet(conn.Id, out var accountId, out var token) - && accountId != 0 && !string.IsNullOrEmpty(token)) + if (_sessions.TryGet(conn.Id, out var accountId, out var token)) { try { - var onlineKey = $"online:acct:{accountId}"; - var sessKey = $"sess:{token}"; + if (accountId != 0 && !string.IsNullOrEmpty(token)) + { + var onlineKey = $"online:acct:{accountId}"; + var sessKey = $"sess:{token}"; - const string lua = @" + const string lua = @" if redis.call('GET', KEYS[1]) == ARGV[1] then redis.call('DEL', KEYS[1]) end redis.call('DEL', KEYS[2]) return 1"; - await _redis.Db.ScriptEvaluateAsync(lua, - new StackExchange.Redis.RedisKey[] { onlineKey, sessKey }, - new StackExchange.Redis.RedisValue[] { token }); + await _redis.Db.ScriptEvaluateAsync(lua, + new StackExchange.Redis.RedisKey[] { onlineKey, sessKey }, + new StackExchange.Redis.RedisValue[] { token }); - // NEW: close the SQL session audit row - await _sessionAudit.EndAsync(accountId, token, reason); - - _sessions.Unbind(conn.Id); - _log.LogInformation("Logged out account {AccountId} on disconnect", accountId); + // NEW: close the SQL session audit row + await _sessionAudit.EndAsync(accountId, token, reason); + _log.LogInformation("Logged out account {AccountId} on disconnect", accountId); + } } catch (Exception ex) { _log.LogWarning(ex, "Failed logout cleanup for account {AccountId}", accountId); - try { await _sessionAudit.EndAsync(accountId, token, reason); } catch { } + if (accountId != 0 && !string.IsNullOrEmpty(token)) + { + try { await _sessionAudit.EndAsync(accountId, token, reason); } catch { } + } + } + finally + { + // Always clear in-memory auth binding for closed connections. _sessions.Unbind(conn.Id); } } diff --git a/pending-clientChanges.md b/pending-clientChanges.md index c63900b..91810ff 100644 --- a/pending-clientChanges.md +++ b/pending-clientChanges.md @@ -137,11 +137,11 @@ ### Runtime opcodes -- `WORLD_SPAWN_REQUEST` (`300`) -- `WORLD_SPAWN` (`301`) -- `WORLD_DESPAWN` (`302`) -- `WORLD_INPUT` (`310`) -- `WORLD_STATE` (`311`) +- `WORLD_SPAWN_REQUEST` (`700`) +- `WORLD_SPAWN` (`701`) +- `WORLD_DESPAWN` (`702`) +- `WORLD_INPUT` (`710`) +- `WORLD_STATE` (`711`) ### Client world navigation requirements @@ -159,12 +159,12 @@ ### Implemented runtime packet contract -- `WORLD_SPAWN_REQUEST` (`300`) request: +- `WORLD_SPAWN_REQUEST` (`700`) request: - `{ regionId?, zoneX?, zoneY?, chunkX?, chunkY? }` - all fields optional. - if not provided, server prefers persisted character world location. - if character has no saved world location, server defaults to first enabled region at `zone/chunk = 0,0`. -- `WORLD_SPAWN` (`301`) response: +- `WORLD_SPAWN` (`701`) response: - `success` - `player`: `{ id, name, x, y, regionId, zoneX, zoneY, chunkX, chunkY, isVip }` - `region`: `{ id, name, zonesX, zonesY, chunksPerZoneX, chunksPerZoneY, chunkWidthTiles, chunkHeightTiles }` @@ -172,9 +172,9 @@ - `initialChunks[]`: subset of `chunkUpdates` entries where `type = "chunk_full"`: - `{ type: "chunk_full", chunk, tiles[], objects[], npcs[], mobs[] }` - `nearbyPlayers[]`: `{ id, name, x, y, facing, speed, isMoving }` -- `WORLD_INPUT` (`310`) request (20hz max): +- `WORLD_INPUT` (`710`) request (20hz max): - `{ seq, moveX, moveY, isRunning, facing }` -- `WORLD_STATE` (`311`) response (10-20hz): +- `WORLD_STATE` (`711`) response (10-20hz): - `tick` - `ackSeq` - `self`: `{ x, y, velocityX, velocityY }` @@ -187,7 +187,7 @@ - world teleport: `{ type: "world_teleport", sourceObjectId, regionId, zoneX, zoneY, chunkX, chunkY, x, y }` - dungeon transfer request: `{ type: "dungeon_request", sourceObjectId, portalType, dungeonTemplateId?, randomTier?, levelBracketMin?, levelBracketMax? }` - `errors[]` optional: e.g. `["blocked_non_walkable"]`, `["blocked_paywall"]`. -- `WORLD_DESPAWN` (`302`) response: +- `WORLD_DESPAWN` (`702`) response: - `{ playerId, reason }`. ### Chunk update handling rules in client