using System.Data; using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class MapMonsterListConfigSummary { public int SpawnRecordCount { get; init; } public int ExpandedMobRecordCount { get; init; } public int DistinctMapCount { get; init; } public int DistinctMonsterTypeCount { get; init; } public int DuplicateSpawnKeyCount { get; init; } public int MissingConfigMapCount { get; init; } public int MissingMonsterBaseInfoCount { get; init; } public int RewardTemplateTypeCount { get; init; } public int MissingRewardTemplateTypeCount { get; init; } public int CurrentConfigMobCount { get; init; } public int CurrentMobLocationCount { get; init; } public int CurrentMobDropRewardCount { get; init; } public int CurrentMobExpRewardCount { get; init; } public int CurrentItemDropRewardCount { get; init; } public int CurrentBitsDropRewardCount { get; init; } public int DeletedConfigMobCount { get; init; } public int DeletedMobLocationCount { get; init; } public int DeletedMobDropRewardCount { get; init; } public int DeletedMobExpRewardCount { get; init; } public int DeletedItemDropRewardCount { get; init; } public int DeletedBitsDropRewardCount { get; init; } public int InsertedConfigMobCount { get; init; } public int InsertedMobLocationCount { get; init; } public int InsertedMobDropRewardCount { get; init; } public int InsertedMobExpRewardCount { get; init; } public int InsertedItemDropRewardCount { get; init; } public int InsertedBitsDropRewardCount { get; init; } } public static class MapMonsterListConfigImporter { public static MapMonsterListConfigSummary ValidateXml(string xmlPath) { List groups = LoadGroups(xmlPath); return new MapMonsterListConfigSummary { SpawnRecordCount = groups.Count, ExpandedMobRecordCount = groups.Sum(x => x.Count), DistinctMapCount = groups.Select(x => x.MapId).Distinct().Count(), DistinctMonsterTypeCount = groups.Select(x => x.MonsterType).Distinct().Count(), DuplicateSpawnKeyCount = CountDuplicateSpawnKeys(groups) }; } public static MapMonsterListConfigSummary AssessDatabase(string connectionString, string xmlPath) { List groups = LoadGroups(xmlPath); using SqlConnection connection = new(connectionString); connection.Open(); HashSet configMapIds = ReadIntSet(connection, "SELECT [MapId] FROM [Config].[Map];"); HashSet monsterTypes = ReadIntSet(connection, "SELECT [Type] FROM [Asset].[MonsterBaseInfo];"); HashSet rewardTemplateTypes = ReadIntSet(connection, "SELECT DISTINCT [Type] FROM [Config].[Mob];"); List xmlTypes = groups.Select(x => x.MonsterType).Distinct().ToList(); return new MapMonsterListConfigSummary { SpawnRecordCount = groups.Count, ExpandedMobRecordCount = groups.Sum(x => x.Count), DistinctMapCount = groups.Select(x => x.MapId).Distinct().Count(), DistinctMonsterTypeCount = xmlTypes.Count, DuplicateSpawnKeyCount = CountDuplicateSpawnKeys(groups), MissingConfigMapCount = groups.Select(x => x.MapId).Distinct().Count(x => !configMapIds.Contains(x)), MissingMonsterBaseInfoCount = xmlTypes.Count(x => !monsterTypes.Contains(x)), RewardTemplateTypeCount = xmlTypes.Count(x => rewardTemplateTypes.Contains(x)), MissingRewardTemplateTypeCount = xmlTypes.Count(x => !rewardTemplateTypes.Contains(x)), CurrentConfigMobCount = CountTable(connection, "[Config].[Mob]"), CurrentMobLocationCount = CountTable(connection, "[Config].[MobLocation]"), CurrentMobDropRewardCount = CountTable(connection, "[Config].[MobDropReward]"), CurrentMobExpRewardCount = CountTable(connection, "[Config].[MobExpReward]"), CurrentItemDropRewardCount = CountTable(connection, "[Config].[ItemDropReward]"), CurrentBitsDropRewardCount = CountTable(connection, "[Config].[BitsDropReward]") }; } public static MapMonsterListConfigSummary ImportReplace(string connectionString, string xmlPath) { List groups = LoadGroups(xmlPath); using SqlConnection connection = new(connectionString); connection.Open(); Dictionary mapConfigIds = LoadMapConfigIds(connection); Dictionary monsterBaseInfo = LoadMonsterBaseInfo(connection); Dictionary rewardTemplates = LoadRewardTemplates(connection); List missingMaps = groups.Select(x => x.MapId).Distinct().Where(x => !mapConfigIds.ContainsKey(x)).ToList(); if (missingMaps.Count > 0) { throw new InvalidOperationException($"MapMonsterList.xml references {missingMaps.Count} maps missing from Config.Map. Import MapList first. First missing map: {missingMaps[0]}."); } List missingMonsters = groups.Select(x => x.MonsterType).Distinct().Where(x => !monsterBaseInfo.ContainsKey(x)).ToList(); if (missingMonsters.Count > 0) { throw new InvalidOperationException($"MapMonsterList.xml references {missingMonsters.Count} monster types missing from Asset.MonsterBaseInfo. Import Monster first. First missing monster type: {missingMonsters[0]}."); } List mobs = ExpandGroups(groups, mapConfigIds, monsterBaseInfo); int missingTemplateTypeCount = groups.Select(x => x.MonsterType).Distinct().Count(x => !rewardTemplates.ContainsKey(x)); using SqlTransaction transaction = connection.BeginTransaction(); try { MapMonsterListConfigSummary before = CountCurrentRows(connection, transaction); DeleteExistingRows(connection, transaction); InsertMobs(connection, transaction, mobs); InsertLocations(connection, transaction, mobs); InsertDropRewards(connection, transaction, mobs, rewardTemplates); InsertExpRewards(connection, transaction, mobs, rewardTemplates); int insertedItemDropRows = InsertItemDropRewards(connection, transaction, mobs, rewardTemplates); int insertedBitsDropRows = InsertBitsDropRewards(connection, transaction, mobs, rewardTemplates); transaction.Commit(); return new MapMonsterListConfigSummary { SpawnRecordCount = groups.Count, ExpandedMobRecordCount = mobs.Count, DistinctMapCount = groups.Select(x => x.MapId).Distinct().Count(), DistinctMonsterTypeCount = groups.Select(x => x.MonsterType).Distinct().Count(), DuplicateSpawnKeyCount = CountDuplicateSpawnKeys(groups), RewardTemplateTypeCount = groups.Select(x => x.MonsterType).Distinct().Count(x => rewardTemplates.ContainsKey(x)), MissingRewardTemplateTypeCount = missingTemplateTypeCount, DeletedConfigMobCount = before.CurrentConfigMobCount, DeletedMobLocationCount = before.CurrentMobLocationCount, DeletedMobDropRewardCount = before.CurrentMobDropRewardCount, DeletedMobExpRewardCount = before.CurrentMobExpRewardCount, DeletedItemDropRewardCount = before.CurrentItemDropRewardCount, DeletedBitsDropRewardCount = before.CurrentBitsDropRewardCount, InsertedConfigMobCount = mobs.Count, InsertedMobLocationCount = mobs.Count, InsertedMobDropRewardCount = mobs.Count, InsertedMobExpRewardCount = mobs.Count, InsertedItemDropRewardCount = insertedItemDropRows, InsertedBitsDropRewardCount = insertedBitsDropRows }; } catch { TryDisableIdentityInsert(connection, transaction); transaction.Rollback(); throw; } } private static List LoadGroups(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("MapMonsterList.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "MapMonsterList") { throw new InvalidOperationException("MapMonsterList.xml root node must be ."); } XElement? fileGroupsElement = root.Element("FileGroups"); if (fileGroupsElement == null) { throw new InvalidOperationException("MapMonsterList.xml is missing the node."); } List groups = new(); int rowIndex = 0; foreach (XElement monsterElement in fileGroupsElement .Elements("FileGroup") .Elements("MapGroups") .Elements("MapGroup") .Elements("Monsters") .Elements("Monster")) { rowIndex++; string rowContext = $"MapMonsterList spawn row {rowIndex}"; int mapId = ReadRequiredInt(monsterElement, "s_dwMapID", rowContext); int monsterType = ReadRequiredInt(monsterElement, "s_dwMonsterTableID", rowContext); int x = ReadRequiredInt(monsterElement, "s_nCenterX", rowContext); int y = ReadRequiredInt(monsterElement, "s_nCenterY", rowContext); int radius = ReadRequiredInt(monsterElement, "s_nRadius", rowContext); int count = ReadRequiredInt(monsterElement, "s_nCount", rowContext); int respawnSeconds = ReadRequiredInt(monsterElement, "s_nResponTime", rowContext); int moveType = ReadRequiredInt(monsterElement, "s_nMoveType", rowContext); _ = ReadRequiredInt(monsterElement, "s_nKillgen_MonFTID", rowContext); _ = ReadRequiredInt(monsterElement, "s_nKillgen_Count", rowContext); _ = ReadRequiredInt(monsterElement, "s_nKillgen_ViewCnt", rowContext); _ = ReadRequiredInt(monsterElement, "s_bInsRespon", rowContext); if (mapId is < short.MinValue or > short.MaxValue) { throw new InvalidOperationException($"{rowContext} has out-of-range smallint map value in 's_dwMapID': '{mapId}'."); } if (monsterType <= 0) { throw new InvalidOperationException($"{rowContext} has invalid monster type in 's_dwMonsterTableID': '{monsterType}'."); } if (radius < 0 || count < 0 || respawnSeconds < 0) { throw new InvalidOperationException($"{rowContext} has negative radius/count/respawn values."); } groups.Add(new MapMonsterSpawnGroup { MapId = mapId, MonsterType = monsterType, X = x, Y = y, Radius = radius, Count = count, RespawnSeconds = respawnSeconds, MoveType = moveType }); } if (groups.Count == 0) { throw new InvalidOperationException("MapMonsterList.xml does not contain any monster spawn rows."); } return groups; } private static List ExpandGroups( IReadOnlyList groups, IReadOnlyDictionary mapConfigIds, IReadOnlyDictionary monsterBaseInfo) { List records = new(); long id = 1; foreach (MapMonsterSpawnGroup group in groups) { MonsterBaseInfoRecord monster = monsterBaseInfo[group.MonsterType]; for (int index = 0; index < group.Count; index++) { records.Add(new MapMonsterMobRecord { Id = id++, MapId = group.MapId, GameMapConfigId = mapConfigIds[group.MapId], X = group.X, Y = group.Y, RespawnSeconds = group.RespawnSeconds, Monster = monster }); } } return records; } private static Dictionary LoadMapConfigIds(SqlConnection connection) { using SqlCommand command = new("SELECT [Id], [MapId] FROM [Config].[Map];", connection); using SqlDataReader reader = command.ExecuteReader(); Dictionary maps = new(); while (reader.Read()) { maps[Convert.ToInt32(reader["MapId"], CultureInfo.InvariantCulture)] = Convert.ToInt64(reader["Id"], CultureInfo.InvariantCulture); } return maps; } private static Dictionary LoadMonsterBaseInfo(SqlConnection connection) { using SqlCommand command = new(@" SELECT [Type], [Model], [Name], [Level], [ViewRange], [HuntRange], [ReactionType], [Attribute], [Element], [Family1], [Family2], [Family3], [ASValue], [ARValue], [ATValue], [BLValue], [CTValue], [DEValue], [DSValue], [EVValue], [HPValue], [HTValue], [MSValue], [WSValue], [Class] FROM [Asset].[MonsterBaseInfo];", connection); using SqlDataReader reader = command.ExecuteReader(); Dictionary records = new(); while (reader.Read()) { int type = Convert.ToInt32(reader["Type"], CultureInfo.InvariantCulture); records[type] = new MonsterBaseInfoRecord { Type = type, Model = Convert.ToInt32(reader["Model"], CultureInfo.InvariantCulture), Name = Convert.ToString(reader["Name"], CultureInfo.InvariantCulture) ?? string.Empty, Level = Convert.ToByte(reader["Level"], CultureInfo.InvariantCulture), ViewRange = Convert.ToInt32(reader["ViewRange"], CultureInfo.InvariantCulture), HuntRange = Convert.ToInt32(reader["HuntRange"], CultureInfo.InvariantCulture), ReactionType = Convert.ToInt32(reader["ReactionType"], CultureInfo.InvariantCulture), Attribute = Convert.ToInt32(reader["Attribute"], CultureInfo.InvariantCulture), Element = Convert.ToInt32(reader["Element"], CultureInfo.InvariantCulture), Family1 = Convert.ToInt32(reader["Family1"], CultureInfo.InvariantCulture), Family2 = Convert.ToInt32(reader["Family2"], CultureInfo.InvariantCulture), Family3 = Convert.ToInt32(reader["Family3"], CultureInfo.InvariantCulture), ASValue = Convert.ToInt32(reader["ASValue"], CultureInfo.InvariantCulture), ARValue = Convert.ToInt32(reader["ARValue"], CultureInfo.InvariantCulture), ATValue = Convert.ToInt32(reader["ATValue"], CultureInfo.InvariantCulture), BLValue = Convert.ToInt32(reader["BLValue"], CultureInfo.InvariantCulture), CTValue = Convert.ToInt32(reader["CTValue"], CultureInfo.InvariantCulture), DEValue = Convert.ToInt32(reader["DEValue"], CultureInfo.InvariantCulture), DSValue = Convert.ToInt32(reader["DSValue"], CultureInfo.InvariantCulture), EVValue = Convert.ToInt32(reader["EVValue"], CultureInfo.InvariantCulture), HPValue = Convert.ToInt32(reader["HPValue"], CultureInfo.InvariantCulture), HTValue = Convert.ToInt32(reader["HTValue"], CultureInfo.InvariantCulture), MSValue = Convert.ToInt32(reader["MSValue"], CultureInfo.InvariantCulture), WSValue = Convert.ToInt32(reader["WSValue"], CultureInfo.InvariantCulture), Class = Convert.ToInt32(reader["Class"], CultureInfo.InvariantCulture) }; } return records; } private static Dictionary LoadRewardTemplates(SqlConnection connection) { Dictionary templates = new(); using (SqlCommand command = new(@" WITH TemplateMob AS ( SELECT [Type], MIN([Id]) AS [MobId] FROM [Config].[Mob] GROUP BY [Type] ) SELECT t.[Type], dr.[MinAmount], dr.[MaxAmount], er.[TamerExperience], er.[DigimonExperience], er.[NatureExperience], er.[ElementExperience], er.[SkillExperience] FROM TemplateMob t LEFT JOIN [Config].[MobDropReward] dr ON dr.[MobId] = t.[MobId] LEFT JOIN [Config].[MobExpReward] er ON er.[MobId] = t.[MobId];", connection)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int type = Convert.ToInt32(reader["Type"], CultureInfo.InvariantCulture); templates[type] = new RewardTemplate { DropMinAmount = ReadByteOrDefault(reader, "MinAmount"), DropMaxAmount = ReadByteOrDefault(reader, "MaxAmount"), TamerExperience = ReadLongOrDefault(reader, "TamerExperience"), DigimonExperience = ReadLongOrDefault(reader, "DigimonExperience"), NatureExperience = ReadShortOrDefault(reader, "NatureExperience"), ElementExperience = ReadShortOrDefault(reader, "ElementExperience"), SkillExperience = ReadShortOrDefault(reader, "SkillExperience") }; } } using (SqlCommand command = new(@" WITH TemplateMob AS ( SELECT [Type], MIN([Id]) AS [MobId] FROM [Config].[Mob] GROUP BY [Type] ) SELECT t.[Type], i.[ItemId], i.[MinAmount], i.[MaxAmount], i.[Chance], i.[Rank] FROM TemplateMob t JOIN [Config].[MobDropReward] dr ON dr.[MobId] = t.[MobId] JOIN [Config].[ItemDropReward] i ON i.[DropRewardId] = dr.[Id] ORDER BY t.[Type], i.[Id];", connection)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int type = Convert.ToInt32(reader["Type"], CultureInfo.InvariantCulture); if (templates.TryGetValue(type, out RewardTemplate? template)) { template.ItemDrops.Add(new ItemDropTemplate { ItemId = Convert.ToInt32(reader["ItemId"], CultureInfo.InvariantCulture), MinAmount = Convert.ToInt32(reader["MinAmount"], CultureInfo.InvariantCulture), MaxAmount = Convert.ToInt32(reader["MaxAmount"], CultureInfo.InvariantCulture), Chance = Convert.ToDecimal(reader["Chance"], CultureInfo.InvariantCulture), Rank = Convert.ToInt32(reader["Rank"], CultureInfo.InvariantCulture) }); } } } using (SqlCommand command = new(@" WITH TemplateMob AS ( SELECT [Type], MIN([Id]) AS [MobId] FROM [Config].[Mob] GROUP BY [Type] ) SELECT t.[Type], b.[MinAmount], b.[MaxAmount], b.[Chance] FROM TemplateMob t JOIN [Config].[MobDropReward] dr ON dr.[MobId] = t.[MobId] JOIN [Config].[BitsDropReward] b ON b.[DropRewardId] = dr.[Id] ORDER BY t.[Type], b.[Id];", connection)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int type = Convert.ToInt32(reader["Type"], CultureInfo.InvariantCulture); if (templates.TryGetValue(type, out RewardTemplate? template) && template.BitsDrop == null) { template.BitsDrop = new BitsDropTemplate { MinAmount = Convert.ToInt32(reader["MinAmount"], CultureInfo.InvariantCulture), MaxAmount = Convert.ToInt32(reader["MaxAmount"], CultureInfo.InvariantCulture), Chance = Convert.ToDecimal(reader["Chance"], CultureInfo.InvariantCulture) }; } } } return templates; } private static void DeleteExistingRows(SqlConnection connection, SqlTransaction transaction) { ExecuteNonQuery(connection, transaction, "DELETE FROM [Config].[ItemDropReward];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Config].[BitsDropReward];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Config].[MobExpReward];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Config].[MobLocation];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Config].[MobDropReward];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Config].[Mob];"); } private static void InsertMobs(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[Mob] ON;"); using SqlCommand command = new(@" INSERT INTO [Config].[Mob] ([Id], [Type], [Model], [Name], [Level], [ViewRange], [HuntRange], [ReactionType], [Attribute], [Element], [Family1], [Family2], [Family3], [RespawnInterval], [GameMapConfigId], [ASValue], [ARValue], [ATValue], [BLValue], [CTValue], [DEValue], [DSValue], [EVValue], [HPValue], [HTValue], [MSValue], [WSValue], [Class], [Coliseum], [ColiseumMobType], [Round], [WeekDay], [DeathTime], [ResurrectionTime], [MobObjectId]) VALUES (@Id, @Type, @Model, @Name, @Level, @ViewRange, @HuntRange, @ReactionType, @Attribute, @Element, @Family1, @Family2, @Family3, @RespawnInterval, @GameMapConfigId, @ASValue, @ARValue, @ATValue, @BLValue, @CTValue, @DEValue, @DSValue, @EVValue, @HPValue, @HTValue, @MSValue, @WSValue, @Class, @Coliseum, @ColiseumMobType, @Round, @WeekDay, @DeathTime, @ResurrectionTime, @MobObjectId);", connection, transaction); AddMobParameters(command); foreach (MapMonsterMobRecord record in records) { BindMobParameters(command, record); command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[Mob] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Config].[Mob]', RESEED, {records.Count});"); } private static void InsertLocations(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[MobLocation] ON;"); using SqlCommand command = new(@" INSERT INTO [Config].[MobLocation] ([Id], [MobConfigId], [MapId], [X], [Y], [Z]) VALUES (@Id, @MobConfigId, @MapId, @X, @Y, @Z);", connection, transaction); AddParameter(command, "@Id", SqlDbType.BigInt); AddParameter(command, "@MobConfigId", SqlDbType.BigInt); AddParameter(command, "@MapId", SqlDbType.SmallInt); AddParameter(command, "@X", SqlDbType.Int); AddParameter(command, "@Y", SqlDbType.Int); SqlParameter zParameter = command.Parameters.Add("@Z", SqlDbType.Decimal); zParameter.Precision = 9; zParameter.Scale = 2; foreach (MapMonsterMobRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@MobConfigId"].Value = record.Id; command.Parameters["@MapId"].Value = (short)record.MapId; command.Parameters["@X"].Value = record.X; command.Parameters["@Y"].Value = record.Y; command.Parameters["@Z"].Value = 0m; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[MobLocation] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Config].[MobLocation]', RESEED, {records.Count});"); } private static void InsertDropRewards( SqlConnection connection, SqlTransaction transaction, IReadOnlyList records, IReadOnlyDictionary rewardTemplates) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[MobDropReward] ON;"); using SqlCommand command = new(@" INSERT INTO [Config].[MobDropReward] ([Id], [MinAmount], [MaxAmount], [MobId]) VALUES (@Id, @MinAmount, @MaxAmount, @MobId);", connection, transaction); AddParameter(command, "@Id", SqlDbType.BigInt); AddParameter(command, "@MinAmount", SqlDbType.TinyInt); AddParameter(command, "@MaxAmount", SqlDbType.TinyInt); AddParameter(command, "@MobId", SqlDbType.BigInt); foreach (MapMonsterMobRecord record in records) { RewardTemplate template = GetTemplateOrDefault(rewardTemplates, record.Monster.Type); command.Parameters["@Id"].Value = record.Id; command.Parameters["@MinAmount"].Value = template.DropMinAmount; command.Parameters["@MaxAmount"].Value = template.DropMaxAmount; command.Parameters["@MobId"].Value = record.Id; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[MobDropReward] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Config].[MobDropReward]', RESEED, {records.Count});"); } private static void InsertExpRewards( SqlConnection connection, SqlTransaction transaction, IReadOnlyList records, IReadOnlyDictionary rewardTemplates) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[MobExpReward] ON;"); using SqlCommand command = new(@" INSERT INTO [Config].[MobExpReward] ([Id], [TamerExperience], [DigimonExperience], [NatureExperience], [ElementExperience], [SkillExperience], [MobId]) VALUES (@Id, @TamerExperience, @DigimonExperience, @NatureExperience, @ElementExperience, @SkillExperience, @MobId);", connection, transaction); AddParameter(command, "@Id", SqlDbType.BigInt); AddParameter(command, "@TamerExperience", SqlDbType.BigInt); AddParameter(command, "@DigimonExperience", SqlDbType.BigInt); AddParameter(command, "@NatureExperience", SqlDbType.SmallInt); AddParameter(command, "@ElementExperience", SqlDbType.SmallInt); AddParameter(command, "@SkillExperience", SqlDbType.SmallInt); AddParameter(command, "@MobId", SqlDbType.BigInt); foreach (MapMonsterMobRecord record in records) { RewardTemplate template = GetTemplateOrDefault(rewardTemplates, record.Monster.Type); command.Parameters["@Id"].Value = record.Id; command.Parameters["@TamerExperience"].Value = template.TamerExperience; command.Parameters["@DigimonExperience"].Value = template.DigimonExperience; command.Parameters["@NatureExperience"].Value = template.NatureExperience; command.Parameters["@ElementExperience"].Value = template.ElementExperience; command.Parameters["@SkillExperience"].Value = template.SkillExperience; command.Parameters["@MobId"].Value = record.Id; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[MobExpReward] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Config].[MobExpReward]', RESEED, {records.Count});"); } private static int InsertItemDropRewards( SqlConnection connection, SqlTransaction transaction, IReadOnlyList records, IReadOnlyDictionary rewardTemplates) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[ItemDropReward] ON;"); using SqlCommand command = new(@" INSERT INTO [Config].[ItemDropReward] ([Id], [ItemId], [MinAmount], [MaxAmount], [Chance], [DropRewardId], [Rank]) VALUES (@Id, @ItemId, @MinAmount, @MaxAmount, @Chance, @DropRewardId, @Rank);", connection, transaction); AddParameter(command, "@Id", SqlDbType.BigInt); AddParameter(command, "@ItemId", SqlDbType.Int); AddParameter(command, "@MinAmount", SqlDbType.Int); AddParameter(command, "@MaxAmount", SqlDbType.Int); SqlParameter chanceParameter = command.Parameters.Add("@Chance", SqlDbType.Decimal); chanceParameter.Precision = 9; chanceParameter.Scale = 2; AddParameter(command, "@DropRewardId", SqlDbType.BigInt); AddParameter(command, "@Rank", SqlDbType.Int); long id = 1; foreach (MapMonsterMobRecord record in records) { RewardTemplate template = GetTemplateOrDefault(rewardTemplates, record.Monster.Type); foreach (ItemDropTemplate itemDrop in template.ItemDrops) { command.Parameters["@Id"].Value = id++; command.Parameters["@ItemId"].Value = itemDrop.ItemId; command.Parameters["@MinAmount"].Value = itemDrop.MinAmount; command.Parameters["@MaxAmount"].Value = itemDrop.MaxAmount; command.Parameters["@Chance"].Value = itemDrop.Chance; command.Parameters["@DropRewardId"].Value = record.Id; command.Parameters["@Rank"].Value = itemDrop.Rank; command.ExecuteNonQuery(); } } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[ItemDropReward] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Config].[ItemDropReward]', RESEED, {id - 1});"); return Convert.ToInt32(id - 1, CultureInfo.InvariantCulture); } private static int InsertBitsDropRewards( SqlConnection connection, SqlTransaction transaction, IReadOnlyList records, IReadOnlyDictionary rewardTemplates) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[BitsDropReward] ON;"); using SqlCommand command = new(@" INSERT INTO [Config].[BitsDropReward] ([Id], [MinAmount], [MaxAmount], [Chance], [DropRewardId]) VALUES (@Id, @MinAmount, @MaxAmount, @Chance, @DropRewardId);", connection, transaction); AddParameter(command, "@Id", SqlDbType.BigInt); AddParameter(command, "@MinAmount", SqlDbType.Int); AddParameter(command, "@MaxAmount", SqlDbType.Int); SqlParameter chanceParameter = command.Parameters.Add("@Chance", SqlDbType.Decimal); chanceParameter.Precision = 9; chanceParameter.Scale = 2; AddParameter(command, "@DropRewardId", SqlDbType.BigInt); long id = 1; foreach (MapMonsterMobRecord record in records) { RewardTemplate template = GetTemplateOrDefault(rewardTemplates, record.Monster.Type); if (template.BitsDrop == null) { continue; } command.Parameters["@Id"].Value = id++; command.Parameters["@MinAmount"].Value = template.BitsDrop.MinAmount; command.Parameters["@MaxAmount"].Value = template.BitsDrop.MaxAmount; command.Parameters["@Chance"].Value = template.BitsDrop.Chance; command.Parameters["@DropRewardId"].Value = record.Id; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Config].[BitsDropReward] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Config].[BitsDropReward]', RESEED, {id - 1});"); return Convert.ToInt32(id - 1, CultureInfo.InvariantCulture); } private static void AddMobParameters(SqlCommand command) { AddParameter(command, "@Id", SqlDbType.BigInt); AddParameter(command, "@Type", SqlDbType.Int); AddParameter(command, "@Model", SqlDbType.Int); command.Parameters.Add("@Name", SqlDbType.VarChar, 50); AddParameter(command, "@Level", SqlDbType.TinyInt); AddParameter(command, "@ViewRange", SqlDbType.Int); AddParameter(command, "@HuntRange", SqlDbType.Int); AddParameter(command, "@ReactionType", SqlDbType.Int); AddParameter(command, "@Attribute", SqlDbType.Int); AddParameter(command, "@Element", SqlDbType.Int); AddParameter(command, "@Family1", SqlDbType.Int); AddParameter(command, "@Family2", SqlDbType.Int); AddParameter(command, "@Family3", SqlDbType.Int); AddParameter(command, "@RespawnInterval", SqlDbType.Int); AddParameter(command, "@GameMapConfigId", SqlDbType.BigInt); AddParameter(command, "@ASValue", SqlDbType.Int); AddParameter(command, "@ARValue", SqlDbType.Int); AddParameter(command, "@ATValue", SqlDbType.Int); AddParameter(command, "@BLValue", SqlDbType.Int); AddParameter(command, "@CTValue", SqlDbType.Int); AddParameter(command, "@DEValue", SqlDbType.Int); AddParameter(command, "@DSValue", SqlDbType.Int); AddParameter(command, "@EVValue", SqlDbType.Int); AddParameter(command, "@HPValue", SqlDbType.Int); AddParameter(command, "@HTValue", SqlDbType.Int); AddParameter(command, "@MSValue", SqlDbType.Int); AddParameter(command, "@WSValue", SqlDbType.Int); AddParameter(command, "@Class", SqlDbType.Int); AddParameter(command, "@Coliseum", SqlDbType.Bit); AddParameter(command, "@ColiseumMobType", SqlDbType.Int); AddParameter(command, "@Round", SqlDbType.TinyInt); AddParameter(command, "@WeekDay", SqlDbType.Int); AddParameter(command, "@DeathTime", SqlDbType.DateTime); AddParameter(command, "@ResurrectionTime", SqlDbType.DateTime); AddParameter(command, "@MobObjectId", SqlDbType.Int); } private static void BindMobParameters(SqlCommand command, MapMonsterMobRecord record) { MonsterBaseInfoRecord monster = record.Monster; command.Parameters["@Id"].Value = record.Id; command.Parameters["@Type"].Value = monster.Type; command.Parameters["@Model"].Value = monster.Model; command.Parameters["@Name"].Value = monster.Name.Length > 50 ? monster.Name[..50] : monster.Name; command.Parameters["@Level"].Value = monster.Level; command.Parameters["@ViewRange"].Value = monster.ViewRange; command.Parameters["@HuntRange"].Value = monster.HuntRange; command.Parameters["@ReactionType"].Value = monster.ReactionType; command.Parameters["@Attribute"].Value = monster.Attribute; command.Parameters["@Element"].Value = monster.Element; command.Parameters["@Family1"].Value = monster.Family1; command.Parameters["@Family2"].Value = monster.Family2; command.Parameters["@Family3"].Value = monster.Family3; command.Parameters["@RespawnInterval"].Value = record.RespawnSeconds; command.Parameters["@GameMapConfigId"].Value = record.GameMapConfigId; command.Parameters["@ASValue"].Value = monster.ASValue; command.Parameters["@ARValue"].Value = monster.ARValue; command.Parameters["@ATValue"].Value = monster.ATValue; command.Parameters["@BLValue"].Value = monster.BLValue; command.Parameters["@CTValue"].Value = monster.CTValue; command.Parameters["@DEValue"].Value = monster.DEValue; command.Parameters["@DSValue"].Value = monster.DSValue; command.Parameters["@EVValue"].Value = monster.EVValue; command.Parameters["@HPValue"].Value = monster.HPValue; command.Parameters["@HTValue"].Value = monster.HTValue; command.Parameters["@MSValue"].Value = monster.MSValue; command.Parameters["@WSValue"].Value = monster.WSValue; command.Parameters["@Class"].Value = monster.Class; command.Parameters["@Coliseum"].Value = false; command.Parameters["@ColiseumMobType"].Value = 0; command.Parameters["@Round"].Value = 0; command.Parameters["@WeekDay"].Value = 0; command.Parameters["@DeathTime"].Value = DBNull.Value; command.Parameters["@ResurrectionTime"].Value = DBNull.Value; command.Parameters["@MobObjectId"].Value = 0; } private static RewardTemplate GetTemplateOrDefault(IReadOnlyDictionary templates, int monsterType) { return templates.TryGetValue(monsterType, out RewardTemplate? template) ? template : RewardTemplate.Empty; } private static MapMonsterListConfigSummary CountCurrentRows(SqlConnection connection, SqlTransaction transaction) { return new MapMonsterListConfigSummary { CurrentConfigMobCount = CountTable(connection, transaction, "[Config].[Mob]"), CurrentMobLocationCount = CountTable(connection, transaction, "[Config].[MobLocation]"), CurrentMobDropRewardCount = CountTable(connection, transaction, "[Config].[MobDropReward]"), CurrentMobExpRewardCount = CountTable(connection, transaction, "[Config].[MobExpReward]"), CurrentItemDropRewardCount = CountTable(connection, transaction, "[Config].[ItemDropReward]"), CurrentBitsDropRewardCount = CountTable(connection, transaction, "[Config].[BitsDropReward]") }; } private static int CountDuplicateSpawnKeys(IReadOnlyList groups) { return groups .GroupBy(x => new { x.MapId, x.MonsterType, x.X, x.Y, x.Radius, x.Count, x.RespawnSeconds, x.MoveType }) .Where(x => x.Count() > 1) .Sum(x => x.Count() - 1); } private static int ReadRequiredInt(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { throw new InvalidOperationException($"{recordContext} has invalid integer value in '{elementName}': '{element.Value}'."); } return value; } private static HashSet ReadIntSet(SqlConnection connection, string sql) { using SqlCommand command = new(sql, connection); using SqlDataReader reader = command.ExecuteReader(); HashSet values = new(); while (reader.Read()) { values.Add(Convert.ToInt32(reader.GetValue(0), CultureInfo.InvariantCulture)); } return values; } private static byte ReadByteOrDefault(SqlDataReader reader, string column) { return reader[column] == DBNull.Value ? byte.MinValue : Convert.ToByte(reader[column], CultureInfo.InvariantCulture); } private static short ReadShortOrDefault(SqlDataReader reader, string column) { return reader[column] == DBNull.Value ? (short)0 : Convert.ToInt16(reader[column], CultureInfo.InvariantCulture); } private static long ReadLongOrDefault(SqlDataReader reader, string column) { return reader[column] == DBNull.Value ? 0L : Convert.ToInt64(reader[column], CultureInfo.InvariantCulture); } private static int CountTable(SqlConnection connection, string tableName) { using SqlCommand command = new($"SELECT COUNT(*) FROM {tableName};", connection); object? value = command.ExecuteScalar(); return Convert.ToInt32(value, CultureInfo.InvariantCulture); } private static int CountTable(SqlConnection connection, SqlTransaction transaction, string tableName) { using SqlCommand command = new($"SELECT COUNT(*) FROM {tableName};", connection, transaction); object? value = command.ExecuteScalar(); return Convert.ToInt32(value, CultureInfo.InvariantCulture); } private static void ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); command.ExecuteNonQuery(); } private static void AddParameter(SqlCommand command, string name, SqlDbType type) { command.Parameters.Add(name, type); } private static void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction) { foreach (string tableName in new[] { "[Config].[BitsDropReward]", "[Config].[ItemDropReward]", "[Config].[MobExpReward]", "[Config].[MobDropReward]", "[Config].[MobLocation]", "[Config].[Mob]" }) { try { ExecuteNonQuery(connection, transaction, $"SET IDENTITY_INSERT {tableName} OFF;"); } catch { // Best-effort cleanup before rollback. } } } private sealed class MapMonsterSpawnGroup { public int MapId { get; init; } public int MonsterType { get; init; } public int X { get; init; } public int Y { get; init; } public int Radius { get; init; } public int Count { get; init; } public int RespawnSeconds { get; init; } public int MoveType { get; init; } } private sealed class MapMonsterMobRecord { public long Id { get; init; } public int MapId { get; init; } public long GameMapConfigId { get; init; } public int X { get; init; } public int Y { get; init; } public int RespawnSeconds { get; init; } public MonsterBaseInfoRecord Monster { get; init; } = new(); } private sealed class MonsterBaseInfoRecord { public int Type { get; init; } public int Model { get; init; } public string Name { get; init; } = string.Empty; public byte Level { get; init; } public int ViewRange { get; init; } public int HuntRange { get; init; } public int ReactionType { get; init; } public int Attribute { get; init; } public int Element { get; init; } public int Family1 { get; init; } public int Family2 { get; init; } public int Family3 { get; init; } public int ASValue { get; init; } public int ARValue { get; init; } public int ATValue { get; init; } public int BLValue { get; init; } public int CTValue { get; init; } public int DEValue { get; init; } public int DSValue { get; init; } public int EVValue { get; init; } public int HPValue { get; init; } public int HTValue { get; init; } public int MSValue { get; init; } public int WSValue { get; init; } public int Class { get; init; } } private sealed class RewardTemplate { public static RewardTemplate Empty { get; } = new(); public byte DropMinAmount { get; init; } public byte DropMaxAmount { get; init; } public long TamerExperience { get; init; } public long DigimonExperience { get; init; } public short NatureExperience { get; init; } public short ElementExperience { get; init; } public short SkillExperience { get; init; } public List ItemDrops { get; } = new(); public BitsDropTemplate? BitsDrop { get; set; } } private sealed class ItemDropTemplate { public int ItemId { get; init; } public int MinAmount { get; init; } public int MaxAmount { get; init; } public decimal Chance { get; init; } public int Rank { get; init; } } private sealed class BitsDropTemplate { public int MinAmount { get; init; } public int MaxAmount { get; init; } public decimal Chance { get; init; } } } }