Files
systemrevivalserver/Game/World/WorldMovementService.cs
T
2026-02-16 08:56:15 -05:00

314 lines
12 KiB
C#

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; }
}
}