using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class SceneProfileSummary { public int SceneCount { get; init; } public int UsedSceneCount { get; init; } public int SkippableSceneCount { get; init; } public int ActionCount { get; init; } public int SceneTargetCount { get; init; } public int DistinctMapCount { get; init; } public int DistinctReferencedTargetCount { get; init; } public int MissingSceneTargetReferenceCount { get; init; } public int MissingAssetMapCount { get; init; } public int ActionWithEffectCount { get; init; } public int ActionWithSoundCount { get; init; } public int DuplicateSceneIdCount { get; init; } public int DuplicateSceneTargetUidCount { get; init; } public string SceneIdRange { get; init; } = string.Empty; } public static class SceneProfileInspector { private const int ExpectedActionTargetCount = 5; public static SceneProfileSummary ValidatePackage(string sceneDataXmlPath) { ScenePackage package = LoadPackage(sceneDataXmlPath); return BuildSummary(package, missingAssetMapCount: 0); } public static SceneProfileSummary AssessDatabase(string connectionString, string sceneDataXmlPath) { ScenePackage package = LoadPackage(sceneDataXmlPath); using SqlConnection connection = new(connectionString); connection.Open(); HashSet assetMapIds = ReadIntSet(connection, "SELECT [MapId] FROM [Asset].[Map];"); int missingAssetMapCount = package.Scenes .Where(x => x.MapId > 0) .Select(x => x.MapId) .Distinct() .Count(x => !assetMapIds.Contains(x)); return BuildSummary(package, missingAssetMapCount); } private static SceneProfileSummary BuildSummary(ScenePackage package, int missingAssetMapCount) { HashSet targetUids = package.Targets.Select(x => x.Uid).ToHashSet(); List referencedTargets = package.Actions .SelectMany(x => x.TargetIds.Append(x.MainTargetId)) .Where(x => x != 0) .Distinct() .ToList(); uint minSceneId = package.Scenes.Count == 0 ? 0 : package.Scenes.Min(x => x.SceneId); uint maxSceneId = package.Scenes.Count == 0 ? 0 : package.Scenes.Max(x => x.SceneId); return new SceneProfileSummary { SceneCount = package.Scenes.Count, UsedSceneCount = package.Scenes.Count(x => x.IsUsed), SkippableSceneCount = package.Scenes.Count(x => x.IsSkippable), ActionCount = package.Actions.Count, SceneTargetCount = package.Targets.Count, DistinctMapCount = package.Scenes.Where(x => x.MapId > 0).Select(x => x.MapId).Distinct().Count(), DistinctReferencedTargetCount = referencedTargets.Count, MissingSceneTargetReferenceCount = referencedTargets.Count(x => !targetUids.Contains(x)), MissingAssetMapCount = missingAssetMapCount, ActionWithEffectCount = package.Actions.Count(x => !string.IsNullOrWhiteSpace(x.Effect)), ActionWithSoundCount = package.Actions.Count(x => !string.IsNullOrWhiteSpace(x.Sound)), DuplicateSceneIdCount = CountDuplicates(package.Scenes.Select(x => x.SceneId)), DuplicateSceneTargetUidCount = CountDuplicates(package.Targets.Select(x => x.Uid)), SceneIdRange = $"{minSceneId} to {maxSceneId}" }; } private static ScenePackage LoadPackage(string sceneDataXmlPath) { if (!File.Exists(sceneDataXmlPath)) { throw new FileNotFoundException("SceneData.xml not found.", sceneDataXmlPath); } string packageDirectory = Path.GetDirectoryName(sceneDataXmlPath) ?? throw new InvalidOperationException("Scene package path does not have a directory."); string sceneTargetsXmlPath = Path.Combine(packageDirectory, "SceneTargets.xml"); if (!File.Exists(sceneTargetsXmlPath)) { throw new FileNotFoundException("SceneTargets.xml not found.", sceneTargetsXmlPath); } List scenes = LoadScenes(sceneDataXmlPath, out List actions); List targets = LoadTargets(sceneTargetsXmlPath); if (scenes.Count == 0) { throw new InvalidOperationException("SceneData.xml does not contain any rows."); } if (targets.Count == 0) { throw new InvalidOperationException("SceneTargets.xml does not contain any rows."); } return new ScenePackage(scenes, actions, targets); } private static List LoadScenes(string sceneDataXmlPath, out List actions) { XElement root = LoadRequiredRoot(sceneDataXmlPath, "SceneDataTable"); XElement scenesElement = root.Element("Scenes") ?? throw new InvalidOperationException("SceneData.xml is missing the node."); List scenes = new(); actions = new List(); int sceneRow = 0; foreach (XElement sceneElement in scenesElement.Elements("SceneData")) { sceneRow++; string sceneContext = $"SceneData row {sceneRow}"; uint sceneId = ReadRequiredUInt(sceneElement, "s_dwSceneID", sceneContext); int mapId = ReadRequiredInt(sceneElement, "s_nMap", sceneContext); _ = ReadRequiredInt(sceneElement, "s_nResion", sceneContext); bool isUsed = ReadRequiredBool(sceneElement, "s_bUse", sceneContext); bool isSkippable = ReadRequiredBool(sceneElement, "s_bSkip", sceneContext); string title = ReadRequiredString(sceneElement, "s_szTitle", sceneContext); _ = ReadRequiredString(sceneElement, "s_szMusic", sceneContext); if (sceneId == 0) { throw new InvalidOperationException($"{sceneContext} has invalid s_dwSceneID value: '0'."); } if (title.Length == 0) { throw new InvalidOperationException($"{sceneContext} has empty required s_szTitle."); } XElement actionsElement = sceneElement.Element("Actions") ?? throw new InvalidOperationException($"{sceneContext} is missing the node."); int actionRow = 0; foreach (XElement actionElement in actionsElement.Elements("Action")) { actionRow++; string actionContext = $"{sceneContext} Action row {actionRow}"; uint mainTargetId = ReadRequiredUInt(actionElement, "s_dwMainTarget", actionContext); uint animationId = ReadRequiredUInt(actionElement, "s_dwAni", actionContext); string talk = ReadRequiredString(actionElement, "s_szTalk", actionContext); string effect = ReadRequiredString(actionElement, "s_szEffect", actionContext); string sound = ReadRequiredString(actionElement, "s_szSound", actionContext); XElement targetsElement = actionElement.Element("Targets") ?? throw new InvalidOperationException($"{actionContext} is missing the node."); List targetElements = targetsElement.Elements("Target").ToList(); if (targetElements.Count != ExpectedActionTargetCount) { throw new InvalidOperationException($"{actionContext} must contain exactly {ExpectedActionTargetCount} rows, but contains {targetElements.Count}."); } uint[] targetIds = new uint[ExpectedActionTargetCount]; foreach (XElement targetElement in targetElements) { int index = ReadRequiredIntAttribute(targetElement, "Index", actionContext); if (index < 1 || index > ExpectedActionTargetCount) { throw new InvalidOperationException($"{actionContext} has out-of-range Target Index value: '{index}'."); } targetIds[index - 1] = ParseUInt(targetElement.Value, $"{actionContext} Target {index}"); } actions.Add(new SceneActionRecord(sceneId, mainTargetId, targetIds, animationId, talk, effect, sound)); } scenes.Add(new SceneRecord(sceneId, isUsed, isSkippable, mapId)); } return scenes; } private static List LoadTargets(string sceneTargetsXmlPath) { XElement root = LoadRequiredRoot(sceneTargetsXmlPath, "SceneTargetTable"); XElement targetsElement = root.Element("Targets") ?? throw new InvalidOperationException("SceneTargets.xml is missing the node."); List targets = new(); int targetRow = 0; foreach (XElement targetElement in targetsElement.Elements("SceneTarget")) { targetRow++; string targetContext = $"SceneTarget row {targetRow}"; uint uid = ReadRequiredUInt(targetElement, "s_dwUID", targetContext); _ = ReadRequiredUInt(targetElement, "s_dwModelID", targetContext); _ = ReadRequiredFloat(targetElement, "s_fDist", targetContext); _ = ReadRequiredFloat(targetElement, "s_fHeight", targetContext); _ = ReadRequiredString(targetElement, "s_szName", targetContext); if (uid == 0) { throw new InvalidOperationException($"{targetContext} has invalid s_dwUID value: '0'."); } targets.Add(new SceneTargetRecord(uid)); } return targets; } private static XElement LoadRequiredRoot(string xmlPath, string expectedRootName) { XDocument document = XDocument.Load(xmlPath); XElement root = document.Root ?? throw new InvalidOperationException($"{Path.GetFileName(xmlPath)} is missing a root node."); if (root.Name.LocalName != expectedRootName) { throw new InvalidOperationException($"{Path.GetFileName(xmlPath)} root node must be <{expectedRootName}>."); } return root; } 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 uint ReadRequiredUInt(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } return ParseUInt(element.Value, $"{recordContext} {elementName}"); } private static float ReadRequiredFloat(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!float.TryParse(element.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float value)) { throw new InvalidOperationException($"{recordContext} has invalid float value in '{elementName}': '{element.Value}'."); } return value; } private static bool ReadRequiredBool(XElement parent, string elementName, string recordContext) { int value = ReadRequiredInt(parent, elementName, recordContext); if (value is not 0 and not 1) { throw new InvalidOperationException($"{recordContext} has invalid bool value in '{elementName}': '{value}'."); } return value == 1; } private static string ReadRequiredString(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } return element.Value; } private static int ReadRequiredIntAttribute(XElement element, string attributeName, string recordContext) { XAttribute? attribute = element.Attribute(attributeName); if (attribute == null) { throw new InvalidOperationException($"{recordContext} is missing required Target '{attributeName}' attribute."); } if (!int.TryParse(attribute.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { throw new InvalidOperationException($"{recordContext} has invalid Target '{attributeName}' attribute value: '{attribute.Value}'."); } return value; } private static uint ParseUInt(string value, string recordContext) { if (!uint.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out uint result)) { throw new InvalidOperationException($"{recordContext} has invalid unsigned integer value: '{value}'."); } return result; } 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 int CountDuplicates(IEnumerable values) where T : notnull { return values.GroupBy(x => x).Where(x => x.Count() > 1).Sum(x => x.Count() - 1); } private sealed record ScenePackage(List Scenes, List Actions, List Targets); private sealed record SceneRecord(uint SceneId, bool IsUsed, bool IsSkippable, int MapId); private sealed record SceneActionRecord(uint SceneId, uint MainTargetId, uint[] TargetIds, uint AnimationId, string Talk, string Effect, string Sound); private sealed record SceneTargetRecord(uint Uid); } }