Add collision teleport portals and ledge-safe movement in VNext dungeons

This commit is contained in:
dingo
2026-02-14 15:05:10 -05:00
parent 147e7d625d
commit 8f7098af81
9 changed files with 382 additions and 34 deletions
+3
View File
@@ -2471,6 +2471,9 @@ public class PlacedObject
public bool IsTrap { get; set; }
public int TrapDamage { get; set; }
public int? LootTableId { get; set; }
public bool TriggeredByWalk { get; set; }
public string? InteractionType { get; set; }
public string? MetadataJson { get; set; }
}
public class RoomTilePlacement
{
+91
View File
@@ -26,6 +26,7 @@ public class DungeonGeneratorVNext
private readonly Dictionary<DungeonRoom, List<TemplateMobSpawn>> _templateMobSpawnsByRoom = new();
private readonly Dictionary<(int X, int Y), List<PlacedTile>> _templateTilesByCell = new();
private readonly Dictionary<int, TileDefinition> _tileDefinitionsById = new();
private readonly Dictionary<int, ObjectTemplate> _objectTemplatesById = new();
private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
public DungeonGeneratorVNext(GameDbContext db, int seed, int tier = 1, ILogger<DungeonGeneratorVNext>? logger = null)
@@ -49,6 +50,7 @@ public class DungeonGeneratorVNext
_templateMobSpawnsByRoom.Clear();
_templateTilesByCell.Clear();
_tileDefinitionsById.Clear();
_objectTemplatesById.Clear();
_selectedPalette = await SelectPaletteAsync();
await LoadRoomTemplatesAsync();
@@ -236,6 +238,39 @@ public class DungeonGeneratorVNext
_tileDefinitionsById[def.Id] = def;
}
var objectTemplateIds = new HashSet<int>();
foreach (var room in _roomTemplates)
{
if (string.IsNullOrWhiteSpace(room.ObjectPlacementsJson)) continue;
try
{
var objects = JsonSerializer.Deserialize<List<BuilderObjectPlacement>>(room.ObjectPlacementsJson, _jsonOptions);
if (objects == null) continue;
foreach (var obj in objects)
{
if (obj.ObjectTemplateId > 0)
{
objectTemplateIds.Add(obj.ObjectTemplateId);
}
}
}
catch
{
// Keep generation resilient if a room has malformed object placement JSON.
}
}
if (objectTemplateIds.Count > 0)
{
var objectTemplates = await _db.ObjectTemplates
.Where(o => o.IsEnabled && objectTemplateIds.Contains(o.Id))
.ToListAsync();
foreach (var template in objectTemplates)
{
_objectTemplatesById[template.Id] = template;
}
}
_logger?.LogInformation(
"VNext room templates loaded: {Count} templates (palette={PaletteId})",
_roomTemplates.Count,
@@ -457,6 +492,7 @@ public class DungeonGeneratorVNext
}
StampRoomTemplateTiles(layout, room, template);
StampRoomTemplateObjects(layout, room, template);
LoadTemplateMobSpawns(room, template);
}
}
@@ -593,6 +629,61 @@ public class DungeonGeneratorVNext
}
}
private void StampRoomTemplateObjects(DungeonLayoutV2 layout, DungeonRoom room, BuilderRoomTemplate template)
{
if (string.IsNullOrWhiteSpace(template.ObjectPlacementsJson)) return;
try
{
var objects = JsonSerializer.Deserialize<List<BuilderObjectPlacement>>(template.ObjectPlacementsJson, _jsonOptions);
if (objects == null || objects.Count == 0) return;
foreach (var obj in objects)
{
if (!_objectTemplatesById.TryGetValue(obj.ObjectTemplateId, out var objectTemplate))
{
continue;
}
int worldX = room.X + obj.X;
int worldY = room.Y + obj.Y;
if (worldX < 0 || worldY < 0 || worldX >= layout.Width || worldY >= layout.Height)
{
continue;
}
layout.Objects.Add(new PlacedObject
{
X = worldX,
Y = worldY,
ObjectTemplateId = objectTemplate.Id,
Name = objectTemplate.Name,
Type = objectTemplate.Type.ToString(),
SpriteSheetId = objectTemplate.SpriteSheetId ?? 0,
FrameIndex = objectTemplate.FrameIndex,
BlocksMovement = objectTemplate.BlocksMovement,
IsInteractable = objectTemplate.IsInteractable,
IsTrap = objectTemplate.Type == ObjectTemplateType.Trap || objectTemplate.Type == ObjectTemplateType.Hazard,
TrapDamage = objectTemplate.Damage,
LootTableId = objectTemplate.LootTableId,
TriggeredByWalk = objectTemplate.TriggeredByWalk,
InteractionType = objectTemplate.InteractionType.ToString(),
MetadataJson = string.IsNullOrWhiteSpace(obj.OverridesJson) ? null : obj.OverridesJson
});
if (objectTemplate.BlocksMovement)
{
layout.Walkable![worldX, worldY] = false;
layout.Tiles[worldX, worldY] = 0;
}
}
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "VNext failed parsing ObjectPlacementsJson for template {TemplateId}:{TemplateName}", template.Id, template.Name);
}
}
private void GenerateSpawnsAndChests(DungeonLayoutV2 layout, List<DungeonRoom> rooms)
{
layout.MobSpawns.Clear();
+9 -2
View File
@@ -385,9 +385,12 @@ public sealed partial class DungeonHandler
frame = o.FrameIndex,
blocks = o.BlocksMovement,
interact = o.IsInteractable,
triggeredByWalk = o.TriggeredByWalk,
interactionType = o.InteractionType,
trap = o.IsTrap,
damage = o.TrapDamage,
loot = o.LootTableId
loot = o.LootTableId,
metadataJson = o.MetadataJson
}).ToArray();
}
@@ -453,7 +456,11 @@ public sealed partial class DungeonHandler
id = p.Id,
x = p.X,
y = p.Y,
type = p.Type.ToString().ToLower()
type = p.Type.ToString().ToLower(),
triggerOnCollision = p.TriggerOnCollision,
triggerRadius = p.TriggerRadius,
destinationX = p.DestinationX,
destinationY = p.DestinationY
}),
// V3 visual tile data
tileSheets,
+33 -2
View File
@@ -854,9 +854,12 @@ public sealed partial class DungeonHandler : IClientMessageHandler
frame = o.FrameIndex,
blocks = o.BlocksMovement,
interact = o.IsInteractable,
triggeredByWalk = o.TriggeredByWalk,
interactionType = o.InteractionType,
trap = o.IsTrap,
damage = o.TrapDamage,
loot = o.LootTableId
loot = o.LootTableId,
metadataJson = o.MetadataJson
}).ToArray();
}
@@ -921,7 +924,11 @@ public sealed partial class DungeonHandler : IClientMessageHandler
id = p.Id,
x = p.X,
y = p.Y,
type = p.Type.ToString().ToLower()
type = p.Type.ToString().ToLower(),
triggerOnCollision = p.TriggerOnCollision,
triggerRadius = p.TriggerRadius,
destinationX = p.DestinationX,
destinationY = p.DestinationY
}),
// V3 visual tile data
tileSheets,
@@ -1351,6 +1358,30 @@ public sealed partial class DungeonHandler : IClientMessageHandler
return;
}
if (portal.DestinationX.HasValue && portal.DestinationY.HasValue)
{
if (!dungeon.Simulation.CanActorMoveTo(portal.DestinationX.Value, portal.DestinationY.Value))
{
_log.LogDebug("Player {Name} tried to use portal {Id} with blocked destination", session.Character.Name, portal.Id);
return;
}
player.X = portal.DestinationX.Value;
player.Y = portal.DestinationY.Value;
player.InputX = 0f;
player.InputY = 0f;
await SendAsync(connection, DungeonOpCodes.PORTAL_USED, new
{
portalId = portal.Id,
type = portal.Type.ToString().ToLower(),
teleported = true,
x = player.X,
y = player.Y
}, ct);
return;
}
_log.LogInformation("Player {Name} using exit portal", session.Character.Name);
// Send portal used confirmation
+15 -2
View File
@@ -144,9 +144,12 @@ public class DungeonLayoutV2 : DungeonLayout
frame = o.FrameIndex,
blocks = o.BlocksMovement,
interact = o.IsInteractable,
triggeredByWalk = o.TriggeredByWalk,
interactionType = o.InteractionType,
trap = o.IsTrap,
damage = o.TrapDamage,
loot = o.LootTableId
loot = o.LootTableId,
metadataJson = o.MetadataJson
}),
// Tile sheets
tileSheets = TileMapSheets.Select(s => new
@@ -194,7 +197,17 @@ public class DungeonLayoutV2 : DungeonLayout
rooms = Rooms.Select(r => new { x = r.X, y = r.Y, w = r.Width, h = r.Height, type = r.Type.ToString() }),
mobs = MobSpawns.Select(m => new { id = m.Id, x = m.X, y = m.Y, type = m.MobType.ToString() }),
chests = ChestSpawns.Select(c => new { id = c.Id, x = c.X, y = c.Y, type = c.ChestType.ToString() }),
objects = Objects.Select(o => new { x = o.X, y = o.Y, id = o.ObjectTemplateId, type = o.Type, blocks = o.BlocksMovement })
objects = Objects.Select(o => new
{
x = o.X,
y = o.Y,
id = o.ObjectTemplateId,
type = o.Type,
blocks = o.BlocksMovement,
triggeredByWalk = o.TriggeredByWalk,
interactionType = o.InteractionType,
metadataJson = o.MetadataJson
})
});
}
+190 -20
View File
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using System.Text.Json;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
@@ -60,6 +61,9 @@ public partial class DungeonSimulation
private readonly Dictionary<int, DungeonNpcDefinition>? _npcDefinitions;
private readonly List<(int MobDefinitionId, float X, float Y, int Tier)> _pendingSummons = new();
private readonly Random _npcWanderRandom = new();
private readonly Dictionary<ulong, long> _portalTeleportCooldownUntilTickByPlayer = new();
private const float ActorCollisionRadiusPx = 10f;
private const long PortalTeleportCooldownTicks = TicksPerSecond / 2;
public DungeonSimulation(
DungeonLayout layout,
@@ -84,6 +88,7 @@ public partial class DungeonSimulation
SpawnNpcs();
InitializeChests();
SpawnExitPortal();
SpawnTemplatePortals();
}
private void SpawnNpcs()
@@ -218,6 +223,114 @@ public partial class DungeonSimulation
};
Portals[fallbackPortal.Id] = fallbackPortal;
}
private void SpawnTemplatePortals()
{
if (Layout is not DungeonLayoutV2 layoutV2 || layoutV2.Objects.Count == 0)
{
return;
}
int nextPortalId = Portals.IsEmpty ? 100 : Portals.Keys.Max() + 1;
foreach (var obj in layoutV2.Objects)
{
if (!obj.Type.Equals(ObjectTemplateType.Portal.ToString(), StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (!TryParsePortalDestination(obj.MetadataJson, out var destX, out var destY))
{
continue;
}
var portal = new PortalInstance
{
Id = nextPortalId++,
X = obj.X * 32 + 16,
Y = obj.Y * 32 + 16,
Type = PortalType.Secret,
IsActive = true,
TriggerOnCollision = true,
TriggerRadius = 16f,
DestinationX = destX,
DestinationY = destY
};
Portals[portal.Id] = portal;
}
}
private static bool TryParsePortalDestination(string? metadataJson, out float destinationX, out float destinationY)
{
destinationX = 0f;
destinationY = 0f;
if (string.IsNullOrWhiteSpace(metadataJson))
{
return false;
}
try
{
using var doc = JsonDocument.Parse(metadataJson);
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object)
{
return false;
}
if (!TryReadCoordinate(root, "targetX", "targetTileX", out var rawX) ||
!TryReadCoordinate(root, "targetY", "targetTileY", out var rawY))
{
return false;
}
bool tileCoordinates = root.TryGetProperty("useTileCoords", out var useTileCoords) &&
useTileCoords.ValueKind == JsonValueKind.True;
destinationX = tileCoordinates ? rawX * 32f + 16f : rawX;
destinationY = tileCoordinates ? rawY * 32f + 16f : rawY;
return true;
}
catch
{
return false;
}
}
private static bool TryReadCoordinate(JsonElement root, string pxName, string tileName, out float value)
{
value = 0f;
if (root.TryGetProperty(pxName, out var px))
{
if (px.ValueKind == JsonValueKind.Number)
{
value = px.GetSingle();
return true;
}
if (px.ValueKind == JsonValueKind.String && float.TryParse(px.GetString(), out var parsedPx))
{
value = parsedPx;
return true;
}
}
if (root.TryGetProperty(tileName, out var tile))
{
if (tile.ValueKind == JsonValueKind.Number)
{
value = tile.GetSingle();
return true;
}
if (tile.ValueKind == JsonValueKind.String && float.TryParse(tile.GetString(), out var parsedTile))
{
value = parsedTile;
return true;
}
}
return false;
}
private void SpawnMobs()
{
@@ -427,6 +540,7 @@ public partial class DungeonSimulation
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
UpdatePlayer(player);
TryTriggerCollisionPortal(player);
}
UpdateNpcs();
@@ -497,9 +611,7 @@ public partial class DungeonSimulation
if ((distX * distX) + (distY * distY) > maxDistSq)
continue;
var tileX = (int)MathF.Floor(nx / 32f);
var tileY = (int)MathF.Floor(ny / 32f);
if (!Layout.IsWalkable(tileX, tileY))
if (!CanActorMoveTo(nx, ny))
continue;
npc.X = nx;
@@ -725,7 +837,7 @@ public partial class DungeonSimulation
float spawnX = mob.X + (float)Math.Cos(angle) * summonDistance;
float spawnY = mob.Y + (float)Math.Sin(angle) * summonDistance;
if (!CanMoveTo(spawnX, spawnY))
if (!CanActorMoveTo(spawnX, spawnY))
{
spawnX = mob.X + (float)Math.Cos(angle) * (summonDistance * 0.5f);
spawnY = mob.Y + (float)Math.Sin(angle) * (summonDistance * 0.5f);
@@ -1247,8 +1359,8 @@ public partial class DungeonSimulation
float newX = target.X + (dx / dist) * ability.DisplacementDistance;
float newY = target.Y + (dy / dist) * ability.DisplacementDistance;
if (CanMoveTo(newX, target.Y)) target.X = newX;
if (CanMoveTo(target.X, newY)) target.Y = newY;
if (CanActorMoveTo(newX, target.Y)) target.X = newX;
if (CanActorMoveTo(target.X, newY)) target.Y = newY;
}
}
@@ -1267,8 +1379,8 @@ public partial class DungeonSimulation
float newX = target.X + (dx / dist) * pullDist;
float newY = target.Y + (dy / dist) * pullDist;
if (CanMoveTo(newX, target.Y)) target.X = newX;
if (CanMoveTo(target.X, newY)) target.Y = newY;
if (CanActorMoveTo(newX, target.Y)) target.X = newX;
if (CanActorMoveTo(target.X, newY)) target.Y = newY;
}
}
}
@@ -1316,7 +1428,7 @@ public partial class DungeonSimulation
private bool TryFindWalkableNear(float x, float y, out float walkableX, out float walkableY)
{
if (CanMoveTo(x, y))
if (CanActorMoveTo(x, y))
{
walkableX = x;
walkableY = y;
@@ -1332,7 +1444,7 @@ public partial class DungeonSimulation
float angle = (MathF.PI * 2f * i) / 8f;
float testX = x + MathF.Cos(angle) * radius;
float testY = y + MathF.Sin(angle) * radius;
if (CanMoveTo(testX, testY))
if (CanActorMoveTo(testX, testY))
{
walkableX = testX;
walkableY = testY;
@@ -1472,8 +1584,8 @@ public partial class DungeonSimulation
float newX = player.X + player.InputX * speed;
float newY = player.Y + player.InputY * speed;
if (CanMoveTo(newX, player.Y)) player.X = newX;
if (CanMoveTo(player.X, newY)) player.Y = newY;
if (CanActorMoveTo(newX, player.Y)) player.X = newX;
if (CanActorMoveTo(player.X, newY)) player.Y = newY;
if (player.InputX != 0 || player.InputY != 0)
{
@@ -1500,8 +1612,8 @@ public partial class DungeonSimulation
float speed = player.MoveSpeed * 1.2f * TickDelta; // Run faster when feared
float newX = player.X + (dx / dist) * speed;
float newY = player.Y + (dy / dist) * speed;
if (CanMoveTo(newX, player.Y)) player.X = newX;
if (CanMoveTo(player.X, newY)) player.Y = newY;
if (CanActorMoveTo(newX, player.Y)) player.X = newX;
if (CanActorMoveTo(player.X, newY)) player.Y = newY;
}
}
}
@@ -1674,11 +1786,69 @@ public partial class DungeonSimulation
}
}
public bool CanMoveTo(float x, float y)
private void TryTriggerCollisionPortal(PlayerInstance player)
{
int tileX = (int)(x / 32);
int tileY = (int)(y / 32);
if (_portalTeleportCooldownUntilTickByPlayer.TryGetValue(player.CharacterId, out var cooldownUntilTick) &&
CurrentTick < cooldownUntilTick)
{
return;
}
foreach (var portal in Portals.Values)
{
if (!portal.IsActive || !portal.TriggerOnCollision || !portal.DestinationX.HasValue || !portal.DestinationY.HasValue)
{
continue;
}
float radius = portal.TriggerRadius > 0f ? portal.TriggerRadius : 18f;
if (Distance(player.X, player.Y, portal.X, portal.Y) > radius)
{
continue;
}
if (!CanActorMoveTo(portal.DestinationX.Value, portal.DestinationY.Value))
{
continue;
}
player.X = portal.DestinationX.Value;
player.Y = portal.DestinationY.Value;
player.InputX = 0f;
player.InputY = 0f;
_portalTeleportCooldownUntilTickByPlayer[player.CharacterId] = CurrentTick + PortalTeleportCooldownTicks;
break;
}
}
public bool CanMoveTo(float x, float y, float collisionRadiusPx = 0f)
{
if (!IsWalkableAtPoint(x, y))
{
return false;
}
if (collisionRadiusPx <= 0f)
{
return true;
}
float r = collisionRadiusPx;
return IsWalkableAtPoint(x - r, y - r) &&
IsWalkableAtPoint(x + r, y - r) &&
IsWalkableAtPoint(x - r, y + r) &&
IsWalkableAtPoint(x + r, y + r);
}
public bool CanActorMoveTo(float x, float y)
{
return CanMoveTo(x, y, ActorCollisionRadiusPx);
}
private bool IsWalkableAtPoint(float x, float y)
{
int tileX = (int)(x / 32f);
int tileY = (int)(y / 32f);
return Layout.IsWalkable(tileX, tileY);
}
@@ -1696,8 +1866,8 @@ public partial class DungeonSimulation
float newX = mob.X + (dx / dist) * moveAmount;
float newY = mob.Y + (dy / dist) * moveAmount;
if (CanMoveTo(newX, mob.Y)) mob.X = newX;
if (CanMoveTo(mob.X, newY)) mob.Y = newY;
if (CanActorMoveTo(newX, mob.Y)) mob.X = newX;
if (CanActorMoveTo(mob.X, newY)) mob.Y = newY;
mob.Rotation = MathF.Atan2(dy, dx);
}
+8 -8
View File
@@ -572,7 +572,7 @@ public static class MobAI
float targetY = mob.SpawnY + MathF.Sin(angle) * dist;
// Check if target is walkable
if (sim.CanMoveTo(targetX, targetY))
if (sim.CanActorMoveTo(targetX, targetY))
{
mob.WanderTargetX = targetX;
mob.WanderTargetY = targetY;
@@ -693,7 +693,7 @@ public static class MobAI
float newY = mob.Y + moveY;
// Check collision for each axis separately
if (sim.CanMoveTo(newX, mob.Y))
if (sim.CanActorMoveTo(newX, mob.Y))
{
mob.X = newX;
}
@@ -703,7 +703,7 @@ public static class MobAI
mob.StuckTime += 0.05f;
}
if (sim.CanMoveTo(mob.X, newY))
if (sim.CanActorMoveTo(mob.X, newY))
{
mob.Y = newY;
}
@@ -736,12 +736,12 @@ public static class MobAI
float newX = mob.X + moveX;
float newY = mob.Y + moveY;
if (sim.CanMoveTo(newX, mob.Y))
if (sim.CanActorMoveTo(newX, mob.Y))
{
mob.X = newX;
}
if (sim.CanMoveTo(mob.X, newY))
if (sim.CanActorMoveTo(mob.X, newY))
{
mob.Y = newY;
}
@@ -754,7 +754,7 @@ public static class MobAI
foreach (float ox in offsets)
{
if (sim.CanMoveTo(mob.X + ox, mob.Y))
if (sim.CanActorMoveTo(mob.X + ox, mob.Y))
{
mob.X += ox * 0.5f;
return;
@@ -763,7 +763,7 @@ public static class MobAI
foreach (float oy in offsets)
{
if (sim.CanMoveTo(mob.X, mob.Y + oy))
if (sim.CanActorMoveTo(mob.X, mob.Y + oy))
{
mob.Y += oy * 0.5f;
return;
@@ -819,7 +819,7 @@ public static class MobAI
float spawnY = mob.Y + (float)Math.Sin(angle) * summonDistance;
// Make sure spawn position is walkable
if (!sim.CanMoveTo(spawnX, spawnY))
if (!sim.CanActorMoveTo(spawnX, spawnY))
{
// Try closer
spawnX = mob.X + (float)Math.Cos(angle) * (summonDistance * 0.5f);
+4
View File
@@ -10,6 +10,10 @@ public class PortalInstance
public float Y { get; set; }
public PortalType Type { get; set; }
public bool IsActive { get; set; } = true;
public bool TriggerOnCollision { get; set; } = false;
public float TriggerRadius { get; set; } = 18f;
public float? DestinationX { get; set; }
public float? DestinationY { get; set; }
}
public enum PortalType
+29
View File
@@ -114,3 +114,32 @@
- `object_remove`: `{ id }`
- `npc_upsert`: `{ id, x, y, npcDefinitionId, npcName, rotation, metadataJson }`
- `npc_remove`: `{ id }`
## Dungeon Portals and Ledge-Safe Movement
- Movement collision now uses entity radius checks against tile walkability.
- Prevents edge-clipping / hanging off non-walkable ledges while moving.
- Dungeon supports collision-triggered teleport portals with server-authoritative destination.
### DUNGEON_STATE portal payload additions
- `portals[]` now also includes:
- `triggerOnCollision` (bool)
- `triggerRadius` (pixels)
- `destinationX`, `destinationY` (world-space pixels, nullable)
### DUNGEON_STATE placed object payload additions
- `placedObjects[]` now also includes:
- `triggeredByWalk`
- `interactionType`
- `metadataJson`
### Template portal metadata convention
- Room template object placements can define portal destination via `OverridesJson`:
- Pixel destination:
- `{ "targetX": 1024, "targetY": 640 }`
- Tile destination:
- `{ "targetTileX": 32, "targetTileY": 20, "useTileCoords": true }`
- VNext maps object templates of type `Portal` into runtime collision portals when destination metadata is present.