Questionable/QuestPathGenerator/QuestSourceGenerator.cs

336 lines
19 KiB
C#
Raw Permalink Normal View History

2024-06-14 09:37:33 +00:00
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
2024-06-14 09:37:33 +00:00
using System.IO;
using System.Linq;
using System.Text.Json;
using Json.Schema;
2024-06-14 09:37:33 +00:00
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
2024-08-02 16:30:21 +00:00
using Questionable.Model.Questing;
2024-06-14 09:37:33 +00:00
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Questionable.QuestPathGenerator.RoslynShortcuts;
namespace Questionable.QuestPathGenerator;
/// <summary>
/// A sample source generator that creates C# classes based on the text file (in this case, Domain Driven Design ubiquitous language registry).
/// When using a simple text file as a baseline, we can create a non-incremental source generator.
/// </summary>
[Generator]
[SuppressMessage("MicrosoftCodeAnalysisReleaseTracking", "RS2008")]
2024-06-14 09:37:33 +00:00
public class QuestSourceGenerator : ISourceGenerator
{
private static readonly DiagnosticDescriptor InvalidJson = new("QSG0001",
"Invalid JSON",
"Invalid quest file {0}",
nameof(QuestSourceGenerator),
DiagnosticSeverity.Error,
true);
2024-06-14 09:37:33 +00:00
public void Initialize(GeneratorInitializationContext context)
{
// No initialization required for this generator.
}
public void Execute(GeneratorExecutionContext context)
{
// Find schema definition
2024-08-02 16:30:21 +00:00
AdditionalText? questSchema =
context.AdditionalFiles.SingleOrDefault(x => Path.GetFileName(x.Path) == "quest-v1.json");
if (questSchema != null)
GenerateQuestSource(context, questSchema);
}
private void GenerateQuestSource(GeneratorExecutionContext context, AdditionalText jsonSchemaFile)
{
var questSchema = JsonSchema.FromText(jsonSchemaFile.GetText()!.ToString());
2024-08-02 16:30:21 +00:00
List<(ushort, QuestRoot)> quests = [];
foreach (var (id, node) in Utils.GetAdditionalFiles(context, jsonSchemaFile, questSchema, InvalidJson))
2024-06-14 09:37:33 +00:00
{
2024-08-02 16:30:21 +00:00
var quest = node.Deserialize<QuestRoot>()!;
if (quest.Disabled)
{
quest.Author = [];
quest.QuestSequence = [];
quest.TerritoryBlacklist = [];
}
2024-06-14 09:37:33 +00:00
quests.Add((id, quest));
}
if (quests.Count == 0)
return;
var partitionedQuests = quests
.OrderBy(x => x.Item1)
.GroupBy(x => $"LoadQuests{x.Item1 / 50}")
.ToList();
2024-08-02 16:30:21 +00:00
var methods = Utils.CreateMethods("LoadQuests", partitionedQuests, CreateInitializer);
2024-06-14 09:37:33 +00:00
var code =
CompilationUnit()
.WithUsings(
List(
new[]
{
UsingDirective(
IdentifierName("System")),
UsingDirective(
QualifiedName(
IdentifierName("System"),
IdentifierName("Numerics"))),
UsingDirective(
QualifiedName(
IdentifierName("System"),
IdentifierName("IO"))),
UsingDirective(
QualifiedName(
QualifiedName(
IdentifierName("System"), IdentifierName("Collections")),
IdentifierName("Generic"))),
UsingDirective(
QualifiedName(
QualifiedName(
IdentifierName("Questionable"),
IdentifierName("Model")),
2024-08-02 16:30:21 +00:00
IdentifierName("Questing"))),
UsingDirective(
QualifiedName(
QualifiedName(
IdentifierName("Questionable"),
IdentifierName("Model")),
IdentifierName("Common")))
2024-06-14 09:37:33 +00:00
}))
.WithMembers(
SingletonList<MemberDeclarationSyntax>(
FileScopedNamespaceDeclaration(
QualifiedName(
IdentifierName("Questionable"),
IdentifierName("QuestPaths")))
.WithMembers(
SingletonList<MemberDeclarationSyntax>(
ClassDeclaration("AssemblyQuestLoader")
.WithModifiers(
TokenList(Token(SyntaxKind.PartialKeyword)))
.WithMembers(List<MemberDeclarationSyntax>(methods))))))
2024-06-14 09:37:33 +00:00
.NormalizeWhitespace();
// Add the source code to the compilation.
context.AddSource("AssemblyQuestLoader.g.cs", code.ToFullString());
}
private static StatementSyntax[] CreateInitializer(List<(ushort QuestId, QuestRoot Root)> quests)
{
List<StatementSyntax> statements = [];
foreach (var quest in quests)
{
statements.Add(
ExpressionStatement(
InvocationExpression(
IdentifierName("AddQuest"))
.WithArgumentList(
ArgumentList(
SeparatedList<ArgumentSyntax>(
new SyntaxNodeOrToken[]
{
Argument(
LiteralExpression(SyntaxKind.NumericLiteralExpression,
Literal(quest.QuestId))),
Token(SyntaxKind.CommaToken),
Argument(CreateQuestRootExpression(quest.QuestId, quest.Root))
})))));
}
return statements.ToArray();
}
private static ObjectCreationExpressionSyntax CreateQuestRootExpression(ushort questId, QuestRoot quest)
2024-06-14 09:37:33 +00:00
{
2024-07-21 21:10:16 +00:00
try
2024-06-14 09:37:33 +00:00
{
return ObjectCreationExpression(
IdentifierName(nameof(QuestRoot)))
.WithInitializer(
InitializerExpression(
SyntaxKind.ObjectInitializerExpression,
SeparatedList<ExpressionSyntax>(
SyntaxNodeList(
AssignmentList(nameof(QuestRoot.Author), quest.Author)
.AsSyntaxNodeOrToken(),
2024-08-03 18:30:18 +00:00
Assignment(nameof(QuestRoot.Disabled), quest.Disabled, false).AsSyntaxNodeOrToken(),
Assignment(nameof(QuestRoot.Comment), quest.Comment, null)
.AsSyntaxNodeOrToken(),
AssignmentList(nameof(QuestRoot.TerritoryBlacklist),
quest.TerritoryBlacklist).AsSyntaxNodeOrToken(),
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(nameof(QuestRoot.QuestSequence)),
CreateQuestSequence(quest.QuestSequence))))));
2024-07-21 21:10:16 +00:00
}
catch (Exception e)
{
throw new Exception($"QuestGen[{questId}]: {e.Message}", e);
}
2024-06-14 09:37:33 +00:00
}
private static ExpressionSyntax CreateQuestSequence(List<QuestSequence> sequences)
{
return CollectionExpression(
SeparatedList<CollectionElementSyntax>(
sequences.SelectMany(sequence => new SyntaxNodeOrToken[]
{
ExpressionElement(
ObjectCreationExpression(
IdentifierName(nameof(QuestSequence)))
.WithInitializer(
InitializerExpression(
SyntaxKind.ObjectInitializerExpression,
SeparatedList<ExpressionSyntax>(
SyntaxNodeList(
Assignment<int?>(nameof(QuestSequence.Sequence), sequence.Sequence, null)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestSequence.Comment), sequence.Comment, null)
.AsSyntaxNodeOrToken(),
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(nameof(QuestSequence.Steps)),
CreateQuestSteps(sequence.Steps))))))),
Token(SyntaxKind.CommaToken),
}.ToArray())));
}
private static ExpressionSyntax CreateQuestSteps(List<QuestStep> steps)
{
QuestStep emptyStep = new();
return CollectionExpression(
SeparatedList<CollectionElementSyntax>(
steps.SelectMany(step => new SyntaxNodeOrToken[]
{
ExpressionElement(
ObjectCreationExpression(
IdentifierName(nameof(QuestStep)))
.WithArgumentList(
ArgumentList(
SeparatedList<ArgumentSyntax>(
new SyntaxNodeOrToken[]
{
Argument(LiteralValue(step.InteractionType)),
Token(SyntaxKind.CommaToken),
Argument(LiteralValue(step.DataId)),
Token(SyntaxKind.CommaToken),
Argument(LiteralValue(step.Position)),
Token(SyntaxKind.CommaToken),
Argument(LiteralValue(step.TerritoryId))
})))
.WithInitializer(
InitializerExpression(
SyntaxKind.ObjectInitializerExpression,
SeparatedList<ExpressionSyntax>(
SyntaxNodeList(
Assignment(nameof(QuestStep.StopDistance), step.StopDistance,
emptyStep.StopDistance)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.NpcWaitDistance), step.NpcWaitDistance,
emptyStep.NpcWaitDistance)
.AsSyntaxNodeOrToken(),
2024-06-14 09:37:33 +00:00
Assignment(nameof(QuestStep.TargetTerritoryId), step.TargetTerritoryId,
emptyStep.TargetTerritoryId)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.DelaySecondsAtStart), step.DelaySecondsAtStart,
emptyStep.DelaySecondsAtStart)
.AsSyntaxNodeOrToken(),
2024-06-14 09:37:33 +00:00
Assignment(nameof(QuestStep.Disabled), step.Disabled, emptyStep.Disabled)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.DisableNavmesh), step.DisableNavmesh,
emptyStep.DisableNavmesh)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.Mount), step.Mount, emptyStep.Mount)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.Fly), step.Fly, emptyStep.Fly)
.AsSyntaxNodeOrToken(),
2024-07-12 21:58:48 +00:00
Assignment(nameof(QuestStep.Land), step.Land, emptyStep.Land)
.AsSyntaxNodeOrToken(),
2024-06-14 09:37:33 +00:00
Assignment(nameof(QuestStep.Sprint), step.Sprint, emptyStep.Sprint)
.AsSyntaxNodeOrToken(),
2024-07-21 21:10:16 +00:00
Assignment(nameof(QuestStep.IgnoreDistanceToObject),
step.IgnoreDistanceToObject, emptyStep.IgnoreDistanceToObject)
.AsSyntaxNodeOrToken(),
2024-06-14 09:37:33 +00:00
Assignment(nameof(QuestStep.Comment), step.Comment, emptyStep.Comment)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.Aetheryte), step.Aetheryte, emptyStep.Aetheryte)
.AsSyntaxNodeOrToken(),
2024-07-21 21:10:16 +00:00
Assignment(nameof(QuestStep.AethernetShard), step.AethernetShard,
emptyStep.AethernetShard)
.AsSyntaxNodeOrToken(),
2024-06-14 09:37:33 +00:00
Assignment(nameof(QuestStep.AetheryteShortcut), step.AetheryteShortcut,
emptyStep.AetheryteShortcut)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.AethernetShortcut), step.AethernetShortcut,
emptyStep.AethernetShortcut)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.AetherCurrentId), step.AetherCurrentId,
emptyStep.AetherCurrentId)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.ItemId), step.ItemId, emptyStep.ItemId)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.GroundTarget), step.GroundTarget,
emptyStep.GroundTarget)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.Emote), step.Emote, emptyStep.Emote)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.ChatMessage), step.ChatMessage,
emptyStep.ChatMessage)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.Action), step.Action, emptyStep.Action)
.AsSyntaxNodeOrToken(),
2024-06-14 09:37:33 +00:00
Assignment(nameof(QuestStep.EnemySpawnType), step.EnemySpawnType,
emptyStep.EnemySpawnType)
.AsSyntaxNodeOrToken(),
AssignmentList(nameof(QuestStep.KillEnemyDataIds), step.KillEnemyDataIds)
.AsSyntaxNodeOrToken(),
2024-07-14 20:17:35 +00:00
AssignmentList(nameof(QuestStep.ComplexCombatData), step.ComplexCombatData)
.AsSyntaxNodeOrToken(),
2024-07-21 21:10:16 +00:00
Assignment(nameof(QuestStep.CombatDelaySecondsAtStart),
step.CombatDelaySecondsAtStart,
emptyStep.CombatDelaySecondsAtStart)
.AsSyntaxNodeOrToken(),
2024-06-14 09:37:33 +00:00
Assignment(nameof(QuestStep.JumpDestination), step.JumpDestination,
emptyStep.JumpDestination)
.AsSyntaxNodeOrToken(),
Assignment(nameof(QuestStep.ContentFinderConditionId),
step.ContentFinderConditionId, emptyStep.ContentFinderConditionId)
.AsSyntaxNodeOrToken(),
2024-08-03 18:30:18 +00:00
Assignment(nameof(QuestStep.SkipConditions), step.SkipConditions,
emptyStep.SkipConditions)
2024-06-14 09:37:33 +00:00
.AsSyntaxNodeOrToken(),
2024-07-20 19:23:54 +00:00
AssignmentList(nameof(QuestStep.RequiredQuestVariables),
step.RequiredQuestVariables)
.AsSyntaxNodeOrToken(),
2024-08-03 20:17:18 +00:00
AssignmentList(nameof(QuestStep.RequiredGatheredItems),
step.RequiredGatheredItems),
2024-06-14 09:37:33 +00:00
AssignmentList(nameof(QuestStep.CompletionQuestVariablesFlags),
step.CompletionQuestVariablesFlags)
.AsSyntaxNodeOrToken(),
AssignmentList(nameof(QuestStep.DialogueChoices), step.DialogueChoices)
.AsSyntaxNodeOrToken(),
AssignmentList(nameof(QuestStep.PointMenuChoices), step.PointMenuChoices)
.AsSyntaxNodeOrToken(),
2024-07-21 21:10:16 +00:00
Assignment(nameof(QuestStep.PickUpQuestId), step.PickUpQuestId,
emptyStep.PickUpQuestId)
.AsSyntaxNodeOrToken(),
2024-07-21 21:10:16 +00:00
Assignment(nameof(QuestStep.TurnInQuestId), step.TurnInQuestId,
emptyStep.TurnInQuestId)
.AsSyntaxNodeOrToken(),
2024-07-21 21:10:16 +00:00
Assignment(nameof(QuestStep.NextQuestId), step.NextQuestId,
emptyStep.NextQuestId)
2024-06-14 09:37:33 +00:00
.AsSyntaxNodeOrToken()))))),
Token(SyntaxKind.CommaToken),
}.ToArray())));
}
}