Working on the world.

This commit is contained in:
dingo
2026-02-18 07:08:49 -05:00
parent 7b5b2b91f0
commit 0c9c2de0ab
5 changed files with 472 additions and 21 deletions
+133 -5
View File
@@ -18,6 +18,7 @@ public sealed partial class WorldHandler : IClientMessageHandler
{
private const int TileSize = 32;
private const float TickDeltaSeconds = 0.1f; // 10Hz
private const float RespawnInvulnerabilitySeconds = 3.0f;
private static readonly TimeSpan NeutralInputGrace = TimeSpan.FromMilliseconds(180);
private static readonly TimeSpan DirectionalPriorityGrace = TimeSpan.FromMilliseconds(450);
@@ -28,6 +29,7 @@ public sealed partial class WorldHandler : IClientMessageHandler
private readonly WorldMovementService _movement;
private readonly WorldBroadcastService _broadcast;
private readonly WorldEditDeltaHub _deltaHub;
private readonly LootService _lootService;
private readonly ConcurrentDictionary<Guid, WorldSessionState> _players = new();
private readonly ConcurrentDictionary<ulong, long> _portalCooldownByCharacter = new();
@@ -36,6 +38,9 @@ public sealed partial class WorldHandler : IClientMessageHandler
// Zone simulations (keyed by "{regionId}:{zoneX}:{zoneY}:{zoneZ}")
private readonly ConcurrentDictionary<string, WorldZoneSimulation> _activeZones = new();
// PvP flag cache per zone (keyed by zone key)
private readonly ConcurrentDictionary<string, bool> _zonePvpFlags = new();
// Mob/NPC definition caches (loaded once at init)
private Dictionary<int, DungeonMobDefinition> _mobDefinitions = new();
private Dictionary<int, DungeonNpcDefinition> _npcDefinitions = new();
@@ -52,7 +57,8 @@ public sealed partial class WorldHandler : IClientMessageHandler
WorldChunkCache cache,
WorldMovementService movement,
WorldBroadcastService broadcast,
WorldEditDeltaHub deltaHub)
WorldEditDeltaHub deltaHub,
LootService lootService)
{
_log = log;
_sessions = sessions;
@@ -61,6 +67,7 @@ public sealed partial class WorldHandler : IClientMessageHandler
_movement = movement;
_broadcast = broadcast;
_deltaHub = deltaHub;
_lootService = lootService;
var debugInputEnv = Environment.GetEnvironmentVariable("WORLD_INPUT_DEBUG");
_debugInput = !string.IsNullOrWhiteSpace(debugInputEnv) &&
@@ -75,6 +82,7 @@ public sealed partial class WorldHandler : IClientMessageHandler
// World combat
OpCodes.WORLD_ATTACK,
OpCodes.WORLD_MOB_LOOT_REQUEST,
OpCodes.WORLD_RESPAWN_REQUEST,
// World NPC
OpCodes.WORLD_NPC_INTERACT,
OpCodes.WORLD_NPC_DIALOG_SELECT,
@@ -165,6 +173,9 @@ public sealed partial class WorldHandler : IClientMessageHandler
case OpCodes.WORLD_MOB_LOOT_REQUEST:
await HandleWorldMobLootAsync(connection, session, payload, ct);
break;
case OpCodes.WORLD_RESPAWN_REQUEST:
await HandleWorldRespawnAsync(connection, session, ct);
break;
// NPC
case OpCodes.WORLD_NPC_INTERACT:
await HandleWorldNpcInteract(connection, session, payload, ct);
@@ -454,11 +465,23 @@ public sealed partial class WorldHandler : IClientMessageHandler
.ToArray();
}
// Check PvP flag for current zone
var isPvp = false;
if (zoneSim != null)
{
isPvp = zoneSim.IsPvpEnabled;
}
else
{
var pvpKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
_zonePvpFlags.TryGetValue(pvpKey, out isPvp);
}
await _broadcast.SendAsync(s.Connection, OpCodes.WORLD_STATE, new
{
tick,
ackSeq = s.Seq,
self = new { x = s.X, y = s.Y, velocityX = s.VelX, velocityY = s.VelY, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY },
self = new { x = s.X, y = s.Y, velocityX = s.VelX, velocityY = s.VelY, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, zoneZ = s.ZoneZ, chunkX = s.ChunkX, chunkY = s.ChunkY, isPvp },
players = VisiblePlayers(s).Select(p => new { id = p.CharacterId, name = p.Name, x = p.X, y = p.Y, facing = p.Facing, speed = p.Speed, isMoving = p.IsMoving, regionId = p.RegionId, zoneX = p.ZoneX, zoneY = p.ZoneY, chunkX = p.ChunkX, chunkY = p.ChunkY }),
mobs = nearbyMobs,
npcs = nearbyNpcs,
@@ -553,14 +576,101 @@ public sealed partial class WorldHandler : IClientMessageHandler
if (!zoneSim.Players.ContainsKey(s.CharacterId))
{
var combatState = new WorldPlayerCombatState(s);
// Initialize with basic stats (character stats would come from DB/gear)
// For now use defaults — Phase 4 will flesh out stat loading from gear
await InitializePlayerCombatStateAsync(combatState, s.CharacterId, ct);
zoneSim.AddPlayer(combatState);
}
}
}
/// <summary>
/// Load real character stats + gear bonuses from DB to initialize player combat state.
/// </summary>
private async Task InitializePlayerCombatStateAsync(WorldPlayerCombatState combatState, ulong characterId, CancellationToken ct)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var character = await db.DungeonCharacters
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == characterId, ct);
if (character == null)
{
// Fallback to defaults
combatState.InitializeFromCharacter(
strength: 10, intelligence: 10, endurance: 10, dexterity: 10,
armor: 0, maxHealth: 100, weaponDamageTypeKey: "physical",
resistances: new Dictionary<string, float>());
zoneSim.AddPlayer(combatState);
return;
}
// Load equipped items with their definitions and crafted bonuses
var equippedItems = await db.DungeonCharacterItems
.AsNoTracking()
.Include(i => i.ItemDefinition)
.Include(i => i.CraftedItem)
.Where(i => i.CharacterId == characterId && i.IsEquipped)
.ToListAsync(ct);
// Sum gear stat bonuses
int gearStr = 0, gearInt = 0, gearEnd = 0, gearDex = 0, gearHealth = 0;
int gearArmor = 0;
string weaponDamageType = "physical";
var equippedDefs = new List<DungeonItemDefinition>();
foreach (var item in equippedItems)
{
if (item.ItemDefinition == null) continue;
equippedDefs.Add(item.ItemDefinition);
var (str, intel, wis, end, dex, health, mana) = item.GetTotalStats(item.ItemDefinition);
gearStr += str;
gearInt += intel;
gearEnd += end;
gearDex += dex;
gearHealth += health;
gearArmor += item.ItemDefinition.Armor;
// Check if this is the weapon (equipped weapon slot)
if (item.EquipSlot == DataServer.Data.Enums.DungeonEquipmentSlot.MainHand &&
!string.IsNullOrEmpty(item.ItemDefinition.DamageTypeKey))
{
weaponDamageType = item.ItemDefinition.DamageTypeKey;
}
}
// Total stats = base character + gear
int totalStr = character.Strength + gearStr;
int totalInt = character.Intelligence + gearInt;
int totalEnd = character.Endurance + gearEnd;
int totalDex = character.Dexterity + gearDex;
// Max health from Endurance formula + gear bonus health
int maxHealth = (50 + (totalEnd * 10)) + gearHealth;
// Merge innate + gear resistances
var resistances = CombatCalculator.CalculatePlayerTotalResistances(
character.Resistances, equippedDefs);
combatState.InitializeFromCharacter(
strength: totalStr,
intelligence: totalInt,
endurance: totalEnd,
dexterity: totalDex,
armor: gearArmor,
maxHealth: maxHealth,
weaponDamageTypeKey: weaponDamageType,
resistances: resistances);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed to load combat stats for character {CharacterId}, using defaults", characterId);
combatState.InitializeFromCharacter(
strength: 10, intelligence: 10, endurance: 10, dexterity: 10,
armor: 0, maxHealth: 100, weaponDamageTypeKey: "physical",
resistances: new Dictionary<string, float>());
}
}
@@ -578,6 +688,24 @@ public sealed partial class WorldHandler : IClientMessageHandler
var zoneSim = new WorldZoneSimulation(zoneKey, regionId, zoneX, zoneY, zoneZ, _cache);
zoneSim.SetRegion(region);
// Load PvP flag from DB
try
{
using var pvpScope = _scopeFactory.CreateScope();
var pvpDb = pvpScope.ServiceProvider.GetRequiredService<GameDbContext>();
var zone = await pvpDb.WorldZones.AsNoTracking()
.FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == zoneZ, ct);
if (zone != null)
{
zoneSim.IsPvpEnabled = zone.IsPvpEnabled;
_zonePvpFlags[zoneKey] = zone.IsPvpEnabled;
}
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed to load PvP flag for zone {ZoneKey}", zoneKey);
}
// Collect mob and NPC spawns from all chunks in this zone
var mobSpawns = new List<(WorldChunkMobSpawnData, int, int)>();
var npcSpawns = new List<(NpcInstance, int, int)>();