512 lines
18 KiB
C#
512 lines
18 KiB
C#
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 ZoneZ { 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 zoneZ, int chunkX, int chunkY, CancellationToken ct = default)
|
|
{
|
|
var key = ChunkKey(regionId, zoneX, zoneY, zoneZ, 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, zoneZ, chunkX, chunkY, ct);
|
|
_chunks[key] = cached;
|
|
return cached;
|
|
}
|
|
finally
|
|
{
|
|
loadLock.Release();
|
|
}
|
|
}
|
|
|
|
public bool IsTileWalkable(CachedRegion region, int zoneZ, 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, zoneZ, 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, int zoneZ, float wx, float wy, bool isVip)
|
|
{
|
|
if (!IsTileWalkable(region, zoneZ, wx, wy, isVip)) return false;
|
|
if (!IsTileWalkable(region, zoneZ, wx + 8f, wy, isVip)) return false;
|
|
if (!IsTileWalkable(region, zoneZ, wx - 8f, wy, isVip)) return false;
|
|
if (!IsTileWalkable(region, zoneZ, wx, wy + 8f, isVip)) return false;
|
|
if (!IsTileWalkable(region, zoneZ, wx, wy - 8f, isVip)) return false;
|
|
return true;
|
|
}
|
|
|
|
public CachedPortalObject? FindPortalAtPosition(CachedRegion region, int zoneZ, 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, zoneZ, 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 zoneZ, int chunkX, int chunkY)
|
|
{
|
|
var key = ChunkKey(regionId, zoneX, zoneY, zoneZ, 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>();
|
|
|
|
// Only auto-create Z=0 (ground level) zones
|
|
var existing = await db.WorldZones
|
|
.Where(z => z.RegionId == regionId && z.ZoneZ == 0)
|
|
.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,
|
|
ZoneZ = 0,
|
|
Name = $"Zone {x},{y}",
|
|
IsEnabled = true,
|
|
CreatedAt = now,
|
|
UpdatedAt = now
|
|
});
|
|
changed = true;
|
|
}
|
|
if (changed) await db.SaveChangesAsync(ct);
|
|
}
|
|
|
|
// ---- Internal ----
|
|
|
|
public static string ChunkKey(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY)
|
|
=> $"{regionId}:{zoneX}:{zoneY}:{zoneZ}:{chunkX}:{chunkY}";
|
|
|
|
public static string ZoneKey(int regionId, int zoneX, int zoneY, int zoneZ)
|
|
=> $"{regionId}:{zoneX}:{zoneY}:{zoneZ}";
|
|
|
|
private async Task<CachedChunk?> LoadChunkFromDbAsync(int regionId, int zoneX, int zoneY, int zoneZ, 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.ZoneZ == zoneZ && z.IsEnabled, ct);
|
|
if (zone == null)
|
|
{
|
|
return BuildEmptyChunk(region, zoneX, zoneY, zoneZ, 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, zoneZ, 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,
|
|
zoneZ,
|
|
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, zoneZ, chunkX, chunkY), tiles.Count, objects.Count, portals.Length);
|
|
|
|
return new CachedChunk
|
|
{
|
|
DbId = chunk.Id,
|
|
Version = chunk.Version,
|
|
RegionId = regionId,
|
|
ZoneX = zoneX,
|
|
ZoneY = zoneY,
|
|
ZoneZ = zoneZ,
|
|
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 zoneZ, 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,
|
|
ZoneZ = zoneZ,
|
|
ChunkX = chunkX,
|
|
ChunkY = chunkY,
|
|
WidthTiles = w,
|
|
HeightTiles = h,
|
|
Walkable = walkable,
|
|
IsPaywall = new bool[w * h],
|
|
ChunkDto = new
|
|
{
|
|
regionId = region.Id,
|
|
zoneX,
|
|
zoneY,
|
|
zoneZ,
|
|
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>()
|
|
};
|
|
}
|
|
}
|