224 lines
8.2 KiB
C#
224 lines
8.2 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
using Json.Schema;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace NeonSprawl.Server.Game.Encounters;
|
|
|
|
/// <summary>Loads and validates <c>content/encounters/*_encounters.json</c> using the same rules as <c>scripts/validate_content.py</c> (NEO-101).</summary>
|
|
public static class EncounterDefinitionCatalogLoader
|
|
{
|
|
/// <summary>Loads catalogs from disk or throws <see cref="InvalidOperationException"/> with actionable messages.</summary>
|
|
public static EncounterDefinitionCatalog Load(
|
|
string encountersDirectory,
|
|
string encounterDefSchemaPath,
|
|
IReadOnlySet<string> knownRewardTableIds,
|
|
ILogger logger)
|
|
{
|
|
encountersDirectory = Path.GetFullPath(encountersDirectory);
|
|
encounterDefSchemaPath = Path.GetFullPath(encounterDefSchemaPath);
|
|
|
|
var errors = new List<string>();
|
|
|
|
if (!File.Exists(encounterDefSchemaPath))
|
|
errors.Add($"error: missing schema file {encounterDefSchemaPath}");
|
|
|
|
if (!Directory.Exists(encountersDirectory))
|
|
errors.Add($"error: missing directory {encountersDirectory}");
|
|
|
|
if (errors.Count > 0)
|
|
ThrowIfAny(errors);
|
|
|
|
string[] jsonFiles = [.. Directory.GetFiles(encountersDirectory, "*_encounters.json", SearchOption.TopDirectoryOnly)
|
|
.OrderBy(p => p, StringComparer.Ordinal)];
|
|
if (jsonFiles.Length == 0)
|
|
errors.Add($"error: no *_encounters.json files under {encountersDirectory}");
|
|
|
|
if (errors.Count > 0)
|
|
ThrowIfAny(errors);
|
|
|
|
var schema = JsonSchema.FromText(File.ReadAllText(encounterDefSchemaPath));
|
|
var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List };
|
|
|
|
var encounterIdToSourceFile = new Dictionary<string, string>(StringComparer.Ordinal);
|
|
var rows = new Dictionary<string, EncounterDefRow>(StringComparer.Ordinal);
|
|
|
|
foreach (var path in jsonFiles)
|
|
{
|
|
JsonNode? root;
|
|
try
|
|
{
|
|
root = JsonNode.Parse(File.ReadAllText(path));
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
errors.Add($"error: {path}: invalid JSON: {ex.Message}");
|
|
continue;
|
|
}
|
|
|
|
if (root is not JsonObject rootObj)
|
|
{
|
|
errors.Add($"error: {path}: expected JSON object at root");
|
|
continue;
|
|
}
|
|
|
|
var schemaVersionNode = rootObj["schemaVersion"];
|
|
if (schemaVersionNode is not JsonValue schemaVersionValue ||
|
|
!schemaVersionValue.TryGetValue<int>(out var schemaVersion) ||
|
|
schemaVersion != 1)
|
|
{
|
|
var got = schemaVersionNode?.ToJsonString() ?? "null";
|
|
errors.Add($"error: {path}: expected schemaVersion 1, got {got}");
|
|
continue;
|
|
}
|
|
|
|
var encountersNode = rootObj["encounters"];
|
|
if (encountersNode is not JsonArray encountersArray)
|
|
{
|
|
errors.Add($"error: {path}: expected top-level 'encounters' array");
|
|
continue;
|
|
}
|
|
|
|
for (var i = 0; i < encountersArray.Count; i++)
|
|
{
|
|
var encounter = encountersArray[i];
|
|
if (encounter is not JsonObject rowObj)
|
|
{
|
|
errors.Add($"error: {path}: encounters[{i}] must be an object");
|
|
continue;
|
|
}
|
|
|
|
var eval = schema.Evaluate(rowObj, evalOptions);
|
|
var schemaMsgs = CollectSchemaMessages(eval, path, i).OrderBy(m => m, StringComparer.Ordinal).ToList();
|
|
if (!eval.IsValid)
|
|
{
|
|
if (schemaMsgs.Count == 0)
|
|
schemaMsgs.Add($"error: {path} encounters[{i}] (root): schema validation failed");
|
|
|
|
errors.AddRange(schemaMsgs);
|
|
}
|
|
|
|
var rowSchemaErrors = schemaMsgs.Count;
|
|
|
|
var eid = (rowObj["id"] as JsonValue)?.GetValue<string>();
|
|
if (eid is not null && rowSchemaErrors == 0)
|
|
{
|
|
if (encounterIdToSourceFile.TryGetValue(eid, out var prevPath))
|
|
{
|
|
errors.Add($"error: duplicate encounter id '{eid}' in {prevPath} and {path}");
|
|
continue;
|
|
}
|
|
|
|
encounterIdToSourceFile[eid] = path;
|
|
|
|
var rewardTableId = (rowObj["rewardTableId"] as JsonValue)?.GetValue<string>();
|
|
if (rewardTableId is not null && !knownRewardTableIds.Contains(rewardTableId))
|
|
{
|
|
errors.Add(
|
|
$"error: {path} encounters[{i}]: rewardTableId '{rewardTableId}' is not in reward table catalogs");
|
|
}
|
|
|
|
rows[eid] = ParseRow(rowObj);
|
|
}
|
|
}
|
|
}
|
|
|
|
ThrowIfAny(errors);
|
|
|
|
var e5m3 = PrototypeE5M3EncounterCatalogRules.TryGetE5M3GateError(encounterIdToSourceFile);
|
|
if (e5m3 is not null)
|
|
{
|
|
errors.Add(e5m3);
|
|
ThrowIfAny(errors);
|
|
}
|
|
|
|
var npcCrossRef = PrototypeE5M3EncounterCatalogRules.TryGetNpcInstanceCrossRefError(rows);
|
|
if (npcCrossRef is not null)
|
|
{
|
|
errors.Add(npcCrossRef);
|
|
ThrowIfAny(errors);
|
|
}
|
|
|
|
if (logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
logger.LogInformation(
|
|
"Loaded encounter catalog from {EncountersDirectory}: {EncounterCount} encounter(s) across {CatalogFileCount} JSON catalog file(s).",
|
|
encountersDirectory,
|
|
rows.Count,
|
|
jsonFiles.Length);
|
|
}
|
|
|
|
return new EncounterDefinitionCatalog(encountersDirectory, rows, jsonFiles.Length);
|
|
}
|
|
|
|
private static EncounterDefRow ParseRow(JsonObject rowObj)
|
|
{
|
|
var id = (rowObj["id"] as JsonValue)!.GetValue<string>();
|
|
var displayName = (rowObj["displayName"] as JsonValue)!.GetValue<string>();
|
|
var completionCriteria = rowObj["completionCriteria"] as JsonObject
|
|
?? throw new InvalidOperationException("expected completionCriteria object");
|
|
var completionCriteriaKind = (completionCriteria["kind"] as JsonValue)!.GetValue<string>();
|
|
var requiredNpcInstanceIds = ParseStringArray(rowObj["requiredNpcInstanceIds"] as JsonArray);
|
|
var rewardTableId = (rowObj["rewardTableId"] as JsonValue)!.GetValue<string>();
|
|
|
|
return new EncounterDefRow(id, displayName, completionCriteriaKind, requiredNpcInstanceIds, rewardTableId);
|
|
}
|
|
|
|
private static IReadOnlyList<string> ParseStringArray(JsonArray? array)
|
|
{
|
|
if (array is null)
|
|
return [];
|
|
|
|
var values = new List<string>(array.Count);
|
|
foreach (var node in array)
|
|
{
|
|
if (node is JsonValue value && value.TryGetValue<string>(out var s))
|
|
values.Add(s);
|
|
}
|
|
|
|
return values;
|
|
}
|
|
|
|
private static List<string> CollectSchemaMessages(EvaluationResults eval, string filePath, int index)
|
|
{
|
|
var sink = new List<string>();
|
|
AppendSchemaMessages(eval, filePath, index, sink);
|
|
return sink;
|
|
}
|
|
|
|
private static void AppendSchemaMessages(EvaluationResults r, string filePath, int index, List<string> sink)
|
|
{
|
|
if (r.HasDetails)
|
|
{
|
|
foreach (var d in r.Details!)
|
|
AppendSchemaMessages(d, filePath, index, sink);
|
|
}
|
|
|
|
if (!r.HasErrors)
|
|
return;
|
|
|
|
foreach (var kv in r.Errors!)
|
|
{
|
|
var loc = r.InstanceLocation?.ToString();
|
|
if (string.IsNullOrEmpty(loc) || loc == "#")
|
|
loc = "(root)";
|
|
|
|
sink.Add($"error: {filePath} encounters[{index}] {loc}: {kv.Key} — {kv.Value}");
|
|
}
|
|
}
|
|
|
|
private static void ThrowIfAny(List<string> errors)
|
|
{
|
|
if (errors.Count == 0)
|
|
return;
|
|
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine("Encounter catalog validation failed:");
|
|
foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal))
|
|
sb.AppendLine(e);
|
|
|
|
throw new InvalidOperationException(sb.ToString().TrimEnd());
|
|
}
|
|
}
|