Persist player overworld location and add world mob spawn editing/runtime payloads

This commit is contained in:
dingo
2026-02-15 08:47:09 -05:00
parent 3c03bc40fa
commit d6b691e534
7 changed files with 330 additions and 18 deletions
+56 -12
View File
@@ -89,6 +89,7 @@ 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);
}
}
@@ -110,18 +111,25 @@ public sealed class WorldHandler : IClientMessageHandler
await db.SaveChangesAsync(ct);
}
var region = await ResolveRegionAsync(db, req.RegionId, ct);
var region = await ResolveRegionAsync(db, req.RegionId ?? character.WorldRegionId, ct);
if (region == null) { await SendErrorAsync(conn, "region_not_found", ct); return; }
await EnsureZonesAsync(db, region, ct);
var zx = Math.Clamp(req.ZoneX ?? 0, 0, Math.Max(0, region.ZonesPerRegionX - 1));
var zy = Math.Clamp(req.ZoneY ?? 0, 0, Math.Max(0, region.ZonesPerRegionY - 1));
var cx = Math.Clamp(req.ChunkX ?? 0, 0, Math.Max(0, region.ChunksPerZoneX - 1));
var cy = Math.Clamp(req.ChunkY ?? 0, 0, Math.Max(0, region.ChunksPerZoneY - 1));
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));
var cx = Math.Clamp(req.ChunkX ?? character.WorldChunkX ?? 0, 0, Math.Max(0, region.ChunksPerZoneX - 1));
var cy = Math.Clamp(req.ChunkY ?? character.WorldChunkY ?? 0, 0, Math.Max(0, region.ChunksPerZoneY - 1));
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 = WorldPxX(region, zx, cx, tx);
var y = WorldPxY(region, zy, cy, ty);
var x = requestedExplicitChunk
? WorldPxX(region, zx, cx, tx)
: (character.WorldX ?? WorldPxX(region, zx, cx, tx));
var y = requestedExplicitChunk
? WorldPxY(region, zy, cy, ty)
: (character.WorldY ?? WorldPxY(region, zy, cy, ty));
if (!float.IsFinite(x) || x < 0f) x = WorldPxX(region, zx, cx, tx);
if (!float.IsFinite(y) || y < 0f) y = WorldPxY(region, zy, cy, ty);
var (pzX, pzY, pcX, pcY) = ToChunkPos(region, x, y);
var s = new SessionState
@@ -142,6 +150,16 @@ public sealed class WorldHandler : IClientMessageHandler
};
_players[conn.Id] = s;
character.WorldRegionId = s.RegionId;
character.WorldZoneX = s.ZoneX;
character.WorldZoneY = s.ZoneY;
character.WorldChunkX = s.ChunkX;
character.WorldChunkY = s.ChunkY;
character.WorldX = s.X;
character.WorldY = s.Y;
character.LastPlayedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
var initial = await ChunkUpdatesAsync(db, region, s, ct);
await SendAsync(conn, OpCodes.WORLD_SPAWN, new
{
@@ -250,7 +268,7 @@ public sealed class WorldHandler : IClientMessageHandler
if (!s.ChunkVersions.TryGetValue(key, out var known) || known != data.version)
{
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 }));
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())
@@ -262,20 +280,21 @@ public sealed class WorldHandler : IClientMessageHandler
return list;
}
private async Task<(long version, object chunk, object[] tiles, object[] objects, object[] npcs)> LoadChunkAsync(GameDbContext db, WorldRegion region, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct)
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>());
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>());
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}", 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);
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());
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)
@@ -408,6 +427,31 @@ public sealed class WorldHandler : IClientMessageHandler
await Task.WhenAll(tasks);
}
private async Task PersistPlayerLocationAsync(SessionState s)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId);
if (character == null) return;
character.WorldRegionId = s.RegionId;
character.WorldZoneX = s.ZoneX;
character.WorldZoneY = s.ZoneY;
character.WorldChunkX = s.ChunkX;
character.WorldChunkY = s.ChunkY;
character.WorldX = s.X;
character.WorldY = s.Y;
character.LastPlayedAt = DateTime.UtcNow;
await db.SaveChangesAsync();
}
catch (Exception ex)
{
_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
+74 -2
View File
@@ -30,6 +30,7 @@
var objectsJson = JsonSerializer.Serialize(Model.ObjectDefinitions.Select(o => new { id = o.Id, name = o.Name }));
var npcsJson = JsonSerializer.Serialize(Model.NpcDefinitions.Select(n => new { id = n.Id, name = n.Name }));
var mobsJson = JsonSerializer.Serialize(Model.MobDefinitions.Select(m => new { id = m.Id, name = m.Name }));
var tileDefsJson = JsonSerializer.Serialize(Model.TileDefinitions.Select(t => new
{
id = t.Id,
@@ -45,7 +46,7 @@
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold text-white">World Editor</h1>
<p class="text-gray-400 mt-1">Live chunk editing for tiles, objects, and NPC spawns</p>
<p class="text-gray-400 mt-1">Live chunk editing for tiles, objects, NPC spawns, and mob spawns</p>
</div>
</div>
@@ -132,6 +133,7 @@
<option value="tile">Tile</option>
<option value="object">Object</option>
<option value="npc">NPC</option>
<option value="mob">Mob</option>
<option value="erase">Erase</option>
</select>
</div>
@@ -141,6 +143,7 @@
<option value="tile">Tile</option>
<option value="object">Object</option>
<option value="npc">NPC</option>
<option value="mob">Mob</option>
</select>
</div>
</div>
@@ -186,6 +189,22 @@
<label class="label">NPC</label>
<select id="npcDefinitionId" class="input"></select>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Mob Tool</h2>
<label class="label">Mob</label>
<select id="mobDefinitionId" class="input"></select>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="label">Spawn Count</label>
<input id="mobSpawnCount" type="number" class="input" min="1" value="1" />
</div>
<div>
<label class="label">Respawn Sec</label>
<input id="mobRespawnSeconds" type="number" class="input" min="0" step="1" value="30" />
</div>
</div>
</div>
</div>
<div class="xl:col-span-9 space-y-4">
@@ -223,6 +242,7 @@
const sheets = @Html.Raw(sheetsJson);
const objectDefs = @Html.Raw(objectsJson);
const npcDefs = @Html.Raw(npcsJson);
const mobDefs = @Html.Raw(mobsJson);
const tileDefs = @Html.Raw(tileDefsJson);
const cdnBaseUrl = '@Model.CdnBaseUrl';
@@ -232,6 +252,7 @@
let currentTiles = new Map();
let currentObjects = [];
let currentNpcs = [];
let currentMobs = [];
let eventSource = null;
let chunkZoom = 1;
const tileDefBySprite = {};
@@ -273,6 +294,7 @@
document.getElementById('objectDefinitionId').innerHTML = objectDefs.map(o => `<option value="${o.id}">${o.name}</option>`).join('');
document.getElementById('npcDefinitionId').innerHTML = npcDefs.map(n => `<option value="${n.id}">${n.name}</option>`).join('');
document.getElementById('mobDefinitionId').innerHTML = mobDefs.map(m => `<option value="${m.id}">${m.name}</option>`).join('');
}
function refreshRegionSelect(selectedId) {
@@ -346,6 +368,7 @@
for (const t of data.tiles) preloadSheetImage(t.sheetId);
currentObjects = data.objects || [];
currentNpcs = data.npcs || [];
currentMobs = data.mobs || [];
document.getElementById('chunkMeta').textContent = `Chunk ${s.zoneX}:${s.zoneY}:${s.chunkX}:${s.chunkY} v${currentChunk.version} (${currentChunk.width}x${currentChunk.height})`;
renderChunk();
startStream();
@@ -405,15 +428,23 @@
else currentNpcs.push({ ...op });
} else if (op.type === 'npc_remove') {
currentNpcs = currentNpcs.filter(n => n.id !== op.id);
} else if (op.type === 'mob_upsert') {
const idx = currentMobs.findIndex(m => m.id === op.id);
if (idx >= 0) currentMobs[idx] = { ...currentMobs[idx], ...op };
else currentMobs.push({ ...op });
} else if (op.type === 'mob_remove') {
currentMobs = currentMobs.filter(m => m.id !== op.id);
} else if (op.type === 'chunk_clear') {
currentTiles.clear();
currentObjects = [];
currentNpcs = [];
currentMobs = [];
} else if (op.type === 'chunk_deleted') {
currentChunk = null;
currentTiles.clear();
currentObjects = [];
currentNpcs = [];
currentMobs = [];
chunkCtx.clearRect(0, 0, chunkCanvas.width, chunkCanvas.height);
document.getElementById('chunkMeta').textContent = 'Chunk deleted';
loadZone();
@@ -554,6 +585,17 @@
chunkCtx.rect(px - Math.max(2, tileSize * 0.2), py - Math.max(2, tileSize * 0.2), Math.max(4, tileSize * 0.4), Math.max(4, tileSize * 0.4));
chunkCtx.fill();
}
for (const m of currentMobs) {
const px = m.x * tileSize + tileSize / 2;
const py = m.y * tileSize + tileSize / 2;
chunkCtx.fillStyle = '#ef4444';
chunkCtx.beginPath();
chunkCtx.moveTo(px, py - Math.max(3, tileSize * 0.28));
chunkCtx.lineTo(px + Math.max(3, tileSize * 0.28), py + Math.max(3, tileSize * 0.28));
chunkCtx.lineTo(px - Math.max(3, tileSize * 0.28), py + Math.max(3, tileSize * 0.28));
chunkCtx.closePath();
chunkCtx.fill();
}
const mode = document.getElementById('paintMode').value;
document.getElementById('eraseTargetWrap').classList.toggle('hidden', mode !== 'erase');
@@ -636,6 +678,25 @@
if (idx >= 0) currentNpcs[idx] = { ...currentNpcs[idx], ...data.op };
else currentNpcs.push(data.op);
}
} else if (mode === 'mob') {
const mobDefinitionId = parseInt(document.getElementById('mobDefinitionId').value, 10) || 0;
const spawnCount = parseInt(document.getElementById('mobSpawnCount').value, 10) || 1;
const respawnSeconds = parseFloat(document.getElementById('mobRespawnSeconds').value) || 30;
const data = await postJson('/admin/worldeditor?handler=UpsertMob', {
...s,
mobDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0,
spawnCount,
respawnSeconds
});
if (data.success) {
currentChunk.version = data.chunkVersion;
const idx = currentMobs.findIndex(m => m.id === data.op.id);
if (idx >= 0) currentMobs[idx] = { ...currentMobs[idx], ...data.op };
else currentMobs.push(data.op);
}
} else if (mode === 'erase') {
const eraseTarget = document.getElementById('eraseTarget').value;
if (eraseTarget === 'tile') {
@@ -662,6 +723,15 @@
currentNpcs = currentNpcs.filter(n => n.id !== hit.id);
}
}
} else if (eraseTarget === 'mob') {
const hit = currentMobs.find(m => m.x === pos.x && m.y === pos.y);
if (hit) {
const data = await postJson('/admin/worldeditor?handler=RemoveMob', { ...s, id: hit.id });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentMobs = currentMobs.filter(m => m.id !== hit.id);
}
}
}
}
@@ -807,13 +877,14 @@
currentTiles.clear();
currentObjects = [];
currentNpcs = [];
currentMobs = [];
renderChunk();
loadZone();
}
async function deleteChunk() {
if (!currentChunk) return;
if (!confirm('Delete this chunk and all contained tiles/objects/NPC spawns?')) return;
if (!confirm('Delete this chunk and all contained tiles/objects/NPC spawns/mob spawns?')) return;
const s = selection();
const data = await postJson('/admin/worldeditor?handler=DeleteChunk', s);
if (!data.success) return;
@@ -821,6 +892,7 @@
currentTiles.clear();
currentObjects = [];
currentNpcs = [];
currentMobs = [];
chunkCtx.clearRect(0, 0, chunkCanvas.width, chunkCanvas.height);
document.getElementById('chunkMeta').textContent = 'Chunk deleted';
loadZone();
@@ -26,6 +26,7 @@ public class IndexModel : AdminPageModel
public List<TileDefinition> TileDefinitions { get; set; } = new();
public List<DungeonObjectDefinition> ObjectDefinitions { get; set; } = new();
public List<DungeonNpcDefinition> NpcDefinitions { get; set; } = new();
public List<DungeonMobDefinition> MobDefinitions { get; set; } = new();
public int SelectedRegionId { get; set; }
public int SelectedZoneX { get; set; }
@@ -82,6 +83,11 @@ public class IndexModel : AdminPageModel
.Where(n => n.IsEnabled)
.OrderBy(n => n.Name)
.ToListAsync();
MobDefinitions = await _db.DungeonMobDefinitions
.Where(m => m.IsEnabled)
.OrderBy(m => m.Name)
.ToListAsync();
}
public async Task<IActionResult> OnGetRegionAsync(int regionId)
@@ -282,6 +288,24 @@ public class IndexModel : AdminPageModel
})
.ToListAsync();
var mobs = await _db.WorldChunkMobSpawns
.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
})
.ToListAsync();
return new JsonResult(new
{
success = true,
@@ -299,7 +323,8 @@ public class IndexModel : AdminPageModel
},
tiles,
objects,
npcs
npcs,
mobs
});
}
@@ -443,10 +468,12 @@ public class IndexModel : AdminPageModel
var tiles = _db.WorldChunkTiles.Where(t => t.WorldChunkId == locate.Chunk.Id);
var objects = _db.WorldChunkObjects.Where(o => o.WorldChunkId == locate.Chunk.Id);
var npcs = _db.WorldChunkNpcSpawns.Where(n => n.WorldChunkId == locate.Chunk.Id);
var mobs = _db.WorldChunkMobSpawns.Where(m => m.WorldChunkId == locate.Chunk.Id);
_db.WorldChunkTiles.RemoveRange(tiles);
_db.WorldChunkObjects.RemoveRange(objects);
_db.WorldChunkNpcSpawns.RemoveRange(npcs);
_db.WorldChunkMobSpawns.RemoveRange(mobs);
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
@@ -734,6 +761,121 @@ public class IndexModel : AdminPageModel
});
}
public async Task<IActionResult> OnPostUpsertMobAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY,
long? id,
int mobDefinitionId,
int x,
int y,
int rotation = 0,
int spawnCount = 1,
float respawnSeconds = 30,
string? metadataJson = null)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
if (!IsInside(locate.Region.ChunkWidthTiles, locate.Region.ChunkHeightTiles, x, y))
{
return new JsonResult(new { success = false, error = "tile_out_of_bounds" }) { StatusCode = 400 };
}
var mobDef = await _db.DungeonMobDefinitions.FirstOrDefaultAsync(m => m.Id == mobDefinitionId && m.IsEnabled);
if (mobDef == null)
{
return new JsonResult(new { success = false, error = "mob_definition_not_found" }) { StatusCode = 404 };
}
WorldChunkMobSpawn mob;
if (id.HasValue)
{
mob = await _db.WorldChunkMobSpawns.FirstOrDefaultAsync(m => m.Id == id.Value && m.WorldChunkId == locate.Chunk.Id)
?? new WorldChunkMobSpawn { WorldChunkId = locate.Chunk.Id };
if (mob.Id == 0)
{
_db.WorldChunkMobSpawns.Add(mob);
}
}
else
{
mob = new WorldChunkMobSpawn { WorldChunkId = locate.Chunk.Id };
_db.WorldChunkMobSpawns.Add(mob);
}
mob.MobDefinitionId = mobDefinitionId;
mob.TileX = x;
mob.TileY = y;
mob.Rotation = rotation;
mob.SpawnCount = Math.Clamp(spawnCount, 1, 100);
mob.RespawnSeconds = Math.Clamp(respawnSeconds, 0f, 86400f);
mob.MetadataJson = string.IsNullOrWhiteSpace(metadataJson) ? null : metadataJson.Trim();
var fromVersion = locate.Chunk.Version;
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
var op = new
{
type = "mob_upsert",
id = mob.Id,
x = mob.TileX,
y = mob.TileY,
mobDefinitionId = mob.MobDefinitionId,
mobName = mobDef.Name,
rotation = mob.Rotation,
spawnCount = mob.SpawnCount,
respawnSeconds = mob.RespawnSeconds,
metadataJson = mob.MetadataJson
};
PublishDelta(regionId, zoneX, zoneY, chunkX, chunkY, fromVersion, locate.Chunk.Version, op);
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
fromVersion,
toVersion = locate.Chunk.Version,
op
});
}
public async Task<IActionResult> OnPostRemoveMobAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long id)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var mob = await _db.WorldChunkMobSpawns.FirstOrDefaultAsync(m => m.Id == id && m.WorldChunkId == locate.Chunk.Id);
if (mob != null)
{
var fromVersion = locate.Chunk.Version;
_db.WorldChunkMobSpawns.Remove(mob);
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
var op = new { type = "mob_remove", id };
PublishDelta(regionId, zoneX, zoneY, chunkX, chunkY, fromVersion, locate.Chunk.Version, op);
}
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new { type = "mob_remove", id }
});
}
private async Task EnsureDefaultRegionAsync()
{
if (await _db.WorldRegions.AnyAsync())
+1
View File
@@ -87,6 +87,7 @@ public sealed class GameDbContext : DbContext
public DbSet<WorldChunkTile> WorldChunkTiles => Set<WorldChunkTile>();
public DbSet<WorldChunkObject> WorldChunkObjects => Set<WorldChunkObject>();
public DbSet<WorldChunkNpcSpawn> WorldChunkNpcSpawns => Set<WorldChunkNpcSpawn>();
public DbSet<WorldChunkMobSpawn> WorldChunkMobSpawns => Set<WorldChunkMobSpawn>();
protected override void OnModelCreating(ModelBuilder b)
{
+9
View File
@@ -50,6 +50,15 @@ public class DungeonCharacter
// Currency
public long Gold { get; set; } = 0;
// Overworld persistent location
public int? WorldRegionId { get; set; }
public int? WorldZoneX { get; set; }
public int? WorldZoneY { get; set; }
public int? WorldChunkX { get; set; }
public int? WorldChunkY { get; set; }
public float? WorldX { get; set; }
public float? WorldY { get; set; }
// Equipment slots (ItemId references, null = empty)
public ulong? EquippedWeapon { get; set; }
+37
View File
@@ -129,6 +129,31 @@ public class WorldChunkNpcSpawn
public string? MetadataJson { get; set; }
}
[Table("world_chunk_mob_spawns")]
public class WorldChunkMobSpawn
{
[Key]
public long Id { get; set; }
public long WorldChunkId { get; set; }
[ForeignKey(nameof(WorldChunkId))]
public WorldChunk? Chunk { get; set; }
public int MobDefinitionId { get; set; }
[ForeignKey(nameof(MobDefinitionId))]
public DungeonMobDefinition? MobDefinition { get; set; }
public int TileX { get; set; }
public int TileY { get; set; }
public int Rotation { get; set; }
public int SpawnCount { get; set; } = 1;
public float RespawnSeconds { get; set; } = 30f;
[MaxLength(1024)]
public string? MetadataJson { get; set; }
}
public sealed class WorldRegionConfig : IEntityTypeConfiguration<WorldRegion>
{
public void Configure(EntityTypeBuilder<WorldRegion> e)
@@ -196,3 +221,15 @@ public sealed class WorldChunkNpcSpawnConfig : IEntityTypeConfiguration<WorldChu
.OnDelete(DeleteBehavior.Cascade);
}
}
public sealed class WorldChunkMobSpawnConfig : IEntityTypeConfiguration<WorldChunkMobSpawn>
{
public void Configure(EntityTypeBuilder<WorldChunkMobSpawn> e)
{
e.HasIndex(x => new { x.WorldChunkId, x.TileX, x.TileY, x.MobDefinitionId });
e.HasOne(x => x.Chunk)
.WithMany()
.HasForeignKey(x => x.WorldChunkId)
.OnDelete(DeleteBehavior.Cascade);
}
}
+10 -3
View File
@@ -114,6 +114,8 @@
- `object_remove`: `{ id }`
- `npc_upsert`: `{ id, x, y, npcDefinitionId, npcName, rotation, metadataJson }`
- `npc_remove`: `{ id }`
- `mob_upsert`: `{ id, x, y, mobDefinitionId, mobName, rotation, spawnCount, respawnSeconds, metadataJson }`
- `mob_remove`: `{ id }`
- `chunk_clear`: `{}`
- `chunk_deleted`: `{}`
@@ -159,13 +161,15 @@
- `WORLD_SPAWN_REQUEST` (`300`) request:
- `{ regionId?, zoneX?, zoneY?, chunkX?, chunkY? }`
- all fields optional; server defaults to the first enabled region at `zone/chunk = 0,0`.
- 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:
- `success`
- `player`: `{ id, name, x, y, regionId, zoneX, zoneY, chunkX, chunkY, isVip }`
- `region`: `{ id, name, zonesX, zonesY, chunksPerZoneX, chunksPerZoneY, chunkWidthTiles, chunkHeightTiles }`
- `initialChunks[]`: subset of `chunkUpdates` entries where `type = "chunk_full"`:
- `{ type: "chunk_full", chunk, tiles[], objects[], npcs[] }`
- `{ type: "chunk_full", chunk, tiles[], objects[], npcs[], mobs[] }`
- `nearbyPlayers[]`: `{ id, name, x, y, facing, speed, isMoving }`
- `WORLD_INPUT` (`310`) request (20hz max):
- `{ seq, moveX, moveY, isRunning, facing }`
@@ -175,7 +179,7 @@
- `self`: `{ x, y, velocityX, velocityY }`
- `players[]`: `{ id, name, x, y, facing, speed, isMoving, regionId, zoneX, zoneY, chunkX, chunkY }`
- `chunkUpdates[]`:
- `chunk_full`: `{ type, chunk, tiles[], objects[], npcs[] }`
- `chunk_full`: `{ type, chunk, tiles[], objects[], npcs[], mobs[] }`
- `chunk_unload`: `{ type, regionId, zoneX, zoneY, chunkX, chunkY }`
- `errors[]` optional: e.g. `["blocked_non_walkable"]`, `["blocked_paywall"]`.
- `WORLD_DESPAWN` (`302`) response:
@@ -188,6 +192,9 @@
- `chunk_unload`:
- remove cache entry and unload chunk visuals/colliders.
- server emits `chunk_full` when entering visibility range or when chunk version changes.
- player world location persistence:
- server saves `{ regionId, zoneX, zoneY, chunkX, chunkY, x, y }` on disconnect.
- next world spawn (without explicit location override) returns player to that saved position.
### Rendering and assets